如
int a[]={13,2,4,5,40,0,56,0,5,0,0,0};
我想去除0怎么编写?
public class Test {
private int a[] = {13,2,4,5,40,0,56,0,5,0,0,0};//数组初始值
private int newlength=0;
public void delete(int n){//删除数组中n的值
for (int i = 0; i < a.length; i++) {
if(a[i] == n){
for(int j = i; j < a.length-1; j++){
a[j] = a[j+1];
}
newlength++;
}
}
}
public void print(){//打印数组
for (int i = 0; i < newlength; i++) {
System.out.println (a[i]);
}
}
public static void main(String[] args) {
Test t = new Test();
t.delete(0);
t.print();
}
}
private int a[] = {13,2,4,5,40,0,56,0,5,0,0,0};//数组初始值
private int newlength=0;
public void delete(int n){//删除数组中n的值
for (int i = 0; i < a.length; i++) {
if(a[i] == n){
for(int j = i; j < a.length-1; j++){
a[j] = a[j+1];
}
newlength++;
}
}
}
public void print(){//打印数组
for (int i = 0; i < newlength; i++) {
System.out.println (a[i]);
}
}
public static void main(String[] args) {
Test t = new Test();
t.delete(0);
t.print();
}
}
温馨提示:答案为网友推荐,仅供参考
第1个回答 2014-12-24
int b[];
for (int i = 0; i < a.lenght; i++) {
if (a[i] == 0) {
continue;
}
b[i] = a[i]
}
for (int i = 0; i < a.lenght; i++) {
if (a[i] == 0) {
continue;
}
b[i] = a[i]
}
第2个回答 2017-08-12
int[] a = { 13,2,4,5,40,0,56,0,5,0,0,0};
int temp = 0;
int[] arr=new int[a.length];//定义中间数组接收去除0剩下的元素
for (int i = 0; i < a.length; i++) {
if (a[i] != 0) {
arr[temp] = a[i];
temp++;
}
}
int[] arr2=new int[temp];//定义新的数组把中间数组缩减
for (int j = 0; j < temp; j++) {
arr2[j]=arr[j];
}
System.out.println(Arrays.toString(arr2));//输出新数组
我是新手,但我写出来了,网上有些回答我实在看不下去,答非所问,请你们别浪费时间!
int temp = 0;
int[] arr=new int[a.length];//定义中间数组接收去除0剩下的元素
for (int i = 0; i < a.length; i++) {
if (a[i] != 0) {
arr[temp] = a[i];
temp++;
}
}
int[] arr2=new int[temp];//定义新的数组把中间数组缩减
for (int j = 0; j < temp; j++) {
arr2[j]=arr[j];
}
System.out.println(Arrays.toString(arr2));//输出新数组
我是新手,但我写出来了,网上有些回答我实在看不下去,答非所问,请你们别浪费时间!
第3个回答 推荐于2017-10-13
import java.util.ArrayList;
public class RemoveZero
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
Integer a[]={13,2,4,5,40,0,56,0,5,0,0,0};
ArrayList array = new ArrayList();
for(int i = 0; i < a.length; i++){
array.add(a[i]);
}
while(array.remove(new Integer(0))){
};
Object[] array2 = array.toArray();
for(int i = 0; i < array2.length; i++){
System.out.println(array2[i]);
}
}
}
想了好久一个一个移除应该是效率比较低的追问
public class RemoveZero
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
Integer a[]={13,2,4,5,40,0,56,0,5,0,0,0};
ArrayList array = new ArrayList();
for(int i = 0; i < a.length; i++){
array.add(a[i]);
}
while(array.remove(new Integer(0))){
};
Object[] array2 = array.toArray();
for(int i = 0; i < array2.length; i++){
System.out.println(array2[i]);
}
}
}
想了好久一个一个移除应该是效率比较低的追问
如果要是有几千个元素那不就成体力工了?
追答这样操作很复杂吗?反正是计算机的事情
本回答被提问者和网友采纳