0

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; } } } 

}

3
  • ok? and what is your actual question? You have a codebase to start from, you know what must change. What is stopping you? try in your if, to change userNumber.nextInt() to number, since you already read the number Commented Jan 28, 2021 at 10:59
  • What is your question ? Commented Jan 28, 2021 at 10:59
  • I have tried number inside if statement but doesn't work. Commented Jan 28, 2021 at 11:05

1 Answer 1

2
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 + " "); 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. It works like a dream :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.