我已经使用 Random 类生成一个随机数并且该数字显示出来,但是当我尝试将生成的随机数与 10 添加时,它只是连接起来,即如果随机数是 20,它将显示为 2010
import java.util.Random;
public class MainClass{
static int x = 50;
static int y = 10;
public class InnerClass {
double myDouble = x;
void show() {
System.out.println(myDouble + 5);
}
}
public static void main(String args[]){
Random rand = new Random();
MainClass obj1 = new MainClass();
MainClass.InnerClass obj2 = obj1.new InnerClass();
int int_random = rand.nextInt(x);
System.out.println(int_random + " :" + " This is the Random Number and its plus 10 is "+ int_random + y);
// obj2.show();
}
}
最佳答案
Java 中的 +
运算符可以执行两种截然不同的操作:将两个数字相加,以及连接两个字符串。如果将数字“添加”到字符串中,则该数字首先会转换为字符串,然后将两个字符串连接起来。
难题的另一部分是 +
是从左到右应用的(它是左关联)。因此,如果您编写 a + b + c
,则表示 (a + b) + c
而不是 a + (b + c)
。因此,如果 a
是字符串,而 b
和 c
是整数,则 (a + b)
将是 a字符串,c
在添加到字符串之前先转换为字符串。
解决方案是使用括号强制计算顺序:显式写入 a + (b + c)
,或者根据您的情况:
System.out.println(int_random + " :" + " This is the Random Number and its plus 10 is "+ (int_random + y));
关于java - 添加到随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61318233/