Java, How to break a loop when input is empty?

AllanJ :

The goal of this is to let the user enter a number per line and when the user no longer wish to continue they should be able to enter a empty line and when that happens the program should you give you a message with the largest number.

Problem is I can't make the loop break with an empty line. I'm not sure how to. I've checked other questions for a solution but I couldn't find anything that helped. I also can't assign scan.hasNextInt() == null....

I'm sure there is a quick and logical solution to this that I'm not thinking of.

import java.util.*;

public class Main {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);

        System.out.println(Enter a number and press [Enter] per line, when you no longer wish to continue press [Enter] with no input.(empty line));
        int x = 0;

        while(scan.hasNextInt()){
            int n = scan.nextInt();

            if (n > x){
               x = n;
            }
        }

        System.out.println("Largets number entered: " + x);

    }
}
Tanishqa Mahendru :
import java.util.*;

public class main {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter a number and press [Enter] per line, when you no longer wish to continue press [Enter] with no input.");
        String str = scanner.nextLine();
        int x = 0;

        try {
            while(!str.isEmpty()){
                int number = Integer.parseInt(str);

                if (number > x){
                    x = number;
                }

                str = scanner.nextLine();
            }
        }
         catch (NumberFormatException e) {
             System.out.println("There was an exception. You entered a data type other than Integer");
         }

        System.out.println("Largets number entered: " + x);

    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=308473&siteId=1