【第一周】四则运算
1.需求分析:对两个数字进行加减乘除四则运算
2.算法思想:
(1)随机获取两个数字和一个运算符构成一个表达式
(2)对表达式进行四则运算并输出对错
(3)统计输出答对和答错的次数
3.具体代码:
package ruan.jian.gong.cheng; import java.util.Random; import java.util.Scanner; public class FigureOperate { public static void main(String[] args) { int rightNum = 0;//答对次数 int wrongNum = 0;//答错次数 for (int i =1; i <= 10; i++) { int num1 =(int) (Math.random() * 10);//随机获取第一个数字 int num2 =(int) (Math.random() * 10);//随机获取第二个数字 // 生成随机运算符 Random num = new Random(); int index = num.nextInt(3) + 1; char[] opes = { '+', '-', '*', '/' }; String ope = String.valueOf(opes[index]); Scanner scan = new Scanner(System.in); if (opes.equals("+")) { // 进行加法运算 System.out.print(num1 + "+" + num2 + "="); int input = scan.nextInt(); int sum = num1 + num2; if (sum==input) { System.out.println("正确"); rightNum++; } else { System.out.println("错误"); wrongNum++; } System.out.println("正确答案是:" + sum); }else if (opes.equals("-")) { // 进行减法运算 System.out.print(num1 + "-" + num2 + "="); int input = scan.nextInt(); int sum = num1 - num2; if (sum==input) { System.out.println("正确"); rightNum++; } else { System.out.println("错误"); wrongNum++; } System.out.println("正确答案是:" + sum); }else if (opes.equals("*")) { // 进行乘法运算 System.out.print(num1 + "*" +num2 + "="); int input = scan.nextInt(); int sum = num1 * num2; if (sum==input) { System.out.println("正确"); rightNum++; } else { System.out.println("错误"); wrongNum++; } System.out.println("正确答案是:" + sum); }else { // 进行除法运算 System.out.print(num1 + "/" + num2 + "="); int input = scan.nextInt(); int sum = num1 / num2; if (sum==input) { System.out.println("回答正确"); rightNum++; } else { System.out.println("回答错误"); wrongNum++; } } } System.out.println("做对" + rightNum + "题"); System.out.println("做错" + wrongNum + "题"); } }
4.输出结果
posted on 2016-09-13 06:54 gonglj1994 阅读(161) 评论(2) 编辑 收藏 举报