Java, 输入为空时如何打破循环?

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

这样做的目的是让用户每行输入一个数字,当用户不再希望继续时,他们应该能够输入一个空行,当这种情况发生时,程序应该给你一个消息最大的数字。

问题是我无法用空行中断循环。我不知道该怎么做。我已经检查了其他问题的解决方案,但找不到任何有用的东西。我也无法分配 scan.hasNextInt() == null.....

我确定有一个我没有想到的快速且合乎逻辑的解决方案。

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

    }
}

这应该可以解决您的问题:

import java.util.Scanner;

public class Whosebug {

    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;

        try {
            while(!scan.nextLine().isEmpty()){
                int num = Integer.parseInt(scan.nextLine());

                if(num > x) {
                    x = num;
                }
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

        System.out.println("Largest number entered: " + x);
        scan.close();
    }

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

    }
}