Java,当输入为空时如何中断循环?

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


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


    }

}


慕田峪9158850
浏览 107回答 2
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();    }}

一只甜甜圈

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);    }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java