开发者

printing all the array value

开发者 https://www.devze.com 2023-01-24 23:28 出处:网络
class ArrayApp{ public static void main(final String[] args){ long [] a开发者_JAVA技巧rr; arr= new long[100];
class ArrayApp{

    public static void main(final String[] args){

     long [] a开发者_JAVA技巧rr; 
     arr= new long[100];
     int i;
     arr[0]=112;
     arr[1]=111;
     for(i=0;i<arr;i++) {
     System.out.println(arr[i]);
     }

  } 
} 

I get this error,

ArrayApp.java:10: operator < cannot be applied to int,long[]
        for(i=0;i<arr;i++) {
                 ^


You need to use the size of the array, which would be arr.length.

for (int i = 0; i < arr.length; ++i)

As of Java 1.5, you can also use the for each loop if you just need access to the array data.

for ( long l : arr )
{
    System.out.println(l);
}


arr is an object of long[] , you can't compare int with it.

Try arr.length

Alternatively You should go for

for(long item:arr){
System.out.println(item);
}


You want arr.length


The question has to be seen in the context of a previous question!

From this former question I remember that you actually have a logical array inside a physical array. The last element of the logical array is not arr.length but 2, because you've "added" two values to the logical array.

In this case, you can't use array.length for the iteration but again need another variable that store the actual position of "the last value" (1, in your case):

long[] arr; 
arr= new long[100];
int i;
arr[0]=112;
arr[1]=111;
int nElem = 2;  // you added 2 values to your "logical" array
for(i=0; i<=nElem; i++) {  
  System.out.println(arr[i]);
}

Note - I guess, you're actually learning the Java language and/or programming. Later on you'll find it much easier to not use arrays for this task but List objects. An equaivalent with List will look like this:

List<Integer> values = new ArrayList<Integer>();
values.add(112);
values.add(111);
for (Integer value:values)
  System.out.println(value);


Long arr = new Long[100];
 arr[0]=112;
 arr[1]=111;
for(int i=0;i<arr.length;i++) {
  if (arr[i] != null ) {
    System.out.println(arr[i]);
  }
}

if you want to show only those which are filled.


You can solve your problem using one line of code: Arrays.asList(arr).toString().replace("[", "").replace("]", "").replace(", ", "\n");

See http://java.dzone.com/articles/useful-abuse for more similar tricks.

0

精彩评论

暂无评论...
验证码 换一张
取 消