Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

Java Scanner, Arraylist and while loop

I am trying a to get user input and add the value in Arraylist as long it is positive number. If user enters a negative number the program should stop. This is my code it take up to three numbers then stops. Thank you in advance.

class ProjectOne{

public void counterLoop() {
    Scanner userNumber = new Scanner(System.in);
    ArrayList<Integer> number = new ArrayList();

    System.out.println("Enter Your No: ");
    number.add(userNumber.nextInt());

    while (true){
        System.out.println("Enter a number: ");
        number.add(userNumber.nextInt());
        System.out.println(number);

        if (userNumber.nextInt() >= 0){
            break;
        }
    }
}

}

question from:https://stackoverflow.com/questions/65935708/java-scanner-arraylist-and-while-loop

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
public void counterLoop() {
    Scanner userNumber = new Scanner(System.in);
    ArrayList<Integer> number = new ArrayList<>();
    while (true) {
        System.out.println("Enter a number: ");
        int n = userNumber.nextInt();
        if(n >= 0)
            number.add(n);
        else break;
    }
}

You should add the number to the list iff it is >= 0. If a negative number is input, the loop should break. You can print your list to see the result,

for(int i : number)
   System.out.print(i + " ");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...