简体   繁体   English

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

[英]check if random number is equal to a specific number. java

Building a program that can check if a random number is = to a specific number. 构建一个可以检查随机数是否=等于特定数字的程序。 Here is what I have so far. 这是我到目前为止所拥有的。 I am generating a random number 10 times. 我正在生成一个随机数10次。 And I want it to print out "The number (int var) was found (How ever many times it generated) times.". 而且我希望它打印出“发现(int var)次(产生了多少次)次”。 I keep running into problems such as trying to pull static variable from non-static variable. 我一直遇到问题,例如试图从非静态变量中提取静态变量。 I'm not sure how to check if the integer is = to the random number. 我不确定如何检查整数是否等于随机数。

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


}

You should try something like: 您应该尝试类似的方法:

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

Just compare val with the random number generated and see if they are equal in the if() {...} , keep a counter to keep track of how many times the random number was equal to val . 只需将val与生成的随机数进行比较,然后在if() {...}查看它们是否equal ,请保留一个counter以跟踪该随机数等于val

@thegauravmahawar 's answer seems decent and interesting. @thegauravmahawar的答案似乎不错而且很有趣。

Nonetheless, here's a suggestion on how to enhance your code: 尽管如此,以下是有关如何增强代码的建议:

(Don't mind if it's got any minor errors; I wrote it all on nano) (不要介意是否有任何小错误;我全都在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

}

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM