pewpew
pewpew

Reputation: 730

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. And I want it to print out "The number (int var) was found (How ever many times it generated) times.". 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);
    }


}

Upvotes: 0

Views: 3163

Answers (2)

Ophir Neto
Ophir Neto

Reputation: 23

@thegauravmahawar 's answer seems decent and interesting.

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)

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

}

}

Upvotes: 0

thegauravmahawar
thegauravmahawar

Reputation: 2823

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.

Upvotes: 1

Related Questions