Java 如何在每次无效输入后要求用户反复输入
因此,我自己的有效日期仅为1520到3999,我是这个网站的新手,我是java的新手 请帮忙 我想知道我做错了什么,或者在这段代码中做了什么Java 如何在每次无效输入后要求用户反复输入,java,Java,因此,我自己的有效日期仅为1520到3999,我是这个网站的新手,我是java的新手 请帮忙 我想知道我做错了什么,或者在这段代码中做了什么 int x; Scanner in = new Scanner (System.in); do { System.out.print ("Enter a date "); x = in.nextInt(); } while (x<1520&&x>39
int x;
Scanner in = new Scanner (System.in);
do
{
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: ");
}
}}
intx;
扫描仪输入=新扫描仪(系统输入);
做
{
System.out.print(“输入日期”);
x=in.nextInt();
}
而(x3999),;
{
System.out.println(“无效的公历日期”);
System.out.print(“请输入有效的公历日期:”);
}
}}
在while循环中,每当输入无效时,获取另一个整数。另外,您需要在while条件下将&&
更改为|
,因为没有任何数字同时小于1520和大于3999。您也不需要do
部分,您需要删除while循环后的分号-这会阻止循环为您做任何有成效的事情
int x;
Scanner in = new Scanner (System.in);
System.out.print ("Enter a date ");
x = in.nextInt();
while (x<1520 || x>3999) // change this to "or", i.e. && --> ||
{
System.out.println ("Invalid Gregorian Calendar date.");
System.out.print ("Please Input a valid Gregorian Calendar date: ");
x = in.nextInt(); // get another number before checking conditions again
}
intx;
扫描仪输入=新扫描仪(系统输入);
System.out.print(“输入日期”);
x=in.nextInt();
while(x3999)//将其更改为“或”,即&&&-->
{
System.out.println(“无效的公历日期”);
System.out.print(“请输入有效的公历日期:”);
x=in.nextInt();//在再次检查条件之前获取另一个数字
}
您需要在while循环中询问用户,直到他输入正确的日期
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();
}
}}
intx;
扫描仪输入=新扫描仪(系统输入);
System.out.print(“输入日期”);
x=in.nextInt();
while(x3999)
{
System.out.println(“无效的公历日期”);
System.out.print(“请输入有效的公历日期:”);
x=in.nextInt();
}
}}
&&
运算符是逻辑的和
输入值不能小于1520且大于3999。
我想您需要检查x
是否小于1520或大于3999
要实现这一点,您应该使用适当的逻辑运算符,在这种情况下,它是或
x3999
您可以按如下方式更改代码(注意,我将&更改为| |,因为没有大于3999且小于1520的数字。)
intx;
扫描仪输入=新扫描仪(系统输入);
系统输出打印(“输入日期”);
x=in.nextInt();
而(x<1520 | | x>3999)
{
System.out.println(“无效的公历日期”);
System.out.print(“请输入有效的公历日期:”);
x=in.nextInt();
}
}
您忘记删除在while
条件之后执行code>。您忘记删除代码>在while
条件之后。
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();
}
}