Guessing game using a tester class - java

I am creating a Guessing game program in java code. I am having an issue with the main class and the tester class running. Any help would be appreciated. The instructions for the game are The computer generates a random # and the user must guess that number in 7 or fewer guesses. If the guesses exceed 7, then the game is over and the user is asked if they want to 'play again?'
Here is my guess class:
import java.util.Random;
public class Guess
{
int computersNumber; // A random number picked by the computer.
int usersGuess = 0; // A number entered by user as a guess.
int guessCount = 0; // Number of guesses the user has made.
Random random = new Random();
int randomNumber = random.nextInt(100);
public Guess(int n)
{
usersGuess = n;
}
public boolean getGuess()
{
boolean isValid = false;
if (isValid)
{
return false;
}
if (usersGuess == computersNumber)
{
return true;
}
return isValid;
}
public boolean isGuessCorrect()
{
return getGuess() == computersNumber;
}
public int getCount()
{
guessCount ++;
return guessCount;
}
boolean playAgain;
}
Tester/main class:
import java.util.Scanner;
public class GuessTester
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Let's play a game!");
System.out.println();
System.out.println("The computer will generate a number between 0 and 100. You will have up to seven guesses"
+ "to figure out what the number is. Good luck!");
System.out.println();
System.out.print("What is your first guess? ");
int n = in.nextInt();
Guess guess = new Guess(n);
if (guess.getGuess == computersNumber)
{
System.out.println("That's Correct! ");
}
if (getCount == 7)
{
System.out.println("You lose, you didn't get the number in 7 guesses.");
}
System.out.println("Would you like to play again? ");
in.nextBoolean();
System.out.println();
System.out.println("Thanks for playing.");
in.close();
}
}

There are a few things in your code that don't compile. Did you post all your code?
First things first: if you have a class Guess and you want to access its methods, you need to instantiate an Object of that class first:
int n = in.nextInt();
Guess guess = new Guess(n);
Next, in order to actually access a method of guess it is written like this:
if (guess.getGuess() == computersNumber) {
System.out.println("That's Correct! ");
}
However in your example, the variable computersNumber is not defined in the main class but it is a member of the Guess class. Since both the computersNumber and the method getGuess() are part of the Guess class it would be better to actually access them from within that class and do the comparison there. Maybe in a separate method:
public class Guess{
....
public boolean isGuessCorrect(){
return getGuess() == computersNumber;
}
}
Another thing I saw in your Guess class is that you access some boolean variable in getGuess(), which is not defined:
if (!isValid) {
return false;
}
Where does isValid come from? where is it defined?
Edit: a little hint for the road:
You can generate a random number between 0 and 100 like this:
Random random = new Random();
int randomNumber = random.nextInt(100); // this will be a number between 0 and 100
int another = random.nextInt(1000); // you can reuse the random object and generate more numbers

Related

How do i increment static variables in java

I'm very new to java but i have decent experience with c++ and python. So, I'm doing a question in which im required to implement an airplane booking system, which does the following -
1.initialize all seats to not occupied(false)
2.ask for input(eco or first class)
3.check if seat is not occupied
4.if seat is not occupied allocate seat else look for next seat
5.if economy seats are booked out, ask if user wants to bump up to first class
6.if user is negative display msg "next plane is in 3hrs"
but,
package oop;
import java.util.Arrays;
import java.util.Scanner;
public class AirplaneBooking {
private final static int MAX_ECO_SEATS = 5;
private final static int MAX_FIRST_CLASS_SEATS = 3;
private final static boolean[] ECO_SEATS = new boolean[MAX_ECO_SEATS];
private final static boolean[] FIRST_CLASS_SEATS = new boolean[MAX_FIRST_CLASS_SEATS];
private static int current_eco_seat = 0;
private static int current_first_class_seat = 0;
public static void initialilze_seats(boolean[] first_class_seats, boolean[] eco_class_seats){
Arrays.fill(first_class_seats, Boolean.FALSE);
Arrays.fill(eco_class_seats, Boolean.FALSE);
}
public static void display(boolean[] seats){
System.out.print("[");
for(boolean seat : seats){
System.out.print(seat + ",");
}
System.out.println("]");
}
public static void book_seat(boolean [] seats, int current_seat){
seats[current_seat] = true;
current_seat++;
System.out.println(current_seat);
}
public static int user_input() {
Scanner input = new Scanner(System.in);
System.out.print("Enter 1 for Economy class or 2 for First class : ");
int user_seat_prefrence = input.nextInt();
if (user_seat_prefrence == 1){
if(current_eco_seat < MAX_ECO_SEATS){
book_seat(ECO_SEATS, current_eco_seat);
}
else{
System.out.println("Looks like eco seats are full, would you like to book for first class insted(1/0) ?");
Scanner next_input = new Scanner(System.in);
int user_next_seat_prefrence = next_input.nextInt();
if (user_next_seat_prefrence == 1){
book_seat(FIRST_CLASS_SEATS, current_first_class_seat);
user_seat_prefrence = 2;
}
else{
System.out.println("next flight leaves in 3 hrs");
}
}
}
else if (user_seat_prefrence == 2){
if (current_first_class_seat < MAX_FIRST_CLASS_SEATS){
book_seat(FIRST_CLASS_SEATS, current_first_class_seat);
}
else{
System.out.println("Looks like first class seats are full, would you like to book economy instead?(1/0)");
int user_next_seat_prefrence = input.nextInt();
if (user_next_seat_prefrence == 1){
book_seat(ECO_SEATS, current_eco_seat);
user_seat_prefrence = 1;
}
else{
System.out.println("Next flight leaves in 3hrs");
}
}
}
else {
System.out.println("Enter valid option");
}
return user_seat_prefrence;
}
public static void print_boarding_pass(int user_seat_prefrence){
if (user_seat_prefrence == 1){
System.out.println("eco");
System.out.println(current_eco_seat - 1);
}
else{
System.out.println("first class");
System.out.println(current_first_class_seat - 1);
}
}
public static void main(String args[]){
initialilze_seats(FIRST_CLASS_SEATS, ECO_SEATS);
display(FIRST_CLASS_SEATS);
display(ECO_SEATS);
while(true){
int user_seat_prefrence = user_input();
print_boarding_pass(user_seat_prefrence);
display(FIRST_CLASS_SEATS);
display(ECO_SEATS);
System.out.print("book another seat:");
Scanner choice = new Scanner(System.in);
boolean book_another_seat = choice.nextBoolean();
if (book_another_seat == false)
break;
}
}
}
The problem i'm having with this code is if the seats for eco class(for example) are full, the program is supposed to ask if i want to book for first class instead and wait for my input, if I press 1 it should book in first class but the program does not await for my input and proceeds to else statement instead.
Also, i use a static variable current_eco_seat and current_first_class_seat to keep track of the current seat being booked, and i pass that static variable to book_seat function, the program then books the seat and increments the current_eco_seat or current_first_class_seat(depending which is passed) so that next seat can be booked in next interation. But the static variable does not get incremented at all.
These are the only problems i have with the program.
Any help is appreciated, thanks
As Java calls methods by value,
Your problem about static is you are passing the value of current_seat to the book_seat method, so changing the value doesn't affect that variable after returning from the method.
To solve it just call the method and do not pass your static vars. It's static, so you have access it from everywhere.
i.e:
public static void book_seat(boolean [] seats){
seats[current_seat] = true;
current_first_class_seat++;
System.out.println(current_seat);
}
Checking Inout stream
Not sure wether your question is related to "static" variables or more related to "How to handle Input Stream?".
Regarding:
if I press 1 it should book in first class but the program does not await for my input and proceeds to else statement instead.
You should think about "flushing" the Input Stream before reading again. flush-clear-system-in-stdin-before-reading
Method Parameter usage
On the other hand this method is wrong
public static void book_seat(boolean [] seats, int current_seat){
seats[current_seat] = true;
current_seat++;
System.out.println(current_seat);
}
this command has no affect, but printing an information to the User. The variable you used in the caller "current_eco_seat" will not change at all.
you don't need to insist incrementing the exact variable, just do the following :
make book_seat() to return incremented value
public static int book_seat(boolean [] seats, int current_seat) {
seats[current_seat] = true;
System.out.println(current_seat + 1);
return current_seat + 1;
}
set returned value to current_first_class_seat or current_eco_seat
if (current_first_class_seat < MAX_FIRST_CLASS_SEATS){
current_first_class_seat = book_seat(FIRST_CLASS_SEATS, current_first_class_seat);
}
else{
System.out.println("Looks like first class seats are full, would you like to book economy instead?(1/0)");
int user_next_seat_prefrence = input.nextInt();
if (user_next_seat_prefrence == 1){
current_eco_seat = book_seat(ECO_SEATS, current_eco_seat);
user_seat_prefrence = 1;
}
else{
System.out.println("Next flight leaves in 3hrs");
}
}
Then you can use book_seat() for both eco and first class reservations handling as previously you have intended.

Println printing multiple times instead of increasing for each loop

I'm trying to make this code print out the number of games played (gameNum). Instead, it always sets gameNum to 2, and prints out the last println the number of times that the game was played. I feel like I made a dumb mistake here, but I am having trouble finding it. Could you please give me a hint instead of the answer? I'd like to figure this out on my own. If not, then feel free to go ahead and write the answer.
Thanks!
import java.util.*;
public class Testing_gameNum {
public static final int amt = 1;
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
guessCounter(console);
}
public static int game(Scanner console) {
Random rand = new Random();
int guess = 0;
int guessNum = 0;
System.out.printf("I'm thinking of a number...", amt);
System.out.println();
int num = 1;
do {
System.out.println("Your guess? ");
guess = console.nextInt();
guessNum += guessNum;
} while (guess != num);
return guessNum;
}
public static void guessCounter(Scanner console) {
int gameNum = 1;
int guessNum = game(console);
if (guessNum == 1){
System.out.printf("You won in %d guesses!", guessNum);
System.out.println();
}
gameNum = gameNum + 1;
System.out.println("Do you want to play again?");
String play = console.next();
if (play.equals("y")) {
guessCounter(console);
}
System.out.println("Number of games: " + gameNum);
}
}
Try something like this:
public class Testing_gameNum
{
public static final int amt = 1;
public static void main(String[] args)
{
Scanner console = new Scanner(System.in);
guessCounter(console);
}
public static int game(Scanner console)
{
Random rand = new Random();
int guess = 0;
int guessNum = 0;
System.out.printf("I'm thinking of a number...", amt);
System.out.println();
int num = 1;
do
{
System.out.println("Your guess? ");
guess = console.nextInt();
guessNum += amt;
}
while (guess != num);
return guessNum;
}
public static void guessCounter(Scanner console)
{
int gameNum = 1;
do
{
int guessNum = game(console);
if (guessNum == 1)
{
System.out.printf("You won in %d guesses!", guessNum);
System.out.println();
}
gameNum = gameNum + 1;
System.out.println("Do you want to play again?");
String play = console.next();
}
while (play.equals("y"))
System.out.println("Number of games: " + gameNum);
}
}
Check for every place gameNum is used. I found it i.e. in the method guessCounter(Scanner console) - and only there.
So every time you call this method, the value of gameNum is initialized to 1. After the game is won, you increment it by 1 and later on print it, hence the 2 in the output.
Move int gameNum = 1; out of the method guessCounter(Scanner console). This should help.
Aside of this please review also the code block
if (play.equals("y")) {
guessCounter(console);
}
Imagine a player goes on and on, always selecting "y". With every game round, you create another level of recursion. This "do you want to play again" could be implemented by a do-while loop, this will avoid the recursion.
You've defined guessCounter to be a recursive method, but that's probably not what you want for several reasons. First, each time you call guessCounter, you're creating a new gameNum and setting it to 1. You play the game and increment it to 2, but then recurse and never touch that variable again, which is the cause of your bug. Additionally, (although this is unlikely to happen in usual play), you could overflow your stack if you play the game enough times. Each time you play the game, the computer needs to remember the point in code that it needs to return to when it completes that call of guessCounter. Eventually you will run out of memory to store those pointers. Recursion is good for certain problems, but it's better to use loops most of the time.
How about using a loop rather than recursion.
I solved my question! Here's the code (explanation below):
public class Testing_gameNum {
public static final int amt = 1;
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
guessCounter(console);
}
public static int game(Scanner console) {
Random rand = new Random();
int guess = 0;
int guessNum = 0;
System.out.printf("I'm thinking of a number...", amt);
System.out.println();
int num = 1;
do {
System.out.println("Your guess? ");
guess = console.nextInt();
guessNum ++;
} while (guess != num);
return guessNum;
}
public static void guessCounter(Scanner console) {
int gameNum = 0;
String play = "y";
do {
int guessNum = game(console);
gameNum += 1;
if (guessNum == 1) {
System.out.printf("You won in %d guesses!", guessNum);
System.out.println();
}
System.out.println("Do you want to play again?");
play = console.next();
} while (play.equals("y"));
System.out.println("Number of games: " + gameNum);
}
}
MY PROBLEMS: gameNum was resetting each time I called guessCounter. I needed a do/while loop; that way, I could initialize gameNum inside the method, and then loop only the section of the method that needed to be repeated. The repetitive println was linked with that same issue: it was reprinted each time I called guessCounter, as opposed to just the part of the code I wanted repeated.
Thanks for your help, everyone!

Guess My number exercice 5-7 in think Java

i'm learning Java with the book think Java : how to think like a computer scientist ? and there is no exercise answers in the book, usually i end up finding similar exercices on different websites but not for this one because i have precise instructions. Can you please tell me if it's correct.
I think the problem is solved, the job is done, but is there an easier way to do it ?
Thanks a lot
Exercise 5-7.
Now that we have conditional statements, we can get back to the “Guess My Number” game from Exercise 3-4.
You should already have a program that chooses a random number, prompts the user to guess it, and displays the difference between the guess and the chosen number.
Adding a small amount of code at a time, and testing as you go, modify the program so it tells the user whether the guess is too high or too low, and then prompts the user for another guess.
The program should continue until the user gets it right. Hint: Use two methods,
and make one of them recursive.
import java.util.Random;
import java.util.Scanner;
public class GuessStarter {
public static void Lower(int number,int number2) {
Scanner in = new Scanner(System.in);
System.out.print("Too Low , try again ");
number2 = in.nextInt();
if (number2==number) {
System.out.println("You're right");}
else if (number2>number)
Higher(number,number2);
else
Lower(number,number2); }
public static void Higher(int number,int number2) {
Scanner in = new Scanner(System.in);
System.out.print("Too high , try again ");
number2 = in.nextInt();
if (number2==number) {
System.out.println("You're right");}
else if (number2>number)
Higher(number,number2);
else
Lower(number,number2); }
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Random random = new Random();
int number = random.nextInt(100) + 1;
int number2;
System.out.print("Type a number: ");
number2 = in.nextInt();
if (number2==number) {
System.out.println("You're right");}
else if (number2>number)
Higher(number,number2);
else
Lower(number,number2);}
}
Don't know if it'll be useful now or not, but, as I was solving the same solution, thought of letting it know if someone finds it useful:
import java.util.Random;
import java.util.Scanner;
/**
* Created by RajU on 27-Jun-17.
*/
public class GuessNumber2 {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
message("I'm thinking of a number between 1 and 10 (including both).\n" +
"Can you guess what it is?\n" +
"Type a number: ");
int userNumber = input.nextInt();
tryAgain(userNumber, calculateRandom(10));
}
public static int calculateRandom(int n) {
Random random = new Random();
return random.nextInt(n) + 1;
}
public static void tryAgain(int userNumber, int generateRandom) {
if (userNumber == generateRandom) {
message("You're absolutely right!");
} else {
if (userNumber > generateRandom) {
message("Think of a lesser number: ");
} else {
message("Think of a greater number: ");
}
userNumber = input.nextInt();
tryAgain(userNumber, generateRandom);
}
}
public static void message(String m) {
System.out.print(m);
}
}
I just completed this exercise. It's pretty interesting to see some different approaches! Here's my take on it:
import java.util.Random;
import java.util.Scanner;
public class GuessGameLevelUp {
/*
* A guessing game where you try to guess a random number between and including 1 and 100.
* This version allows you to continue guessing until you get the right answer.
* When you're off, a hint will let yet know whether your most recent guess was too high or low.
*/
public static void main (String [] args) {
//Generates a random number for the game
Random random = new Random();
int answer = random.nextInt(100) +1;
//Introduces the game and gives a prompt
System.out.println("I'm thinking of a number between and including "
+ "1 and 100, can you guess which?");
System.out.print("Take a guess: ");
//Enables guess value input and parrots guess
Scanner in = new Scanner(System.in);
int guess;
guess = in.nextInt();
System.out.println("Your guess is: "+guess);
//Stacks a new class to determine the outcome of the game
tooHighTooLow(answer, guess);
}
public static void tooHighTooLow(int a, int g) {
//Triggers and parrots guess if correct
if (a==g) {
System.out.print("Correct! The number I was thinking of was: "+g);
//Triggers "Too Low" prompt and uses recursive to offer another attempt
} else if (a>g) {
System.out.print("Too Low! Try again: ");
Scanner in = new Scanner(System.in);
g = in.nextInt();
System.out.println("Your guess is: "+g); //Parrots guess
tooHighTooLow(a, g);
//Triggers "Too High" prompt and uses recursive to offer another attempt
}else
System.out.print("Too high! Try again: ");
Scanner in = new Scanner(System.in);
g = in.nextInt();
System.out.println("Your guess is: "+g); //Parrots guess
tooHighTooLow(a, g);
}
}
I got stuck on this one too, but your code helped me in arriving at a solution. Here's what I came up with:
import java.util.Random;
import java.util.Scanner;
public class Ch5Ex7 {
public static void compareNumbers(int userNumber,int randomNumber) {
if(userNumber == randomNumber) {
System.out.println("You got it!");
} else if ( userNumber > randomNumber ) {
System.out.println("Too high. Guess again: ");
Scanner in = new Scanner(System.in);
userNumber = in.nextInt();
compareNumbers(userNumber, randomNumber);
} else {
System.out.print("Too low. Guess again: ");
Scanner in = new Scanner(System.in);
userNumber = in.nextInt();
compareNumbers(userNumber,randomNumber);
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Random random = new Random();
int randomNumber = random.nextInt(100) + 1;
int userNumber;
System.out.print("Type a number: ");
userNumber = in.nextInt();
compareNumbers(userNumber, randomNumber);
}
}
Thanks for pointing me in the right direction!

if statement not working properly with variables from another method

I'm totally new to Java (4 days old), and I'm trying to create my first program after watching a few YouTube videos.
Basically I'm trying to make a (guess my number game). I've created a function/method to get a random number and another function/method to get a user inputted number (both from another class called random)
I've then called these 2 values in my main method/function to be compared in a (if) statement but every time I run the program I get the same output.
Output:
Welcome to The Guessing Game
*******Version 1.1**********
Enter your name please :
john
Nice to meet you john
Ok then....let's go over the rules
I'm gonna pick a number between 1 and 10
You have 4 atempts to guess otherwise i win
Good luck!!!!
Ok i've chosen the number between 1 and 10
take a guess :
2
You are correct!!!!
I seem to get the same output every time ;-(
Sorry in advance for asking a maybe straight forward question.
(Do remember I'm a newbie and many thanks for your help.)
shaz
Below is a copy of my code:
public class GuessMain {
public static void main(String[] args) {
introduction intro = new introduction();
intro.welcome();
introduction enterName = new introduction();
enterName.userName();
introduction rules = new introduction();
rules.explainRules();
// introduction getN = introduction();
// getN.getName();
introduction glMessage = new introduction();
glMessage.goodluckMessage();
random pickRandNumber = new random();
pickRandNumber.pickRandom();
random readyMessage = new random();
readyMessage.readysteadyGo();
random guessNumobj = new random();
guessNumobj.getGuessnum();
random getNumobj = new random();
getNumobj.getNumber();
}
if (guessNumobj.getGuessnum() == getNumobj.getNumber()){
System.out.println("You are correct!!!!");
}else if (guessNumobj.getGuessnum() > getNumobj.getNumber()){
System.out.println("Too high!!!!");
}else if (guessNumobj.getGuessnum() < getNumobj.getNumber()){
System.out.println("Too low!!!!");
}
}
}
import java.util.Scanner;
public class introduction {
private String name;
public void welcome() {
System.out.println("Welcome to The Guessing Game");
System.out.println("*******Version 1.1**********");
}
public void userName() {
System.out.println("Enter your name please :");
Scanner userInput = new Scanner(System.in);
name = userInput.nextLine();
System.out.println("Nice to meet you " + name);
}
public void explainRules() {
System.out.println("Ok then....let's go over the rules");
System.out.println("I'm gonna pick a number between 1 and 10");
System.out.println("You have 4 atempts to guess otherwise i win");
}
public String getName() {
return this.name;
}
public void goodluckMessage() {
System.out.println("Good luck!!!! ");
}
}
import java.util.Random;
import java.util.Scanner;
public class random {
private int number;
private int guessNum;
public void pickRandom () {
Random getRandom = new Random();
for (int counter = 1; counter <= 1; counter++) {
number = getRandom.nextInt(10); //this stores the random number[(10){1 to 10}] in (number;) vairiable
}
}
public void readysteadyGo(){
System.out.println("Ok i've chosen the number between 1 and 10");
System.out.println("take a guess :");
Scanner scanOb = new Scanner(System.in);
guessNum = scanOb.nextInt();
}
public int getNumber(){
return this.number;
}
public int getGuessnum(){
return this.guessNum;
}
}
random is a class, and you can have any number of instances (objects) of that class. Each instance contains its own versions of number and guessNum. If you create two new random() objects, object1 and object2, and you do something that assigns to object1.number, and then you look at the value of object2.number, it will not be the value that you assigned to object1.number.
That's the problem with your code. You create one object pickRandNumber, and then call a method that sets pickRandNumber.number. You create another object readyMessage and then call a method that asks for user input and then sets readyMessage.guessNum. Then you create two new objects, and try to get the number and guessNum from the new objects. Those new objects have their own number and guessNum values, which you haven't set to anything--you've set the values of number and guessNum in different objects.
The solution is to rewrite main() to use the right objects. So after
random pickRandNumber = new random();
pickRandNumber.pickRandom();
that will set pickRandNumber.number, and if you want to retrieve that number, use something like:
if (pickRandNumber.getNumber() == ....)

java number guessing game with joptionpane allways says my input is 0 and i win even if its wrong?

I have to create a program that asks for a number between 1 and 10.
A random number between 1 and 10 is generated and it should then output if I have guessed correctly
with my guessed number and the secret number displayed.
Also, it should output if I have guessed too high or too low with the secret number displayed.
I have to use joptionpane in the main class with the calculations and comparisons done in an instantiable class. also I have to use else and if-statements.
I have written the code but it outputs 0 as the guessed number no matter what number I choose also it tells me that I have guessed correctly even if i have it wrong.
here are the two sets of code I have written.
import javax.swing.JOptionPane;
public class GuessApp{
public static void main(String args[]){
int guessNum, secretNum, correct, tooHigh, tooLow;
Guess myGuess;
myGuess = new Guess();
guessNum = Integer.parseInt(JOptionPane.showInputDialog(null,"Please enter a number between 1 and 10"));
myGuess.setGN(guessNum);
myGuess.compute();
guessNum = myGuess.getGuessNum();
secretNum = myGuess.getSecretNum();
tooHigh = myGuess.getTooHigh();
tooLow = myGuess.getTooLow();
correct = myGuess.getCorrect();
if (guessNum==correct){
JOptionPane.showMessageDialog(null,"Congratulations your number is"+guessNum+"and the secret number is"+secretNum+"you have won the game");
}
else if (tooHigh==guessNum){
JOptionPane.showMessageDialog(null,"I'm sorry you have guessed too high, your number is"+guessNum+"and the secret number is"+secretNum);
}
else if (tooLow==guessNum){
JOptionPane.showMessageDialog(null,"I'm sorry you guessed too low, your number is"+guessNum+"and the secret number is"+secretNum);
}
}
}
public class Guess{
private int guessNum, correct, tooHigh, tooLow, secretNum;
public Guess(){
guessNum = 0;
}
public void setGN(int guessNum){
this.guessNum = guessNum;
}
public void setSN(int secretNum){
this.secretNum = secretNum;
}
public void setCT(int correct){
this.correct = correct;
}
public void setTH(int tooHigh){
this.tooHigh = tooHigh;
}
public void setTL(int tooLow){
this.tooLow = tooLow;
}
public void compute(){
guessNum = guessNum;
secretNum = (int)(Math.random()*((10 - 1) +1)+1);
if ((secretNum<guessNum)){
guessNum = tooHigh;
}
else if ((secretNum>guessNum)){
guessNum = tooLow;
}
else if ((secretNum==guessNum)){
guessNum = correct;
}
}
public int getGuessNum(){
return guessNum;
}
public int getSecretNum(){
return secretNum;
}
public int getTooHigh(){
return tooHigh;
}
public int getTooLow(){
return tooLow;
}
public int getCorrect(){
return correct;
}
}
I have just started a java class so I'm new to this.
Any help would be greatly appreciated.
Thanks in advance.
ints are initialized to 0. In your compute method no matter what guessnum is going to be set to 0 because it will be one of those three things. Then the first if will always be true because everything at this point is set to 0. I would suggest rewriting it a bit and using too high too low and correct as bools instead of ints. That would allow you to find the answers more clearly.
public void compute(){
guessNum = guessNum;
secretNum = (int)(Math.random()*((10 - 1) +1)+1);
if ((secretNum<guessNum)){
tooHigh = true;
}
else if ((secretNum>guessNum)){
tooLow = true;
}
else if ((secretNum==guessNum)){
correct = true;
}
}
You aren't setting your fields (guessNum, correct, tooHigh, etc) in your Guess class so inside compute you are basically always setting guessNum to 0. Then you say getCorrect which returns 0 and you compare 0 to 0. You do set secretNum to the random value. So you will always get the case that guessNum and correct both come back 0 but secretNum is a random number.
Without setting int fields (variables that are "owned" by a class rather than in the scope of a method) yourself they are automatically initialized to 0. Primitive types in a method do not initialize automatically but the rules are different for fields. Arrays of primitive numbers also initialize all elements to 0 whether they are a field or in a method.
I would suggest simplifying your Guess class (if a class is necessary for some reason). Here is a much simplified version:
public class GuessMySecret {
private int secret = (int)(Math.random() * 10) + 1;
// constructors can be omitted if they don't have to do anything
public boolean isTooLow(int guess) {
return guess < secret;
}
public boolean isTooHigh(int guess) {
return guess > secret;
}
}
// in main
int yourGuess = /* get your number */ ;
GuessMySecret mySecret = new GuessMySecret();
if (mySecret.isTooLow(yourGuess)) {
// respond
} else if (mySecret.isTooHigh(yourGuess)) {
// respond
} else {
// presume to be correct
}
Though if you want to have multiple rounds using this model you have to either make a new object each time or have the class able to generate a new number.
Here is some hint.
You should first generate a random number between 1 and 10.
Populate the guess number enterd
Comparion the guess number enterd with random number. If they are equal then show congratulation information.
If they are not equal. Then compare guess number with highest number and lowest number. And I think the tooHigh and tooLow shuold be declared as boolean type.
4.Use the boolean flags populated in step#3, you can know whether the number is correct or too high or too low.
In your code, what the values for tooHigh, tooLow etc. They are always zeros.
Change some logic in method compute in Guess class. And have a try then.
An example is below:
Guess class
public class Guess {
private int secretNum = 0;
public Guess() {
generateSecretNum();
}
/**
* generate a secret number
*/
public void generateSecretNum() {
secretNum = (int) (Math.random() * ((10 - 1) + 1) + 1);
}
public boolean isTooHigh(int guessNum) {
return guessNum > secretNum;
}
public boolean isTooLow(int guessNum) {
return guessNum < secretNum;
}
/**
* #return the secretNum
*/
public int getSecretNum() {
return secretNum;
}
/**
* #param secretNum
* the secretNum to set
*/
public void setSecretNum(int secretNum) {
this.secretNum = secretNum;
}
}
GuessApp class
import javax.swing.JOptionPane;
public class GuessApp {
public static void main(String args[]) {
// Store the value user entered
int guessNum = 0;
// When an instance of Guess is created. A secret number is generated as
// well.
Guess myGuess = new Guess();
guessNum = Integer.parseInt(JOptionPane.showInputDialog(null,
"Please enter a number between 1 and 10"));
if (myGuess.isTooHigh(guessNum)) {
// Too High
JOptionPane.showMessageDialog(null,
"I'm sorry you have guessed too high, your number is"
+ guessNum + "and the secret number is "
+ myGuess.getSecretNum());
} else if (myGuess.isTooLow(guessNum)) {
//Too Low
JOptionPane.showMessageDialog(null,
"I'm sorry you guessed too low, your number is" + guessNum
+ "and the secret number is "
+ myGuess.getSecretNum());
} else {
//Equal to secret number
JOptionPane.showMessageDialog(null,
"Congratulations your number is" + guessNum
+ "and the secret number is "
+ myGuess.getSecretNum() + "you have won the game");
}
}
}

Categories