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

时间:2015-10-17 04:16:43

标签: java for-loop random numbers

构建一个程序,可以检查随机数是否=特定数字。这是我到目前为止所拥有的。我生成一个随机数10次。我希望它打印出来“找到了数字(int var)(它产生了多少次)。”我一直在遇到诸如尝试从非静态变量中提取静态变量的问题。我不知道如何检查整数是否=随机数。

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);
    }


}

2 个答案:

答案 0 :(得分:1)

你应该尝试类似的东西:

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与生成的随机数进行比较,看看它们equal中是if() {...},保留counter即可跟踪随机数的次数等于val

答案 1 :(得分:0)

@thegauravmahawar的回答看似体面而有趣。

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

(不要小心,如果它有任何小错误;我把它写在纳米上)

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

}

}