Java编写四则运算
一、需求分析
程序可接收一个输入参数n,然后按要求产生n道加减乘除练习题,每个数字在 0 和 100 之间。
二、功能分析
输入需要产生的题目个数。
屏幕依次显示产生的题目以及计算结果。
package arithmetic; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.Scanner; import java.util.function.BiFunction; public class Exam { Scanner scan=new Scanner(System.in); private List<Subject> subjectList; public List<Subject> getSubjectList() { return subjectList; } public void setSubjectList(List<Subject> subjectList) { this.subjectList = subjectList; } public Exam() { System.out.print("请输入出题个数"); int count = scan.nextInt(); List<Subject> list = new ArrayList<Subject>(); BiFunction<Integer, Integer, Integer> add = (x, y) -> x + y; BiFunction<Integer, Integer, Integer> minus = (x, y) -> x - y; BiFunction<Integer, Integer, Integer> multiple = (x, y) -> x * y; BiFunction<Integer, Integer, Integer> divide = (x, y) -> x / y; for (int i = 0; i < count; i++) { Subject subject = new Subject(); Integer a = new Random().nextInt(99); Integer b = new Random().nextInt(99); subject.setA(a); subject.setB(b); subject.setIndex(i + 1); Integer symbol = new Random().nextInt(3); if (symbol == 0) { subject.setSymbol("+"); subject.setAnswer(add.apply(a, b)); } else if (symbol == 1) { subject.setSymbol("-"); subject.setAnswer(minus.apply(a, b)); } else if (symbol == 2) { subject.setSymbol("×"); subject.setAnswer(multiple.apply(a, b)); } else if (symbol == 3) { subject.setSymbol("÷"); subject.setAnswer(divide.apply(a, b)); } list.add(subject); } this.subjectList = list; } public static void main(String[] args) { Exam exam = new Exam(); // 查看试卷 exam.getSubjectList().forEach(subject -> { System.out.println(subject.getA() + " " + subject.getSymbol() + " " + subject.getB() + " = " + subject.getAnswer()); }); } } /** * 定义题目的类 * */ class Subject { private Integer index; private Integer a; private Integer b; private String symbol; private Integer answer; public Integer getIndex() { return index; } public void setIndex(Integer index) { this.index = index; } public Integer getA() { return a; } public void setA(Integer a) { this.a = a; } public Integer getB() { return b; } public void setB(Integer b) { this.b = b; } public String getSymbol() { return symbol; } public void setSymbol(String symbol) { this.symbol = symbol; } public Integer getAnswer() { return answer; } public void setAnswer(Integer answer) { this.answer = answer; } }

浙公网安备 33010602011771号