我的博士告诉我要弄清楚用户试图得到正确答案的次数,这让我很困惑。这是程序。请有人帮我解决这个问题。
public static void main(String[] args) {
int a = (int) (Math.random() * 10);
int b = (int) (Math.random() * 10);
Scanner s = new Scanner(System.in);
System.out.println("What is: " + a + " + " + b + " ?");
int answer = s.nextInt();
while (answer != (a + b)) { ///tell him it's wrong
System.out.println("Incorrect. Try again.");
System.out.println("What is: " + a + " + " + b + " ?");
answer = s.nextInt();
}
System.out.println("Correct.");
/// how many tries did the user tried? H.W
}
}
答案 0 :(得分:0)
只需要一个count
变量,然后在循环中将其增加。
public static void main(String[] args) {
int a = (int) (Math.random() * 10);
int b = (int) (Math.random() * 10);
Scanner s = new Scanner(System.in);
int count = 0;
System.out.println("What is: " + a + " + " + b + " ?");
int answer = s.nextInt();
while (answer != (a + b)) { ///tell him it's wrong
System.out.println("Incorrect. Try again.");
count++; //increase if the number of wrong answers
System.out.println("What is: " + a + " + " + b + " ?");
answer = s.nextInt();
}
System.out.println("Correct after " + count + " time(s)");
}
答案 1 :(得分:0)
您可以将最初设置为0的变量设为count
,并在每次执行while
循环时将其递增,即每当用户不正确时。在循环外部,您可以将尝试次数打印为count
。
在代码中你可以这样做..
import java.util.*;
class Main {
public static void main(String[] args) {
int a = (int) (Math.random() * 10);
int b = (int) (Math.random() * 10);
int count = 0; // setting variable to count number of tries
Scanner s = new Scanner(System.in);
System.out.println("What is: " + a + " + " + b + " ?");
int answer = s.nextInt();
while (answer != (a + b)) { ///tell him it's wrong
System.out.println("Incorrect. Try again.");
count++; // incrementing the number of tries i.e count
System.out.println("What is: " + a + " + " + b + " ?");
answer = s.nextInt();
}
System.out.println("Correct after " + count + " time(s)"); // displaying count
/// how many tries did the user tried? H.W
}
}
答案 2 :(得分:0)
public static void main(String[] args) {
int a = (int) (Math.random() * 10);
int b = (int) (Math.random() * 10);
Scanner s = new Scanner(System.in);
System.out.println("What is: " + a + " + " + b + " ?");
int answer = s.nextInt();
int count = 0;
while (answer != (a + b)) { ///tell him it's wrong
count++; // Why count ??
System.out.println("Incorrect. Try again.");
System.out.println("What is: " + a + " + " + b + " ?");
answer = s.nextInt();
}
System.out.println("Correct. It took you " + count + "attempt/s.");
/// how many tries did the user tried? H.W
}
}
我看到你对上述答案的评论。答案是100%正确。
现在回答您关于使用count
。
告诉我你将如何手动完成。如果你向你的朋友提问,他/他尝试了4次,然后在最后一次尝试得到了正确答案,即第5次尝试,那么你将如何告诉他/她"哦你做了5次尝试......!&# 34; ??
每次他/她回答时,你都会在你的指尖上计算它(直到正确的猜测),对吗?
正是你通过代码执行的操作,启动/初始化变量为zero
(0),当你从用户那里得到输入(即回答)时,检查它是否正确...如果这是正确的你会把计数值增加1(打开你的第一根手指然后说'#34;嘿你曾经尝试过一次"),如果它是错的你会(打开你的手指然后说'#34;不,再试一次。")将计数器增加1,并在每次错误的尝试时一次又一次地增加计数器。如果答案匹配,你会增加计数器并说'#34; Hurray ..你得到了正确答案并且花了count
次。"
希望你的问题得到解决。 !!