【发布时间】:2014-09-13 21:42:29
【问题描述】:
我基本上希望能够循环 X + Y = Z 等式,直到用户输入除整数以外的其他内容,例如字母“A”,并且当有任何数字时,循环停止显示消息。
另外,我对如何随机定位“?”感到困惑。用户必须输入正确答案。
例如
System.out.println("What is: " + num1 + " + ? = " + answer);
到目前为止:
我正在定位“?”手动通过 IF 语句。能否以更有效的方式完成?
public static void main(String[] args) {
Random rand = new Random();
Scanner input = new Scanner(System.in);
int num1, num2, number3, answer;
do {
num1= 1 + rand.nextInt(10);
num2= 1 + rand.nextInt(10);
answer= num1 + num2;
System.out.println("What is: " + num1 + " + ? = " + answer);
number3= input.nextInt();
if (number3 == num2)
System.out.println("That is correct");
else
System.out.println("That is wrong");
num1= 1 + rand.nextInt(10);
num2= 1 + rand.nextInt(10);
answer= num1 + num2;
System.out.println(num1 + " + ? = " + answer);
number3= input.nextInt();
} while(number3 !=0);
}
【问题讨论】:
-
您是否尝试过 try/catch 块来检测非整数输入?例如尝试{ number3 = input.nextInt(); }catch(异常 e){ 中断;我还没有测试过,但它看起来是检测无效输入的好方法。
-
看起来你在做同样的事情两次。代码看起来像是在您的 if..else 语句之后重复。也许考虑删除它。您能否详细说明“我正在通过 IF 语句手动定位“?”?
-
I am positioning the "?" manually through the IF statements.不,您不是,您将?定位在 print 语句定位它的位置。基本上你想要的是检查输入是否是任何整数? -
@Tuan333 我会尝试使用catch/try,谢谢!
-
@clever_trevor 很抱歉造成混乱,我希望能够更改用户看到“?”所在的位置。有什么想法吗?
标签: java loops variables random