将运算符赋给变量是not possible.
在30行or less...该程序要求用户进行简单的加法、除法、乘法或减法运算
如果您想使用尽可能少的行来实现它,build in functional interfaces将是一个不错的 Select .为此,需要IntBinaryOperator
来表示对两个int
参数执行的操作.
功能接口可以通过使用lambda expression或method reference(also, you can do that with an anonymous inner class as well by it'll not be shorter)来实现.加法运算可以这样表示:
IntBinaryOperator add = Integer::sum; // or (i1, i2) -> i1 + i2
问题类型(添加、多个等)应 Select randomly
为此,首先,需要定义一个Random
对象.为了获得给定范围内的一个随机整数,请使用nextInt()
方法,该方法需要int
个界,并返回一个从0
到界(exclusive)的值:
rand.nextInt(RANGE)
为了避免硬编码,RANGE
应该被定义为一个全局常数.
因为您的应用程序必须与用户交互,所以每operation个都应该与将向用户公开的name相关联.
可以通过声明record
(a special kind class withfinal
field and auto-generated constructor, gettershashCode/equals
toString()
)来实现.声明记录的语法非常简洁:
public record Operation(String name, IntBinaryOperator operation) {}
表示算术运算的Records可以存储在list中.您可以通过生成一个随机索引(从0
到列表大小)来 Select 一个操作.
operations.get(rand.nextInt(operations.size()))
与常见的getter不同,编译器将为记录生成的getter的名称将与其字段的名称相同,即name()
和operation()
.
为了使用从记录中检索到的函数,需要调用记录上的方法applyAsInt()
,传递之前生成的两个数字.
这可能就是它的样子.
public class Operations {
public static final int RANGE = 100;
public static final Random rand = new Random();
public record Operation(String name, IntBinaryOperator operation) {}
public static final List<Operation> operations =
List.of(new Operation("add", Integer::sum), new Operation("sub", (i1, i2) -> i1 - i2),
new Operation("mult", (i1, i2) -> i1 * i2), new Operation("div", (i1, i2) -> i1 / i2));
public static void main(String[] args) {
// you code (instansiate a scanner, enclose the code below with a while loop)
for (int i = 0; i < 10; i++) {
Operation oper = operations.get(rand.nextInt(operations.size()));
int operand1 = rand.nextInt(RANGE);
int operand2 = rand.nextInt(RANGE);
System.out.println(operand1 + " " + oper.name() + " " + operand2); // exposing generated data to the user
int userInput = sc.nextInt(); // reading user's input
int result = oper.operation().applyAsInt(operand1,operand2); // exposing the result
System.out.println(result + "\n__________________");
}
// termination condition of the while loop
}
}
这是用户将看到的输出示例:
38 add 67
105 // user input
105
_____________________
97 sub 15
...