【问题标题】:check if random number is equal to a specific number. java检查随机数是否等于特定数字。爪哇
【发布时间】:2015-10-17 04:16:42
【问题描述】:

构建一个程序,可以检查一个随机数是否 = 到一个特定的数字。这是我到目前为止所拥有的。我正在生成一个随机数 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);
    }


}

【问题讨论】:

  • 您的打印语句超出了方法范围!
  • 你需要比较numberval,每次2相等时,你需要增加一个本地计数器,然后你可以打印。
  • 哎呀!固定的。谢谢
  • 这就是我在想@Siddhartha。我会继续搞砸这个想法。谢谢。
  • 如果您遇到问题,请告诉我们

标签: java for-loop random numbers


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

【讨论】:

  • 耶,我从未使用过嵌套循环(猜猜它可能不是嵌套循环),但在 Java 中我是新手:P。虽然现在我可以看到它,但它是有道理的。谢谢!
【解决方案2】:

@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

}

}

【讨论】:

  • 哇,是的,我还不太擅长编程,但我一定会把这个答案保存在我的档案中,以备后用! ;)
  • looper() 函数的目的是在找到与所需数字对应的随机值时立即停止,返回true,如果没有发生则返回false。如果您愿意,您可以创建另一个返回 int 的类似 looper() 的函数,并让它返回一个计数器,说明找到了多少次所述值。请务必检查 int 是否为 0 或其他值!
  • 顺便说一句,您应该尝试将与该类相关的函数放入该类中。我认为创建一个新类只是为了调用一个函数/方法是没有意义的;这就是我在主类中实现循环功能的原因。
  • 您还可以使用称为“字符串插值”的方法在字符串中添加任何变量,就像我在上面所做的那样(在“数字 %i 找到!”处)。可以帮助您编写更简洁、更简洁的代码。
猜你喜欢
  • 1970-01-01
  • 2012-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-08
  • 1970-01-01
相关资源
最近更新 更多