Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 将Int转换为字符串时发生子字符串错误 for(int i=0;i_Java - Fatal编程技术网

Java 将Int转换为字符串时发生子字符串错误 for(int i=0;i

Java 将Int转换为字符串时发生子字符串错误 for(int i=0;i,java,Java,我试图找出如何将3个随机数转换成字符串,然后能够将每个随机数转换成不同的变量,但是我的lotteryNumberFinal字符串总是只设置为最后一个随机数,而不是全部三个随机数 这是我的意思的一张照片: 最简单的方法: for (int i=0; i < 3; i++) { lotteryNumber = (int)(Math.random()*10); System.out.print(lotteryNumber); lotteryNumberFinal = I

我试图找出如何将3个随机数转换成字符串,然后能够将每个随机数转换成不同的变量,但是我的lotteryNumberFinal字符串总是只设置为最后一个随机数,而不是全部三个随机数

这是我的意思的一张照片:

最简单的方法:

for (int i=0; i < 3; i++) {
    lotteryNumber = (int)(Math.random()*10);
    System.out.print(lotteryNumber);

    lotteryNumberFinal = Integer.toString(lotteryNumber);
} 

System.out.println(lotteryNumberFinal);  
lotteryNumberFinal=“”;
对于(int i=0;i<3;i++){
lotteryNumber=(int)(Math.random()*10);
系统输出打印(乐透号码);
乐透号码最终+=乐透号码;
} 
System.out.println(彩票号码最终);
请注意,现在不需要进行Integer.toString转换,因为在将int转换为另一个字符串时,int将被强制转换为字符串表示形式


然后,如果需要,可以使用子字符串获取单个数字。。。但数组将是正确的方法

您正在for循环中分配lotteryNumber,这就是为什么它会覆盖该值并保留最后一个值。在您希望所有的lotteryNumberFinal变量都包含在lotteryNumberFinal变量中的情况下,您可以使用下面的代码。在这种情况下,您不需要显式的整数到字符串的转换-

lotteryNumberFinal = "";
for(int i=0; i < 3; i++) {
        lotteryNumber = (int)(Math.random()*10);
        System.out.print(lotteryNumber);

        lotteryNumberFinal += lotteryNumber;
    } 

System.out.println(lotteryNumberFinal); 
String lotteryNumberFinal=“”//定义要连接乐透号码的字符串变量。
对于(int i=0;i<3;i++){
lotteryNumber=(int)(Math.random()*10);
系统输出打印(乐透号码);
lotteryNumberFinal+=lotteryNumber;//在这种情况下,您不需要进行整数到字符串的转换,因为它会将您的值连接到一个字符串值中,因此它会自动转换为字符串。
}

您可以使用+=代替=是,或者将字符串连接在一起,或者创建一个字符串数组,如果您想单独保留它们以备以后使用,“将每个字符串子串到不同的变量”是什么意思?firstNumber=lotteryNumberFinal.substring(0,1);secondNumber=lotteryNumberFinal.子字符串(1,2);thirdNumber=lotteryNumberFinal.子字符串(2);这很有效,非常感谢-不能做数组,因为这是我的类的一个项目,我们还没有达到数组:pTime limit on it@getlost
    String lotteryNumberFinal = "";  //define String variable where you want to concatenate your lotterNumber. 

    for(int i=0; i < 3; i++) {
        lotteryNumber = (int)(Math.random()*10);

        System.out.print(lotteryNumber);

        lotteryNumberFinal += lotteryNumber; // in this case you don't need to do Integer to String conversion because it will concatenate your value in a String value so it will automatically converted into string.
}