程序3-1
假设开发一个程序,让一年级的小朋友练习加法运算。程序随机产生两个一位整数:number1和number2,然后显示“What is 1 + 7”,如程序清单3-1运行示例。当学生在对话框中输入答案之后,程序显示一个消息,表明答案是真的还是假的。
程序3清单-1
package Chapter_03; import java.util.Scanner; public class Code_2 { public static void main(String[] args) { int number1 = (int)(System.currentTimeMillis() % 10); int number2 = (int)(System.currentTimeMillis() / 7 % 10); Scanner input = new Scanner(System.in); System.out.print("What is "+ number1 + " + " + number2 + " ?"); int answer = input.nextInt(); System.out.print(number1 + " + " + number2 + " = " + answer + " is " + (number1 + number2 == answer)); } }
程序调试:
What is 6 + 5 ?7 6 + 5 = 7 is false
本题3.2程序清单:
package Chapter_03;
import java.util.Scanner;
public class Code_2 {
public static void main(String[] args) {
int number1 = (int)(System.currentTimeMillis() % 10);
int number2 = (int)(System.currentTimeMillis() / 7 % 10);
int number3 = (int)(System.currentTimeMillis() / 3 % 10);
Scanner input = new Scanner(System.in);
System.out.print("What is "+ number1 + " + " + number2 + " + " + number3 + " ?");
int answer = input.nextInt();
System.out.print(number1 + " + " + number2 + " + " + number3 + " = " + answer + " is " + (number1 + number2 + number3 == answer));
}
}
程序调试
What is 1 + 8 + 3 ?7 1 + 8 + 3 = 7 is false