Sirig Gurung
Sirig Gurung

Reputation: 1

ArrayList Scanner input help Java

I am trying to write a code where you sort a given list of numbers, and I'm trying to do so using ArrayList. I am using a while loop to allow for repeated inputs. This is my code:

import java.util.Scanner; 
import java.util.ArrayList;

public class sortinggg {

    public static Scanner keyboard = new Scanner(System.in);
    public static ArrayList<Integer> number = new ArrayList<Integer>();

    public static void main (String [] args) {

        int count= 0;

        System.out.println("Enter your numbers.");

        while (keyboard.hasNextInt()); {
            number.add(keyboard.nextInt()); 
        }

The integer count is irrelevant right now, as I only use it when I am sorting the list.

The problem is that after I input my numbers, even if I type in a string (for example), the program doesn't move on to the next line of code. Am i missing anything here?

P.S. I tired looking up questions that have been asked previously on this topic, but none of the solutions suggested worked for me.Thank you for your help in advance!

Upvotes: 0

Views: 1544

Answers (2)

Ravindra Ranwala
Ravindra Ranwala

Reputation: 21124

In the first place the ; just after the while is wrong. It does not let you to execute the body. Then how are you going to skip the loop. You may ask the end user to enter some special value and use it to break the loop. The corrected version is given below.

public static void main(String[] args) {
        int count = 0;

        System.out.println("Enter your numbers or -1 to skip.");

        while (keyboard.hasNextInt()) {
            int num = keyboard.nextInt();
            if (num == -1) {
                break;
            }
            number.add(num);

        }

        System.out.println(number);

    }

Upvotes: 1

Nitin Bisht
Nitin Bisht

Reputation: 5331

Try this:

import java.util.ArrayList;
import java.util.Scanner;

public class Main
{
    public static void main(String args[])
    {
        Scanner keyboard = new Scanner(System.in);
        ArrayList<Integer> number = new ArrayList<Integer>();

        System.out.println("Enter your numbers:");

        while (keyboard.hasNextInt()) {
            number.add(keyboard.nextInt()); 
        }
    }
} 

Modifications:

  1. In while (keyboard.hasNextInt()); remove semicolon(;) at the end.

Here while loop will keep adding values to the arraylist until you provide int values.

Upvotes: 2

Related Questions