-2

I have a simple for loop that asks a user to enter an integer 10 times. How can I add these inputs to an array without having to make 10 separate variables?

Scanner scan = new Scanner(System.in);
    for (int i = 1; i<= 10; i++) {
        System.out.println("Please enter an Integer:");
        scan.nextInt();
    }
}

Example Inputs: 10, 1, 3, 25, 33, 26, 12, 0, 7, 18

Desired Output: myArray = [10, 1, 3, 25, 33, 26, 12, 0, 7, 18]

Brewsta
  • 1
  • 3
  • 2
    Possible duplicate of [How do I declare and initialize an array in Java?](https://stackoverflow.com/questions/1200621/how-do-i-declare-and-initialize-an-array-in-java) – Tripp Kinetics Apr 05 '18 at 21:11
  • https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html – shmosel Apr 05 '18 at 21:15

3 Answers3

0

Something like this maybe?

    Scanner scan = new Scanner(System.in);
    int [] input_nums = new int [10];

    for (int i = 1; i<= 10; i++) {
        System.out.println("Please enter an Integer:");
        int a = scan.nextInt();
        input_nums[i] = a;
    }
}
ninesalt
  • 2,968
  • 3
  • 23
  • 49
0

Use this: This is assuming there will always be 10 numbers that you need to input

 public void test5(){
    Scanner scan = new Scanner(System.in);
    int[] arr = new int[10];
    for (int i = 0; i< 10; i++) {
        System.out.println("Please enter an Integer:");
        arr[i]=scan.nextInt();
    }
    scan.close();
    //To check array output
    for(int a:arr){
      System.out.println(a);
    }
}

If you want to make it more dynamic(array size not known beforehand) you can try this:

public void test6(){
    Scanner scan = new Scanner(System.in);
    System.out.println("Please enter Integers(in a single line separated by space):");

    int[] intArr = null;
    if(scan.hasNext()){
        String line = scan.nextLine();
        intArr = Arrays.stream(line.split("\\s+")).mapToInt(Integer::parseInt).toArray();
    }
    scan.close();
    for(int a: intArr) {
        System.out.println(a);
    }
}
humblefoolish
  • 389
  • 3
  • 14
0

Using ArrayList:

Scanner scan = new Scanner(System.in);
ArrayList array = new ArrayList();
for (int i = 1; i<= 10; i++) {
    System.out.println("Please enter an Integer:");
    int number = scan.nextInt();
    array.add(number);
}
L.B
  • 88
  • 3