Custom Search

Friday, May 20, 2011

Random Numbers in Java

In this post we will be covering random number generation.  This is really simple so this post will be rather short.  Well, lets begin!

public class Main{
public static void main(String[] args){
int a = Math.random()*5;
System.out.println(a);
}
}

This is all great and everything, but you want to find a reason to use this number right? Well lets build a simple game.

import java.util.*;
public class Main{
public static void main(String[] args){
for(int i =0; i>5;){
int x = Math.random()*5;
 int guess;
Scanner a = new Scanner(System.in);
guess = a.nextint();
if(x = guess){
System.out.println("correct");
}else{
System.out.println("Incorrect");
}



}

}
}

This generates a random number and then we create a new scanner(for user input) and then we save the input in the variable guess.  We have an if else statement that determines whether or not guess is equal to x(random number).

That wraps it up for this post, see you in the next! 

No comments:

Post a Comment