我正试图为我的班级写一个30行或更少的程序(self 挑战).

程序要求用户进行简单的加法、除法、乘法或减法100,玩家回答、冲洗并重复10次,然后询问玩家是否要继续或结束程序.问题类型(addmult等)应随机 Select .

因此,我不需要使用巨大的switch 盒或if-else树,我想知道是否有任何方法可以在变量中包含运算符,然后稍后使用它.

例子:

var operator = +;
int[] n = {1, 2};
System.out.println(n[0] operator n[1]);

输出为"3"

这是我想做的事情的一个例子.这可能吗?

推荐答案

将运算符赋给变量是not possible.

在30行or less...该程序要求用户进行简单的加法、除法、乘法或减法运算

如果您想使用尽可能少的行来实现它,build in functional interfaces将是一个不错的 Select .为此,需要IntBinaryOperator来表示对两个int参数执行的操作.

功能接口可以通过使用lambda expressionmethod 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 withfinalfield and auto-generated constructor, gettershashCode/equalstoString())来实现.声明记录的语法非常简洁:

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
...

Java相关问答推荐

Android -如何修复Java.time.zone. ZoneRulesExcept:未知时区ID:Europe/Kyiv

BiPredicate和如何使用它

Java List with all combinations of 8 booleans

现场观看Android Studio中的变化

为什么JAVA&S清洁器使用链表而不是并发HashSet?

试着做一个2x2的魔方求解算法,我如何找到解路径(DFS)?

如何修复PDF重建过程中的文本定位

如何从Keyloak映射Hibernate实体中的用户

Spring Security不允许加载js

二进制数据的未知编码/序列化

有谁能帮我修一下这个吗?使输出变得更加整洁

是否有一个Java Future实现可以在池繁忙时在调用者线程中执行?

将stringBuilder + forloop转换为stream + map

在不使用instanceof或强制转换的情况下从父类变量调用子类方法

AspectJ编织外部依赖代码,重新打包jar并强制依赖用户使用它

Eureka客户端无法使用用户/通行证注册到Eureka服务器

如何组合Mono和Flux

ANTLR 接受特殊字符,例如 .标识符或表达式中的(点)和 ,(逗号)

Java ModbusRTU写寄存器

如何在 lambda 中烘焙值