Hello I want to write a loop that quit the loop if the user hits Enter or there is negative number. this is what i have so far. it only quits the loop if user enter characters.

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

public class loop {

	public static void main(String[] args) {
		System.out.println("Enter a positive number: ");
		Scanner sc = new Scanner(System.in);
		ArrayList<Integer> list= new ArrayList<Integer>();
		while (sc.hasNextInt()){
			list.add(sc.nextInt());
			sc=new Scanner(System.in);

thanks

Edited 5 Years Ago by newbieha: n/a

Problem #1 - you don't want to make a new Scanner each time through the loop. No need. Get rid of that line.

Problem # 2 - you want to break on a negative number? In that case, check the value of that sc.nextInt() call, and if it's negative, do a break.

Thanks Jon. I am new to java. you mean like this? it gives me error when i enter any positive number

import java.util.Scanner
import java.util.ArrayList;
public class loop {

	public static void main(String[] args) {
		System.out.println("Enter a positive number: ");
		Scanner sc = new Scanner(System.in);
		ArrayList<Integer> list= new ArrayList<Integer>();
		while (sc.hasNextInt()){
                        if(sc.nextInt<0){
                             break;}
                        else{
			   list.add(sc.nextInt());}

Edited 5 Years Ago by newbieha: n/a

That's almost what I was thinking. Remember, each time you execute nextInt(), it gets the next int from the input. You have to hang on to that int if you want to put it in your list. Try assigning the nextInt() to a variable, then checking the variable to see if it's negative, and put it in the list if it isn't.

Also, when you have if ( condition) break; you don't need an else. It won't be an error to have the else, but any time condition is true you're going to break, so if you get to the else at all, it's going to execute.
That being said, I always state the else because it makes the code easier to read. I just wanted to point out that it's not strictly necessary.

Thanks Jon. It works fine now. If I want to quit the loop if the user just hits Enter. do i just add another else if statement?

This article has been dead for over six months. Start a new discussion instead.