所以这是我的代码我不知道要添加什么,如果我想显示非数字输入的无效消息请帮助ty
import java.util.Scanner;
public class Date
{
public static void main (String args [])
{
int x;
Scanner in = new Scanner (System.in);
System.out.print("Enter a date ");
x = in.nextInt();
while (x < 1520 || x > 3999)
{
System.out.println ("Invalid Gregorian Calendar date.");
System.out.print ("Please Input a valid Gregorian Calendar date: ");
x = in.nextInt();
}
System.out.println("Good");
答案 0 :(得分:0)
使用try catch块,并将x = in.nextInt();
放入其中
答案 1 :(得分:0)
Scanner类对此
有a methodScanner in = new Scanner(System.in);
int x;
if(in.hasNextInt()){
x = in.nextInt();
System.out.println("Valid number");
}else{
System.out.println("Not a number");
}
继续提示,直到输入有效号码
int x;
System.out.println("Enter a number: ");
while(!in.hasNextInt()){
System.out.println("Invalid number, try again: ");
key.nextLine(); // Flush out invalid number
}
x = key.nextInt();
答案 2 :(得分:0)
我已经改变了你的代码。我认为这就是你的目标。
我在解释方面不是那么好,但我试着说出我做了什么。
首先,我摆脱了你的in.nextInt()
,因为这是非常严格的。它只接受一个整数,如果你输入其他东西,它会抛出一个异常。通常情况下这没关系,但是因为你希望用户能够纠正输入,这将导致比它解决的更多麻烦。
然后我将您的代码置于无限循环while(true)
中,这样可以确保在输入错误值后再次重新启动应用程序。
循环内发生的事情非常简单。控制台打印出您希望用户执行的操作,并将控制台输入作为字符串读取,因此您不必首先面对任何异常。
然后我尝试将给定的String解析为整数值。我添加了trim()
来杀死前导空格以及尾随空格,所以我不必通过输入带空格的数字来处理用户感到困惑,因为他们在获取时不会直接看到错误他们的&#34;不是整数&#34;错误。如果输入包含空格,则抛出此内容。
现在我检查给定的整数值是否符合您的指定。我不需要在这里使用循环,因此我将其更改为简单的if语句。
如果值错误(或者让if (x < 1520 || x > 3999)
返回true),我将打印出您的错误消息。由于我们已经将String输入转换为整数,并且我们没有到达else
- 分支,我们现在返回到循环的开头,在等待新输入之前再次打印请求。
现在,只要用户输入其他值,例如2011年(根据您的规格有效)我们现在将到达打印&#34; Good&#34;并通过调用break
离开循环。由于应用程序没有什么可做的,它将停止运行。如果您希望用户能够在肯定的情况下输入新值,则只需删除break
- 语句。
如果用户键入的值不是整数,则强制转换将失败并抛出NumberFormatException。我们通过用try-catch
- 块围绕转换来捕获此异常,并在我们到达catch块后打印出整数错误。
然后应用程序以相同的方式做出反应,就像输入错误的数字一样,我们将再次返回循环的开头。
在扫描仪周围放置试块的原因是handle closing。
import java.util.Scanner;
public class Date {
public static void main(String args[]) {
String input = "";
int x = 0;
try (Scanner in = new Scanner(System.in);) {
while (true) {
System.out.print("Please Input a valid Gregorian Calendar date: ");
input = in.nextLine();
try {
x = Integer.parseInt(input.trim());
if (x < 1520 || x > 3999) {
System.out.println("Invalid Gregorian Calendar date.");
}
else {
System.out.println("Good");
break;
}
} catch (NumberFormatException e) {
System.out.println("Given value \"" + input.trim() + "\" is not an integer.");
}
}
}
}
}