ArrayList

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • beeto
    New Member
    • Feb 2008
    • 2

    #1

    ArrayList

    I was wondering if it was possible to do a loop which continuously adds the integers that the user specifies into the array list and only stops asking the user for inputs once they input something other than an integer.

    Here's what I have so far of the method, I just can't think of a way to do what I've mentioned above.
    Code:
    public static void do_enter()
    {
    	Scanner scan = new Scanner(System.in);
    	
    	ArrayList numbers = new ArrayList();
    	
    	System.out.print("Enter a number: ");
    	numbers.add(scan.nextInt());
    	
    	System.out.println(numbers);
    }
    Example would be like:

    Enter a number: 1
    [1]
    Enter a number: 2
    [1, 2]
    Enter a number: -1
    [1, 2 , -1]
    Enter a number: abc
    (program should end)
  • BigDaddyLH
    Recognized Expert Top Contributor
    • Dec 2007
    • 1216

    #2
    To detect an input of a non-int, you could either test for it with Scanner's hasNextInt or catch a NoSuchElementEx ception. Study the API: http://java.sun.com/javase/6/docs/ap...l/Scanner.html

    Comment

    • sukatoa
      Contributor
      • Nov 2007
      • 539

      #3
      Originally posted by beeto
      I was wondering if it was possible to do a loop which continuously adds the integers that the user specifies into the array list and only stops asking the user for inputs once they input something other than an integer.

      Here's what I have so far of the method, I just can't think of a way to do what I've mentioned above.
      Code:
      public static void do_enter()
      {
      	Scanner scan = new Scanner(System.in);
      	
      	ArrayList numbers = new ArrayList();
      	
      	System.out.print("Enter a number: ");
      	numbers.add(scan.nextInt());
      
      	
      	System.out.println(numbers);
      }
      Example would be like:

      Enter a number: 1
      [1]
      Enter a number: 2
      [1, 2]
      Enter a number: -1
      [1, 2 , -1]
      Enter a number: abc
      (program should end)
      You can put try/catch in [PHP]numbers.add(sca n.nextInt());[/PHP]

      I think it is NumberFormatExc eption to use if the input cannot convert into integer value
      When exception occur, then terminate the program...

      Correct me if im wrong,
      Sukatoa (Shadow shaman)

      Comment

      • beeto
        New Member
        • Feb 2008
        • 2

        #4
        Thanks guys, I'll try it out.

        Comment

        Working...