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

时间:2019-09-05 06:34:57

标签: java break

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

问题是我无法用空行使循环中断。我不确定该怎么做。我已经检查了其他问题以寻求解决方案,但找不到任何有帮助的方法。我也无法分配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);

    }
}

2 个答案:

答案 0 :(得分:2)

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

import java.util.Scanner;

public class StackOverflow {

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

}

答案 1 :(得分:2)

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

    }
}