检查随机数是否等于特定数字。 java

check if random number is equal to a specific number. java

构建一个可以检查随机数是否等于特定数字的程序。这是我到目前为止所拥有的。我生成了一个随机数 10 次。我希望它打印出 "The number (int var) was found (How ever many times it generated) times."。我让 运行 陷入诸如试图从非静态变量中提取静态变量之类的问题。我不确定如何检查整数是否等于随机数。

import java.util.Random;
public class Driver{


    public static void main(String[] args)
    {

         Loop.loop4(4);
    }

public class Loop
{

    public static void loop4(int val)
    {

        for(int iteration = 1; iteration <=10; iteration ++)
        {
            Random number = new Random(); 
            number.nextInt(10);
        }

        System.out.println("The number " + val +" was found " (Dont know how to do this part);
    }


}

你应该尝试这样的事情:

int count = 0;
for(int iteration = 1; iteration <=10; iteration ++) {
   Random number = new Random(); 
   int n = number.nextInt(10);
   if(n == val) count++;
}
System.out.println("The number " + val +" was found " + count + "  number of times");

只需将val与生成的随机数进行比较,看它们是否在if() {...}中是equal,留一个counter来记录出现了多少次随机数等于 val.

@thegauravmahawar 的回答似乎很不错也很有趣。

尽管如此,这里有一个关于如何增强您的代码的建议:

(有什么小错误不要介意,我都是在nano上写的)

package loop;

import java.util.Random;

public class Loop {

public static void main(String[] args){

int number = 100, range = 100 // Type in any ints

if looper(number, range) { System.out.println("Number %i found!", number) }
else { System.out.println("Number not found!" ) }

}


public bool looper(int numberToBeFound, int range){

guard numberToBeFound<=range else { System.out.println("number to be found is
greater than range!") }

for (int i = 1; i<=range; i++) {

Random randomNumber = new Random();
randomNumber.nextInt(range)

if randomNumber == NumberToBeFound { break; return true } // Unsure if this'll work

}

return false

}

}