Compare to variable from other class - java

I tried so hard but I couldn't get this to work. My method "guess" in class "Game" should compare the parameter "someInt" with the variable "x" from the class "Number". I would really appreciate any help, I have to get this done this evening. This is what I got, so far:
public class Number
{
private int x;
/**
* Constructor for class Number.
* This constructor assigns x to a new random
* number between 1 and 100
*/
public Number()
{
// The following lines creates a random number
// between 1 and 100 and assigns it to x
java.util.Random random = new java.util.Random();
x = random.nextInt(100) + 1;
}
public int getNumber(){
return x;
}
}
And my other class:
public class Game
{
private Number number;
/**
* This constructor should initialize the filed number
*/
public Game() {
Number number1 = new Number();
number1.getNumber(x);
}
/**
* This method takes a parameter "someInt" and
* compares it with the value stored in "this.number".
* If "someInt" is less than the value stored in "this.number",
* then the system should print "Your guess is too small" on the screen;
* if "someInt" is larger than that value,
* then the system should print "Your guess is too large" on the screen;
* otherwise it should print "You win!".
*/
public void guess(int someInt) {
if (someInt < x){
System.out.println("Your guess is too small");
}
else if (someInt > x) {
System.out.println("Your guess is too large");
}
else {
System.out.println("You win!");
}
}
}

Here is a modified version
public class Game
{
private Number number;
/**
* This constructor should initialize the filled number
*/
public Game() {
this.number = new Number();
}
/**
* This method takes a parameter "someInt" and
* compares it with the value stored in "this.number".
* If "someInt" is less than the value stored in "this.number",
* then the system should print "Your guess is too small" on the screen;
* if "someInt" is larger than that value,
* then the system should print "Your guess is too large" on the screen;
* otherwise it should print "You win!".
*/
public void guess(int someInt) {
if (someInt < number.getNumber()){
System.out.println("Your guess is too small");
}
else if (someInt > number.getNumber()) {
System.out.println("Your guess is too large");
}
else {
System.out.println("You win!");
}
}
}
On the other hand, you shouldn't use classes with the same names as in java.lang, as Number. It's distracting, making your code hard-readable and bug-genic.
The problems were:
Number.getNumber() does not take arguments, you provided one
You created a local object number1 while you should be operating on number.
In guess(), you used x, instead, Number.getNumber() should be used.
I recommend renaming Number to something not causing name clashes with java.lang.Number.

You have number1.getNumber(x); , but getNumber in your number class has no arguments.
In your getNumber method you have a return of x. You need to handle it in game like:
int numberToCompare; (declare below private Number number)
number1.getNumber(x); must be numberToCompare = number1.getNumber();
then you need to compare someint with numberToCompare.

this here is wrong:
public Game() {
Number number1 = new Number();
number1.getNumber(x);
}
because Number.getNumber() takes no param and must return an int (it is a GETTER)...
maybe you meant to do:
public class Game {
private int x;
private Number number;
/**
* This constructor should initialize the filed number
*/
public Game() {
Number number1 = new Number();
this.x = number1.getNumber();
}

Related

Wierd ArrayList values

Intent: The program is intended to recieve an input from the user and compare it against the contents of the ArrayList. If the input is not found, the program the input to the list and gives it a winCount of 1. The list is printed with the number of wins following it. In the end the user with the hightest wincount wins. If there is a tie a user is randomly selected.
The problem: My arrayValues are not properly stored
The Team class has been provided with the methods below :
public class Team implements Comparable<Team> {
// _-v-_-v-_-v-_-v-_-v-_-v-_-v-_-v-_-v-_-v-_-v-_-v-_-v-_-v-_-v-_-v-_-v-_
// CS 1323: Implement this method
/**
* This is the method you will fix to allow you to return the contents of
* this Team item in the nice format: "name: winCount". The current
* implementation will allow the program to compile, but it returns nothing.
*
* For example: "Sooners: 3"
*
* #return the formatted String that can then be output to the console.
*/
public String toString(String team, int wins) {
String winStatement = team + ": " + wins;
return winStatement;
}
// _-^-_-^-_-^-_-^-_-^-_-^-_-^-_-^-_-^-_-^-_-^-_-^-_-^-_-^-_-^-_-^-_-^-_
// Data fields
private String name;
private int winCount;
Team() {
name = "Sooners";
winCount = 1;
}
Team(String inputName) {
name = inputName;
winCount = 1;
}
Team(String inputName, int inputWinCount) {
name = inputName;
winCount = inputWinCount;
}
// ----------------------------------------------------
// Getters and Setters (aka Accessors and Mutators) ===
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name
* the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the winCount
*/
public int getWinCount() {
return winCount;
}
/**
* #param winCount
* the winCount to set
*/
public void setWinCount(int winCount) {
this.winCount = winCount;
}
/**
* Increments the winCount variable by one for this Team
*/
public void incrementWinCount() {
winCount++;
}
/**
* This method allows you to check to see if this Team object has the same
* name as another Team object.
*
* This method allows you to use the contains method in ArrayList to see
* if any element in an array list has the same name as a specific Team.
*
* #param o
* the other Team being compared to.
*/
#Override
public boolean equals(Object o) {
return name.equals(((Team) o).name);
}
/**
* This method allows you to check to see if this Team object has the same
* name as another Team object
*
* #param otherTeam
* one team
*/
public boolean sameName(Team otherTeam) {
return name.equals(otherTeam.name);
}
/**
* This method allows you to check to see if this Team object has the same
* name as another Team object
*
* #param team1
* one team
* #param team2
* the other team
*/
public static boolean sameName(Team team1, Team team2) {
return team1.name.equals(team2.name);
}
/**
* This method allows you to sort an ArrayList of Team items using
* Collections.sort
*
* #param o
* the other Team being compared to.
* #return -1 if this Team item should come first, +1 if this Team item
* should come after the other, and 0 if this Team item is
* equivalent to the other.
*/
#Override
public int compareTo(Team o) {
if (this.winCount < o.winCount) {
return -1;
} else if (this.winCount > o.winCount) {
return 1;
}
return 0;
}
}
I am new to reference variables and ArrayLists, so I suspect the error has something to do with them. The code is below :
public class Project6_ReeceWitcher
{
public static void main(String args[])
{
Scanner scnr = new Scanner(System.in);
Random rando = new Random();
String name = "hi";
int cycles = 0;
int value = 0;
ArrayList<Team> teams = new ArrayList<Team>();
Team myTeam = new Team();
Team thisTeam = new Team(name);
System.out.println("Welcome to the Advanced Sportsball Tracker!");
while (!name.equals("x")) // looping print statement
{ // x loop begins
System.out.println("Which team just won? (x to exit)");
name = scnr.next();
if (!teams.equals(name))
{
teams.add(thisTeam);
myTeam.setWinCount(1);
}
else if (teams.equals(name))
{
myTeam.incrementWinCount();
}
cycles++;
}// x loop ends
if (cycles == 1) // prints no data if user immediately exits
{
System.out.println("No data input");
}
System.out.println("Final Tally: "); // loop to print teams
for (Team team : teams) // FIXME
{
System.out.println(team);
}
The program runs and outputs these values
Welcome to the Advanced Sportsball Tracker!
Which team just won? (x to exit)
1
Which team just won? (x to exit)
2
Which team just won? (x to exit)
x
Final Tally:
Team#75b84c92
Team#75b84c92
Team#75b84c92
The winner is the with win(s)
However the intended output is
Welcome to the Advanced Sportsball Tracker!
Which team just won? (x to exit)
Sooners - these values are user inputs and are not printed
Which team just won? (x to exit)
Sooners -
Which team just won? (x to exit)
Cowboys -
Which team just won? (x to exit)
Bears -
Which team just won? (x to exit)
Bears -
Which team just won? (x to exit)
Cowboys -
Which team just won? (x to exit)
ThatOtherTeam -
Which team just won? (x to exit)
x
Final Tally:
ThatOtherTeam: 1
Sooners: 2
Cowboys: 2
Bears: 2
The winner is the Cowboys with 2 win(s)!
Thank you for the assistance!

Deitel Java exercise 6.30

I missed points for putting implementation in the driver class, rather than having the driver class only make calls methods in other classes. I'm not sure how to move the implementation outside of the main class. Suggestions welcome!
/*
*Deitel Chapter 6 Exercise 6.30
*/
package guess;
import java.util.Scanner;
/**
*Driver class for number guessing game
*/
public class GuessDriver {
/**
*
* #param args
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
/*
*instantiate guess class
*/
Guess Guess = new Guess();
/*
*loops program until user guesses correct number
*/
while (Guess.getGuess() != Guess.secretNumber){
/*
*takes input from user
n*/
System.out.println("Enter a number from 1 to 1000: ");
int setGuess = input.nextInt();
Guess.setGuess(setGuess);
/*
*nested if-else statements compares guess against secret number
*/
if(Guess.secretNumber < Guess.guess){
System.out.println("too high");
} else if (Guess.secretNumber > Guess.guess){
System.out.println("too low");
} else {
System.out.println("Congratulations, you win!");
}
}
}
}
/*
*Deitel Chapter 6 Exercise 6.30
*/
package guess;
import java.util.Random;
/**
* Takes in and stores an integer, sets value for random number
*/
public class Guess {
/**
*instance variable
*/
public int guess;
/**
*instance variable
*/
public int secretNumber = (int) (Math.random() * 999 + 1);
/**
*return secret number
* #return
*/
public int getSecretNumber() {
return secretNumber;
}
/**
*return guess
* #return
*/
public int getGuess() {
return guess;
}
/**
*set guess
* #param guess
*/
public void setGuess(int guess) {
this.guess = guess;
}
}
Well, first of all. I would suggest to make private all variables of the Guess class. (See that you have a getSecretNumber() method that already gives you the value of the secretNumber variable.
Secondly, you could create a public method like checkGuessing(int guess) in the Guess class. This method would take the user input, and write the answer on console ("too high", "too low", and so on).
Another option could be to add this same functionality to the setGuess method.
Finally, to ease future debugging, you should name the classes with Uppercase letters, the variables (even the instances of classes) with camelCase letters, and try that class's variables be named different than the name of the class.
So the final code could be something like this:
in GuessDriver class:
package guessdriver;
import java.util.Scanner;
/**
*Driver class for number guessing game
*/
public class GuessDriver {
/**
*
* #param args
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
/*
*instantiate guess class
*/
Guess guess = new Guess();
/*
*loops program until user guesses correct number
*/
while (guess.checkGuessing()==false){
/*
*takes input from user
n*/
System.out.println("Enter a number from 1 to 1000: ");
int setGuess = input.nextInt();
guess.setGuess(setGuess);
}
}
}
And in the Guess class:
package guessdriver;
public class Guess {
/**
*instance variable
*/
private int guessing;
/**
*instance variable
*/
private int secretNumber = (int) (Math.random() * 999 + 1);
/**
*return secret number
* #return
*/
public int getSecretNumber() {
return secretNumber;
}
/**
*return guess
* #return
*/
public int getGuess() {
return guessing;
}
/**
*set guess
* #param guess
*/
public void setGuess(int guessing) {
this.guessing = guessing;
}
public boolean checkGuessing(){
if(secretNumber < guessing){
System.out.println("too high");
return false;
} else if (secretNumber > guessing){
System.out.println("too low");
return false;
} else {
System.out.println("Congratulations, you win!");
return true;
}
}
}

Amend all values in an Arraylist

I have a lab for my Programming I class where we need to design a program that uses an ArrayList of resistances to calculate the total resistance of a parallel and series circuit. For the parallel circuit, I need to change every item in the ArrayList to its reciprocal (1/item). I got to this point and cannot seem to find why this is wrong and a possible way around it. Thanks.
**the error I get is "The method get(int) in the type ArrayList is not applicable for the arguments (double)" for the line " resistances = 1 / resistances.get(index);" **
-businesslogic class-
import java.util.ArrayList;
/**
* The class Circuit gathers the resistances of a user-defined number of
* resistors for a user-defined type of circuit and displays the total
* resistance of the circuit for the main method of the Presentation class.
*/
public class Circuit {
private double arrayListSize;
public double n;
public double sum;
public double finalSum;
public ArrayList<Double> resistances = new ArrayList<Double>();
/**
* #param initialPop
* user-defined initial population
*/
public final void setArraySize(final double alSize) {
arrayListSize = alSize;
}
public final double getArraySize() {
return arrayListSize;
}
public final void setResistors(double alResistances) {
for (n = 0; n < getArraySize(); n++) {
resistances.add(alResistances);
}
}
public ArrayList<Double> getResistors() {
return resistances;
}
public final void setPResistance(ArrayList<Double> resistances) {
for (double index : resistances) {
resistances = 1 / resistances.get(index);
}
sum = 0;
for (double i : resistances) {
sum =sum + i;
}
double finalSum = 1 / sum;
}
public final double getPResistance() {
return finalSum;
}
}
-presentation class-
import java.util.Scanner;
/**
* The Class Presentation
*/
public class Presentation {
/**
* The main class uses the Circuit class and user input
* to calculate the total resistance of a circuit.
*
* #param args
* command line arguments
*/
public static void main(final String[] args) {
Scanner keyboard = new Scanner(System.in);
Circuit resistanceTotal = new Circuit();
System.out.println("This program will calculate the"
+ " total resistance of either a parallel or "
+ " a series circuit.\n");
System.out.println("Would you like to calculate the"
+ " resistance of a parallel circuit (1) or a"
+ " series circuit (2)?");
int userChoice = keyboard.nextInt();
System.out.println("How many resistors are there in the circuit?");
resistanceTotal.setArraySize(keyboard.nextDouble());
System.out.println("Enter resistance of resistor #" + (resistanceTotal.n + 1));
resistanceTotal.setResistors(keyboard.nextDouble());
resistanceTotal.getResistors();
if (userChoice == 1) {
resistanceTotal.setPResistance(resistanceTotal.getResistors());
resistanceTotal.getPResistance();
}
if (userChoice != 1 & userChoice != 2) {
System.out.println("You must enter 1 or 2!!!");
}
keyboard.close();
}
}
Your error is in this the setPResistance method. The method arrayList.get(i) takes a int value as a parameter, and you passed it the actual value of the position, which is a double.
To replace each item in the arraylist to its reciprocal, change the method like so:
public final void setPResistance(ArrayList<Double> resistances) {
for (int c = 0; c < resistances.size(); c++) {
resistances.set(c, 1/resistances.get(c));
}
}
Java docs on the set(int index, Double element) method:
Replaces the element at the specified position in this list with the
specified element.

Java program stuck in user input loop

I'm creating a small 'game' program where a player enters a floor/room number, but when the player guess it gets stuck and loops on a single player and doesn't move to the next player and doesn't tell if the player is correct or incorrect as a guess where the dog is being held in the building.
PuppyPlay.java:
import java.util.Random;
import java.util.Scanner;
/**
* This program is used as a driver program to play the game from the
* class LostPuppy.
*
* A puppy is lost in a multi-floor building represented in the class
* LostPuppy.class. Two players will take turns searching the building
* by selecting a floor and a room where the puppy might be.
*
*/
public class PuppyPlay{
/**
* Driver program to play LostPuppy.
*
* #param theArgs may contain file names in an array of type String
*/
public static void main(String[] theArgs){
Scanner s = new Scanner(System.in);
LostPuppy game;
int totalFloors;
int totalRooms;
int floor;
int room;
char[] players = {'1', '2'};
int playerIndex;
boolean found = false;
Random rand = new Random();
do {
System.out.print("To find the puppy, we need to know:\n"
+ "\tHow many floors are in the building\n"
+ "\tHow many rooms are on the floors\n\n"
+ " Please enter the number of floors: ");
totalFloors = s.nextInt();
System.out.print("Please enter the number of rooms on the floors: ");
totalRooms = s.nextInt();
s.nextLine(); // Consume previous newline character
// Start the game: Create a LostPuppy object:
game = new LostPuppy(totalFloors, totalRooms);
// Pick starting player
playerIndex = rand.nextInt(2);
System.out.println("\nFloor and room numbers start at zero '0'");
do {
do {
System.out.println("\nPlayer " + players[playerIndex]
+ ", enter floor and room to search separated by a space: ");
floor = s.nextInt();
room = s.nextInt();
//for testing, use random generation of floor and room
//floor = rand.nextInt(totalFloors);
//room = rand.nextInt(totalRooms);
} while (!game.indicesOK(floor, room)
|| game.roomSearchedAlready(floor, room));
found = game.searchRoom(floor, room, players[playerIndex]);
playerIndex = (playerIndex + 1) % 2;
System.out.println("\n[" + floor + "], [" + room + "]");
System.out.println(game.toString());
s.nextLine();
} while (!found);
playerIndex = (playerIndex + 1) % 2;
System.out.println("Great job player " + players[playerIndex] +"!");
System.out.println("Would you like to find another puppy [Y/N]? ");
} while (s.nextLine().equalsIgnoreCase("Y"));
}
}
LostPuppy.java:
import java.util.Random; // Randomize the dog placement in building
import java.util.Scanner; // User input
/**
* This program is used as a program to play the game from the
* driver PuppyPlay.java
*
* A puppy is lost in a multi-floor building represented in the class
* LostPuppy.class. Two players will take turns searching the building
* by selecting a floor and a room where the puppy might be.
*
*/
public class LostPuppy{
private char[][] myHidingPlaces; // Defining class fields for assignment
private int myFloorLocation;
private int myRoomLocation;
private char myWinner;
private boolean myFound;
/**
* Creates constructor takes floor/room numbers inputted by user
*
* #param theFloors for number of floors
* #param theRooms for number of rooms
*/
public LostPuppy(int theFloors, int theRooms) {
Random random = new Random();
myHidingPlaces = new char[theFloors][theRooms];
// Filling array with spaces
int i;
for (i = 0; i < theFloors; i++) {
for (int k = 0; k < theRooms; k++) {
myHidingPlaces[i][k] = ' ';
}
}
myFloorLocation = random.nextInt(theFloors);
myRoomLocation = random.nextInt(theRooms);
myHidingPlaces[myFloorLocation][myRoomLocation] = 'P';
myWinner = ' ';
myFound = false;
}
/**
* Checks if room has been searched prior
*
* #param theFloors for number of floors
* #param theRooms for number of rooms
*/
public boolean roomSearchedAlready(int theFloors, int theRooms) {
boolean searchedRoom;
if (myHidingPlaces[theFloors][theRooms] == ' ') {
myHidingPlaces[theFloors][theRooms] = 'S';
searchedRoom = false;
} else {
searchedRoom = true;
}
return searchedRoom;
}
/**
* Checks if the puppy has been found
*
* #param theFloors for number of floors
* #param theRooms for number of rooms
*/
public boolean puppyLocation(int theFloors, int theRooms) {
if (myHidingPlaces[myFloorLocation][myRoomLocation] == myHidingPlaces[theFloors][theRooms]) {
myFound = true;
} else {
myFound = false;
}
return myFound;
}
/**
* Checks if floors and rooms won't throw out of bounds error
*
* #param theFloors for number of floors
* #param theRooms for number of rooms
*/
public boolean indicesOK(int theFloors, int theRooms) {
boolean indicesFit;
if (theFloors < numberOfFloors() && theRooms < numberOfRooms()) {
indicesFit = true;
} else {
indicesFit = false;
}
return indicesFit;
}
/*
* Checks # of floors and returns it
*/
public int numberOfFloors() {
return myHidingPlaces.length;
}
/*
* Checks # of rooms and returns it
*/
public int numberOfRooms() {
return myHidingPlaces[0].length;
}
/**
* Checks which player found the dog and won, or if not checks to see what player
* guessed wrong and puts their # in the box
*
* #param theFloors for number of floors
* #param theRooms for number of rooms
* #param thePlayer for 1st or 2nd player
*/
public boolean searchRoom(int theFloors, int theRooms, char thePlayer) {
if (myHidingPlaces[myFloorLocation][myRoomLocation] == myHidingPlaces[theFloors][theRooms]) {
myFound = true;
myWinner = thePlayer;
} else {
myHidingPlaces[theFloors][theRooms] = thePlayer;
myFound = false;
}
return myFound;
}
/*
* toString displays the current hidingPlaces array and it’s contents EXCEPT
* the location of the puppy which remains hidden until he/she is found at
* which point toString will be called (by the driver) and both the player
* who found the puppy and a ‘P’ will be displayed in the same cell….
*
*
*
*/
public String toString() {
return null;
}
}
To run this code you'll need to put both codes with their respective posted names and run PuppyPlay.java with LostPuppy.java in the same folder FYI.
The problem lied in this place in PuppyPlay:
found = game.searchRoom(floor, room, players[playerIndex]);
playerIndex = (playerIndex + 1) % 2;
System.out.println("\n[" + floor + "], [" + room + "]");
System.out.println(game.toString());
s.nextLine();
So your program expect you to input something here, and it will keep waiting until you press enter, so you can just remove that line: s.nextLine();

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