How can I store numbers into array every time I input a new number from keyboard (java)?

34,800

Solution 1

Scanner input = new Scanner(System.in);
          ArrayList<Integer> al = new ArrayList<Integer>();

            int check=0;
            while(true){
                check = input.nextInt();
                if(check == 0) break;
                al.add(check);

            }

            for (int i : al) {
                System.out.print(i);
            }


}

That's what I did. When user enters "0", it breaks.

Solution 2

A while() loop involving the Scanner object would be beneficial. You don't need to reinitialize/redeclare it every time through the loop.

import java.util.Scanner;
public class smth {
    final int SIZE = 10; // You need to define a size.
    Scanner input = new Scanner(System.in);
    int array[]= new int[SIZE];

    public void readFromTerminal() {
        System.out.println("Read lines, please enter some other character to stop.");
        String in = input.nextLine();
        while ( ) { } // I encourage you to fill in the blanks!
    }
}

[EDIT] If you want the user to be able to enter an "unlimited" number of integers, then an ArrayList<Integer> would be more ideal.

import java.util.Scanner;
public class smth {
    Scanner input = new Scanner(System.in);
    ArrayList<Integer> array = new ArrayList<Integer>(); //  Please reference the documentation to see why I'm using the Integer wrapper class, and not a standard int.

    public void readFromTerminal() {
        System.out.println("Read lines, please enter some other character to stop.");
        String in = input.nextLine();
        while ( ) { } // I encourage you to fill in the blanks!
    }
}
Share:
34,800
gtboy
Author by

gtboy

Updated on December 03, 2020

Comments

  • gtboy
    gtboy over 3 years
    import java.util.Scanner;
    public class smth {
          Scanner input = new Scanner(System.in);
          int array[]={};
    
    }
    

    what can i do next, to store every number I input from keyboard into array.

  • jbranchaud
    jbranchaud over 12 years
    And I agree with @Makoto, you can initialize the scanner outside of the loop so that it is only done once.
  • Makoto
    Makoto over 12 years
    No problem. Remember, here on SO if you see an answer you like/agree with, don't forget to accept it so the community knows your issue is resolved.