Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
Hi,
im needing to make a java program that works with random numbers. Im trying to generate random numbers then have the program so a user manually guesses each number.
I have came up with this piece of code to generate numbers....
import java.util.Random;
import java.io.*;public static void main(String[] args){
Random rand = new Random();
int randNum1=rand.nextInt(9);
int randNum2=rand.nextInt(9);
int randNum3=rand.nextInt(9);
}
}This works fine for generating the numbers but im gettin into difficulty trying to do the guessing bit....
I need a loop so that the 1st number has to be correct then the 2nd number then the 3rd, ie in order. It needs to tell the user if they are correct or not then if they are, move them onto the next number. I also need a count for how many guesses they make in total.
If anyone has any ideas on how i could do this i would be extrememly greatful.
Thanks
Best Wishes.

A quick example.. I'll let you fill in the rest.
import java.util.Random;
import java.io.*;
import java.util.*;
import java.lang.*;
import java.text.*;public class NumGuess {
public static void main(String[] args) {
try{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));Random rand = new Random();
int randNum1=rand.nextInt(9);
int randNum2=rand.nextInt(9);
int randNum3=rand.nextInt(9);boolean done=false;
boolean firstCorrect=false;
boolean secondCorrect=false;
boolean thirdCorrect=false;int guessCount=0;
do{
System.out.println("Numbers(just for reference.. remove later on): "+randNum1+" "+randNum2+" "+randNum3);
System.out.println("Enter you guess: ");
String guessString="";
int guessInt=0;
boolean badInput=false;
try {
guessString = br.readLine();
} catch (IOException ioe) {
System.out.println("IO error, quitting!");
System.exit(1);
}
try{
guessInt=Integer.parseInt(guessString);
} catch(NumberFormatException nfe){
badInput=true;
System.out.println("Numbers Only!");
}
if(!badInput){
if(!firstCorrect){ //match it!
if(guessInt == randNum1){
firstCorrect=true;
System.out.println("Got the first one!");
done=true;
}
}
//Try to match the rest.....
}
} while(!done);
} catch (Exception e){
System.out.println("Could not recover from error!");
}
}
}

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |