[color=blue]编写一个辅助小学生学习乘法的程序。使用一个Random对象产生两个一位数正整数。然后程序应该给用户提出一个问题,诸如“How much is 6 times 7 ?”。然后由学生输入答案。接着程序检查学生的答案是否正确,如果正确,则显示消息“very good!”并另外问一个乘法问题。如果答案是错的,则显示消息“no,please try again.”并让学生重复同一个问题,直到学生最终得到正确答案。应该使用一个单独的方法来生成每一个新问题。这个方法应该在应用程序开始执行时调用一次,以后每次当用户回答正确了问题时调用一次。[/color]
今天的题主要讨论如何用Java实现类似于goto的写法
或者
今天的题主要讨论如何用Java实现类似于goto的写法
package test45;
import java.util.Random;
import java.io.*;
public class TimesClass {
/**
* @param args
*/
public static void main(String[] args) {
// TODO 自动生成方法存根
TimesClass tc = new TimesClass();
int flag;
int result;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int input;
try {
while (true) {
flag = 0;
result = tc.getNum();
input = Integer.parseInt(br.readLine());
while (flag == 0) {
if (input == result) {
System.out.println("very good!");
flag = 1;
} else {
flag = 0;
System.out.println("no,please try again.");
input = Integer.parseInt(br.readLine());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public int getNum() {
Random rand = new Random();
int num[] = new int[2];
num[0] = rand.nextInt(10);
num[1] = rand.nextInt(10);
System.out.println("How much is " + num[0] + " times " + num[1] + " ?");
return num[0] * num[1];
}
}
或者
package test45;
import java.util.Random;
import java.util.Scanner;
public class Times {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
L1: while (true) {
int question = new Times().question();
L2: while (true) {
int answer = scanner.nextInt();
if (answer == question) {
System.out.println("very good!");
continue L1;
} else {
System.out.println("no,please try again.");
continue L2;
}
}
}
}
public int question() {
Random random = new Random();
int a = random.nextInt(10);
int b = random.nextInt(10);
System.out.println("How much is " + a + " times " + b);
return a * b;
}
}