Java每日一题08

[color=blue]编写一个辅助小学生学习乘法的程序。使用一个Random对象产生两个一位数正整数。然后程序应该给用户提出一个问题,诸如“How much is 6 times 7 ?”。然后由学生输入答案。接着程序检查学生的答案是否正确,如果正确,则显示消息“very good!”并另外问一个乘法问题。如果答案是错的,则显示消息“no,please try again.”并让学生重复同一个问题,直到学生最终得到正确答案。应该使用一个单独的方法来生成每一个新问题。这个方法应该在应用程序开始执行时调用一次,以后每次当用户回答正确了问题时调用一次。[/color]

今天的题主要讨论如何用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;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值