我在编写一个简单的循环任务时遇到了麻烦。我需要循环来做的事情如下:
1)提示用户询问什么是50 + 10 =
2)如果用户输入了错误的答案,则会弹出一条警告消息,说明他们还有2次尝试
3)一旦用户耗尽他们所有的尝试,就会弹出一条不同的消息,说明你没有再尝试
这是我能够提出的:
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);
}
如果我将控制变量的值从1改为2,则打印50 + 10 = 50 + 10 =
当我运行该程序时,它将输出0次尝试而不是2次尝试,然后是1,然后是抱歉消息。
答案 0 :(得分: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);
}