Java 我怎样才能再次请求输入而不只是出错
所以我想请求用户输入。问题是,如果用户尝试键入非数字的内容,而不是数字,我还希望程序给出错误消息并再次请求输入Java 我怎样才能再次请求输入而不只是出错,java,Java,所以我想请求用户输入。问题是,如果用户尝试键入非数字的内容,而不是数字,我还希望程序给出错误消息并再次请求输入 public class Mystuff { public static void main(String[] args) { System.out.println("Write your string"); String s = SubProgram.string(); System.out.println(
public class Mystuff {
public static void main(String[] args) {
System.out.println("Write your string");
String s = SubProgram.string();
System.out.println("The string: " +s);
int i = SubProgram.getInt();
System.out.println("The int: " +i);
}
}
课程:
import java.util.Scanner;
public class SubProgram {
private static final Scanner INPUT = new Scanner(System.in);
public static String string() {
String s = INPUT.nextLine();
return s;
}
public static int getInt(){
System.out.println("Write your number");
int num = INPUT.nextInt();
return num;
}
}
要重复某事,请使用循环 基本模式是:
do {
print a prompt;
read input;
validate input;
if not valid, print error message;
} while (valid input has not been provided);
一种合理的方法是在“验证输入”步骤中设置一些标志(例如,valid
)true或false,然后循环在(!valid)时为
对于使用nextInt()
,如果输入不是有效的整数,它将引发异常。您需要捕获该异常(请参见try catch
语句),并使用该异常设置“无效”
我相信,通过这些解决方案的草图,您可以编写实际的代码。如您所知,使用循环,例如:
public static int getInt(){
String num = null;
while (num == null) {
System.out.println("Write your number");
num = INPUT.nextLine();
if (!num.matches("\\d+")) {
System.err.println("Invalid number supplied! (" + num + ")");
num = null;
}
}
return Integer.valueOf(num);
}将输入提示放入循环中。在用户输入有效值之前,您一直处于循环中。您是否在今天(星期日)早些时候问过这个问题?谢谢,但现在我还有一个问题。。。当我试图返回时,总是说有问题。如果我尝试在try
内返回,则表示如果我尝试在后返回,则此方法必须返回int类型的结果,而表示num不能解析为变量
所有代码路径都需要返回值,而不仅仅是循环内try内的值。如果希望“num”在循环外部可访问,则必须在外部声明它(在本例中,在之前)。下一步阅读:范围!
public static int getInt(){
String num = null;
while (num == null) {
System.out.println("Write your number");
num = INPUT.nextLine();
if (!num.matches("\\d+")) {
System.err.println("Invalid number supplied! (" + num + ")");
num = null;
}
}
return Integer.valueOf(num);