简体   繁体   English

Java中返回算术运算符

[英]returning arithmetic operators in java

I am working on a program that returns arithmetic expressions which include operators and integer numbers. 我正在研究一个返回算术表达式的程序,该算术表达式包括运算符和整数。 The code that i have implemented for it is this : 我为它实现的代码是这样的:

public String randomOperators() {
    Random random = new Random();
    String[] operators = {"+","-","*","/"};
    return operators[random.nextInt(4)];
}

the problem in this code is that it returns the operators but all the operators in the expression are same: example: i get an expression 9+2+3+4+5+ = ? 这段代码中的问题是它返回了运算符,但是表达式中的所有运算符都相同:例如:我得到一个表达式9 + 2 + 3 + 4 + 5 + =? i don't want it to have + in all, it can be many random operators in one expression. 我完全不希望它有+,在一个表达式中可以有许多随机运算符。 Any help would be appreciated. 任何帮助,将不胜感激。 Thanks 谢谢

new Random() initializes the random seed with an approximation of the current time, so if called many times in quick succession, the system clock will read the same -- and the random numbers generated will be the same. new Random()使用当前时间的近似值初始化随机种子,因此,如果快速连续调用多次,则系统时钟将读取相同的内容-生成的随机数将相同。

Instead, have one Random stored as a static field, or pass in a Random to randomOperators and reuse that same instance. 而是将一个Random存储为静态字段,或者将Random传递给randomOperators用该实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM