Java,当输入为空时如何中断循环?
这样做的目的是让用户在每行输入一个数字,当用户不再希望继续时,他们应该能够输入一个空行,当这种情况发生时,程序应该给您一个最大数字的消息 问题是我不能用空行使循环中断。我不知道该怎么做。我已经检查了其他问题的解决方案,但我找不到任何有帮助的。我也无法分配Java,当输入为空时如何中断循环?,java,break,Java,Break,这样做的目的是让用户在每行输入一个数字,当用户不再希望继续时,他们应该能够输入一个空行,当这种情况发生时,程序应该给您一个最大数字的消息 问题是我不能用空行使循环中断。我不知道该怎么做。我已经检查了其他问题的解决方案,但我找不到任何有帮助的。我也无法分配scan.hasNextInt()==null 我相信有一个快速合理的解决方案,我没有想到 import java.util.*; public class Main { public static void main(String[
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 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();
}
}
您可以使用
Scanner\hasNextLine()
和Scanner\nextLine()
获取输入并检查该字符串是否为空。如果是,您可以中断循环,如果不是,您可以尝试将输入解析为int
,并执行其他逻辑。我不知道为什么会被否决。它符合OP的要求。不过,如果用户输入数字以外的任何内容时抛出的可能的numberformatception
有一些解释和try-catch会更好。也许您可以添加try-catch块来处理可能的numberformatceptions
并打破循环?只是一个有完整答案的问题。
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);
}
}