Array Printing Java

后端 未结 3 1533
面向向阳花
面向向阳花 2021-01-28 12:05

Basically I want my code to enable the user to enter x amount of integers (they chose x), then they will then store each of their inputted integer values in my array.

Fo

相关标签:
3条回答
  • 2021-01-28 12:18

    Ok, you can take away the for loop and do it this way

    System.out.println(Arrays.toString(myArray));
    

    I would strongly recommend to do it with the for loop. It prints one element at the time every time the loop runs, and with your for loop it runs through every element. You need to change the println to this (inside you for loop)

    System.out.println(myArray[counter]);
    

    or if you want to have the array on the same line

    System.out.print(myArray[counter]+ " ");
    

    Later on when programming you are going to see how useful this is compared to Arrays.toString() method.

    0 讨论(0)
  • 2021-01-28 12:18

    You can also use java.util.ArrayList

    ArrayList<Integer> myArray = new ArrayList<Integer>(amount);
    
    for (int counter = 0; counter < amount; counter ++){
     myArray.add(counter,input.nextInt());
    }
    System.out.println(myArray);
    

    prints array like this -> [1, 2, 3, 4]

    0 讨论(0)
  • 2021-01-28 12:27

    The string you get is the object notation of array which is expected [I@55f96302 where

    • [I is the class name
      • [ one dimentional array
      • I integer array
    • @ joins the string
    • 55f96302 some hash code

    To print array do

    System.out.println(Arrays.toString(myArray));
    

    or you can simply loop through each element of array

    0 讨论(0)
提交回复
热议问题