随机数递增

时间:2018-11-26 18:05:59

标签: java

我一直在尝试使此脚本运行一段时间。我通常对增量没有任何问题,但是我似乎无法将其架构降低。这是我到目前为止所拥有的。

package Temper;
import java.util.Random;
import java.util.Scanner;
public class Temp {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    {
    System.out.println("I am going to store a bunch of random numbers so pick the first one ");
    Scanner in = new Scanner(System.in);
    in.nextInt();
    }
    {
        System.out.println("I know I said pick a number of your own but here are a bunch of random ones instead \n");
    {
            method1();
        }
        }
        }
    public static int method1()
        {   
            int rv = 0;
            for(int i = 0; i <= 99; i++);
            {

                Random r = new Random();
                int number = r.nextInt(100) + 1;
                System.out.println(number);
                rv = rv + number;
            }
            return rv;
        }   
 }              

当我在控制台中运行脚本时,它必须给我一个数字而不是100。 任何帮助弄清楚这一点将不胜感激。谢谢

我最终使它像这样工作:

package Increment;
import java.util.Scanner;
import java.util.Random;
public class RandomScript {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    System.out.println("I am going to store a bunch of numbers I'll let you pick the first one ");
    Scanner in = new Scanner(System.in);
    in.nextInt();

    System.out.println("I know I said you could pick the first number but here are a bunch of random numbers instead.");

    method1();
}
public static int method1()
{
    int rv = 0;
    Random r = new Random();
    for(int i = 0; i <= 25; i++)
        {
        int number = r.nextInt(100) + 1;
            System.out.println(number);
            rv = rv + number;
        }
    return rv;
}

}

1 个答案:

答案 0 :(得分:3)

在您的for(...)语句的结尾处有一个分号。

在Java中,这是

for(...);
{
    // something
}

等效于此:

for(...)
{
    ;  // null statement does nothing
}
// something

因此,在进入实例化Random并使用一次的块之前,您什么也不做100次。删除分号,使for应用于该块。

说到实例化Random,您只应该在程序中这样做一次。将Random r = new Random();移动到循环之外。否则,您每次都需要喝一口水就相当于挖一口新井,而不是效率更高的挖一口井并从中汲取所需饮料的方法。