Java 如何在X+;Y=Z操作和循环
我基本上希望能够循环一个X+Y=Z方程,直到用户输入除整数以外的其他值,比如字母“A”,并且当有任何数字时,循环停止显示消息 此外,我对如何随机定位用户必须输入正确答案的“?”感到困惑 比如说Java 如何在X+;Y=Z操作和循环,java,loops,variables,random,Java,Loops,Variables,Random,我基本上希望能够循环一个X+Y=Z方程,直到用户输入除整数以外的其他值,比如字母“A”,并且当有任何数字时,循环停止显示消息 此外,我对如何随机定位用户必须输入正确答案的“?”感到困惑 比如说 System.out.println("What is: " + num1 + " + ? = " + answer); 到目前为止: 我正在通过IF语句手动定位“?”。这能以更有效的方式完成吗 public static void main(String[] args) { Random
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);
}
以下是一种方法:
public static void main(String[] args) {
Random rand = new Random();
Scanner scanner = new Scanner(System.in);
int[] xyz = new int[3];
String[] display = new String[3];
int answer, position;
do {
xyz[0] = 1 + rand.nextInt(10);
xyz[1] = 1 + rand.nextInt(10);
xyz[2] = xyz[0] + xyz[1];
for (int i = 0; i < xyz.length; i++)
display[i] = String.valueOf(xyz[i]);
position = rand.nextInt(3);
display[position] = "?";
System.out.println("What is: " + display[0] + " + " + display[1] + " = " + display[2]);
do {
System.out.println("Please enter an integer or 'S' to stop");
String input = scanner.nextLine();
if (input.equals("S")) {
scanner.close();
System.out.println("Stopped");
return;
}
else if (input.matches("\\d+")) { // \\d+ means "a digit (0-9) once or more
answer = Integer.parseInt(input);
break;
}
} while (true);
if (answer == xyz[position])
System.out.println("That is correct");
else
System.out.println("That is wrong");
} while (true);
}
publicstaticvoidmain(字符串[]args){
Random rand=新的Random();
扫描仪=新的扫描仪(System.in);
int[]xyz=新的int[3];
字符串[]显示=新字符串[3];
回答,位置;
做{
xyz[0]=1+rand.nextInt(10);
xyz[1]=1+rand.nextInt(10);
xyz[2]=xyz[0]+xyz[1];
对于(int i=0;i
注意事项:
- 我使用内部
循环反复检查输入,并要求用户输入有效的输入do while
- 我使用两个数组:一个用于存储数字,另一个用于存储显示值
- 我还添加了一个停止条件,因为外循环是无限的。完成后始终关闭
扫描仪
- 我为“?”随机选择了3个位置中的1个