For loop 用于循环输出
我在为循环编写简单任务时遇到问题。我需要循环执行以下操作: 1) 提示用户询问50+10是多少= 2) 如果用户输入错误答案,将弹出警告消息,表示他们还有两次尝试 3) 一旦用户用尽了所有的尝试,就会弹出一条不同的消息,说您不再尝试了 这就是我能想到的:For loop 用于循环输出,for-loop,java.util.scanner,For Loop,Java.util.scanner,我在为循环编写简单任务时遇到问题。我需要循环执行以下操作: 1) 提示用户询问50+10是多少= 2) 如果用户输入错误答案,将弹出警告消息,表示他们还有两次尝试 3) 一旦用户用尽了所有的尝试,就会弹出一条不同的消息,说您不再尝试了 这就是我能想到的: public static void main(String[] args) { Scanner input = new Scanner(System.in); int attempt = 1; int answer = 60; for(
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int attempt = 1;
int answer = 60;
for( attempt = 1; attempt < 0; --attempt)
System.out.print(" 50 + 10 = ");
answer = input.nextInt();
input.nextLine();
if( answer != 60)
{
System.out.printf( "Invalid! Try Again! %d attempt(s) left! ", attempt);
System.out.print( "\n50 + 10 = " );
answer = input.nextInt();
}
if( attempt == 0)
{
System.out.print( "Sorry! You have no more attempts left!" );
}
System.exit(0);
}
publicstaticvoidmain(字符串[]args){
扫描仪输入=新扫描仪(System.in);
int尝试=1;
int答案=60;
for(尝试=1;尝试<0;--尝试)
系统输出打印(“50+10=”);
answer=input.nextInt();
input.nextLine();
如果(答案=60)
{
System.out.printf(“无效!重试!%d次剩余尝试!”,尝试);
系统输出打印(“\n50+10=”);
answer=input.nextInt();
}
如果(尝试==0)
{
System.out.print(“对不起!您没有更多尝试了!”);
}
系统出口(0);
}
如果我将控制变量的值从1改为2,它将打印50+10=50+10=
当我运行程序时,它将输出0次尝试,而不是2次尝试,然后是1次,然后是抱歉消息。看看这里……我已经在某种程度上修改了它
for( attempt = 1; attempt >= 0; --attempt)
{
System.out.print(" 50 + 10 = ");
answer = input.nextInt();
input.nextLine();
if( answer != 60)
{
if(attempt!=0)
{
System.out.printf( "Invalid! Try Again! %d attempt(s) left!\n ", attempt);
continue;
}
else
System.out.print( "Sorry! You have no more attempts left!" );
}
System.exit(0);
}
这确实有效,但我确实有一个关于控制变量的问题。当我把它改成2或3时,为什么它会复制我输入的任何数字?例如,在我的代码中,A2将使50+10=50+10=Its,因为for循环永远不会打开……没有大括号({})来包含for循环将执行的语句……因此它只执行第一个语句……啊,好的。这本愚蠢的书中有for循环的例子,但没有一个使用大括号,所以我把它们省略了。谢谢你的帮助和时间!