Couldnt find the Error in Guess Game Class - java

Okay, this is part of the full code of a guessing game.
public static void Game(){ //Second page of game with option of continue playing when guessed close enough to answer.
Scanner scan = new Scanner(System.in);
GuessingGame testgame=new GuessingGame();
testgame.Generator();
int num = testgame.GetGenNum();
//Produces a random number between 1 and 100 inclusive of 1 and 100
System.out.println("Guess the target integer which is between 1 and 100 inclusive");
int guess=scan.nextInt();
int difference=(guess-num);
while(guess!=num){
int yesCounter=0;
System.out.println("Guess again " +num+" "+difference);
guess=scan.nextInt();
difference=(guess-num);
///something wrong here, shouldnt repeat if difference too big
if(difference<=5||difference>=-5){ //something wrong with the condition, it says its close enough even tho it isnt.
while(yesCounter<1){
System.out.println("Close enough, do you want to keep Guessing? Y/N ");
yesCounter++;
String play = scan.nextLine();
//play=play1;
while(!(play.equalsIgnoreCase("y")))
{
if(play.equalsIgnoreCase("n")){
System.exit(1);
}
else{
if((play.equalsIgnoreCase("y"))){
invalid();
guess=scan.nextInt();
}
else{
Game(); ///TAKE note as it might restart the game with new random integer
}
}
}
}
}
}
output is:
.........................
Play? Y/N
y
Guess the target integer which is between 1 and 100 inclusive
50
Guess again 44 6
44
Close enough, do you want to keep Guessing? Y/N
Guess the target integer which is between 1 and 100 inclusive
..........................
the problem is, when user guess a number, the condition is if the difference between the guess and the generated number is 5 or smaller, tell user that its close enough, and ask if user wants to continue guessing, but the condition wasn't fulfilled and yet still runs, can someone help?

while(!(play.equalsIgnoreCase("y")))
{
if(play.equalsIgnoreCase("n")){
System.exit(1);
}
else{
if((play.equalsIgnoreCase("y"))){
invalid();
guess=scan.nextInt();
....
That isn't right, if((play.equalsIgnoreCase("y"))) can never be true, since the loop it is in, explicitely cannot be entered if it is true. That's where your problem is, it will always restart the game because it calls Game() in the else-branch. In short, this is what you do:
boolean _true = true;
while(! _true) {
if(_true) {
//impossible
}
else {
Game(); //ALWAYS
}
}
Since you tagged your question with homework, I will not give the full correction, but now you know where it goes wrong, you should be able to figure out what you need to change in order to advance :)

You mixed or and and (Note: The condition you used (difference<=5||difference>=-5) is always true.). You may use any of the following
if (difference<=5 && difference>=-5) { ... } # difference is 5 or less
or
if (difference<=-5 || difference>=5) { ... } # difference is 5 or more
Better readable if you use Math.abs(...) instead:
if (Math.abs(difference)<=5) { ... } # difference is 5 or less
and
if (Math.abs(difference)>=5) { ... } # difference is 5 or more
resp.

if(difference<=5||difference>=-5) This says if the difference is less than 5 or greater than -5. All numbers are less than 5 or greater than -5, so this is always true.
I'm assuming what you want is something like if(Math.abs(difference)<=5). This will tell you if the absolute value of your difference variable is less than or equal to 5.

Related

How to use while loop user input established variable out of scope (if possible)

I need to ask the user for a number of dice to roll, (at least 1) and then loop if necessary to return a positive integer. Simple question, but I'm new to Java and don't understand how to do this using a while loop and bringing my variable back into scope.
Here's what I have so far, as anyone can see my variable 'numOfDice' is never pulled back into scope, as I need it later in my program to establish a variable array length.
while (true) {
System.out.println("Hello! How many dice would you like to roll");
int numOfDice = scan.nextInt();
if (numOfDice<=0) {
System.out.println("Please enter a positive integer and try again");
}else {
break;
}
}
So as you can see my variable is never pulled back into scope, and I've tried initializing it before the while loop, with no luck. I've also tried
System.out.println("Hello! How many dice would you like to roll");
int numOfDice = scan.nextInt();
while (true) {
if (numOfDice<=0) {
System.out.println("Please enter a positive integer and try again");
}else {
break;
}
}
But this results in an infinite loop if a negative number is an input, as my if will repeat forever.
Anyways, I'm very new to Java (my 6th week learning) and any veteran help would be much appreciated. I'm willing to learn new ways to create these loops or tricks to pull variables back into scope (if possible).
Solved. Thanks to tgdavies telling me to split the declaration and assignment I was able to finish this problem. Here's the solution for anyone who stumbles upon this.
System.out.println("Hello! How many dice would you like to roll");
int numOfDice;
numOfDice = scan.nextInt();
while (true) {
if (numOfDice <= 0) {
System.out.println("Please enter a positive integer and try again");
numOfDice = scan.nextInt();
} else {
break;
}
}
This is very simple.
First you have to declare your variable outside the loop.
int numOfDice = -1;
Then you need to think of a way to update the state of your variable numOfDice inside the loop. Hence,
numOfDice = sc.nextInt();
Should be inside your loop. Now, the state of your variable numOfDice is updated. After that we can check if the value is a negative or not, and reiterate the loop accordingly.
Hence, the overall code will look like this.
int numOfDice = -1; //Declaration - value is negative because the while loop has to be executed at least once.
Scanner sc = new Scanner(System.in);
while(numOfDice<=0){ // checks if the variable is negative or positive, loop continues if the value is negative
System.out.println("Hello! How many dice would you like to roll");
numOfDice = sc.nextInt(); //updates the state of the variable
if (numOfDice<=0) {
// this line will be printed only if the value is negative.
System.out.println("Please enter a positive integer and try again");
}
}
Hope this answer is helpful.
Refer this article to understand more about while loops in java.
Let me start by showing my solution first...
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Let's start rolling some dice");
while (true) {
System.out.println("Hello! How many dice would you like to roll");
int numOfDice = scan.nextInt();
if (numOfDice < 0) {
System.err.println("Please enter a positive integer and try again");
} else if (numOfDice == 0) {
System.out.println("Goodbye!");
break;
}
}
scan.close();
}
As you can see, it is not much of a variation, but it has clear boundaries. For example, you can't have a negative number of dice rolled. So checking for the number of dice to be less than zero (negative) is an error and an appropriate message is shown when that condition is reached.
The second thing you see is a clear case for ending the "forever" loop. And that is when zero is passed through the Scanner object. Not much of an explanation required. Pass zero and simply break out of the loop.
The rest, if a positive integer is passed, keep rolling the dice!
Output sample
Let's start rolling some dice
Hello! How many dice would you like to roll
2
Hello! How many dice would you like to roll
3
Hello! How many dice would you like to roll
9
Hello! How many dice would you like to roll
-3
Please enter a positive integer and try again
Hello! How many dice would you like to roll
-2
Please enter a positive integer and try again
Hello! How many dice would you like to roll
1
Hello! How many dice would you like to roll
3
Hello! How many dice would you like to roll
0
Goodbye!
...to return a positive integer
Sorry for the dramatic heading, but I miss this from the OPs question the first time I read it. The code above keeps rolling until the user enters zero. Let's modify this so that it returns a positive integer.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Let's start rolling some dice");
while (true) {
System.out.println("Hello! How many dice would you like to roll");
int numOfDice = scan.nextInt();
if (numOfDice < 0) {
System.err.println("Please enter a positive integer and try again");
} else if (numOfDice == 0) {
System.out.println("Goodbye!");
break;
} else {
// Add some code here (i.e. a Random generation of dice values 1-6)
System.out.println("You rolled a " + diceRollValue);
break;
}
}
scan.close();
}
Variable Scope
Since the OP seems to struggle with issues related to scope, I will expand on this answer to focus on scope. Good coding practices call for minimizing the scope of variables. This means (in theory):
No global variables, period!
Local variables should be declared at the lowest possible block.
Variables shall be declared as close to the point of usage as possible.
Of course, in practice, global variables are often necessary. But what no developer should do is declare global variables by default. Instead, all variables shall be declared at the lowest levels of the code, and then "bubbled up" as needed and stop "bubbling" them up when the desired accessibility is reached. Let's look at an example from this code.
The variable numOfDice is declared inside the while loop. This is the lowest level where this variable can be declared. Since the variable is used at the top of the loop, it is OK to declare it and assign a value in the same line. The question is, should this variable be declared outside the loop? The answer is yes, for a very specific reason.
Creating a "forever" loop while(true){...} may not be a good idea. IN FACT, it can be argued that putting the break condition there might be a better coding practice than to include the break condition inside the loop. So, for this reason (and improving readability of the code as well), we might be better off setting the the variable outside the loop to a value, and then prompt the user to enter the number of rolls inside the loop like this:
System.out.println("Let's start rolling some dice");
int numOfDice = -1;
while (numOfDice != 0) {
System.out.println("Hello! How many dice would you like to roll");
int numOfDice = scan.nextInt();
...
}
Setting the value to -1 allows the instruction pointer to enter the loop because the evaluation of numOfDice returns true. Once inside the loop, it will continue to iterate until the evaluation returns false; and this is when the user enters 0. In the original code, negative values prompt an error message. Negative and positive values continue the "game". This is perfectly fine. As to the improved readability, when you see while (numOfDice != 0) the intent is clear; much better than to "hide" the break condition inside the loop. If the loop contain a lot of lines of code, the break condition is harder to find. So, in the end, this is a better solution.
An alternative is to use a do...while loop. This is the preferred structure when the intent is for the loop to run at least once. This is possible because the break condition is evaluated at the end of the loop rather than at the beginning in a conventional while loop. The equivalent do...while loop is as follows:
System.out.println("Let's start rolling some dice");
int numOfDice = 0; // initialize to the break condition value (just in case)
do {
System.out.println("Hello! How many dice would you like to roll");
int numOfDice = scan.nextInt();
...
} while (numOfDice != 0);
The last thing with regards to scope. I mentioned before that variables should be declared as close to the point of usage as possible. This means that instead of this
public void myMethod() {
int myVariable = 0
.
.
.
.
.
myVariable = someCodeThatSetsValue();
.
.
}
You should do this instead to follow best practices
public void myMethod() {
.
.
.
.
.
.
int myVariable = someCodeThatSetsValue();
.
.
}

How can if statements be executed after an else statement has met its requirements?

public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
int hankees, socks;
out.print("Hankees and Socks scores? ");
hankees = keyboard.nextInt();
socks = keyboard.nextInt();
out.println();
if (hankees > socks) {
out.println("Hankees win...");
out.print("Hankees: ");
out.println(hankees);
out.print("Socks: ");
out.println(socks);
} else {
out.println("It's a tie...");
out.print("Hankees: ");
out.println(hankees);
out.print("Socks: ");
out.println(socks);
}
if (socks > hankees) {
out.println("Socks win...");
out.print("Socks: ");
out.println(socks);
out.print("Hankees: ");
out.println(hankees);
}
keyboard.close();
}
}
I am very new to Java, but I have noticed that Java codes tend to be executed regardless of the codes that follow if the conditions are met.
So here I expected the else code to be executed ( in the case of socks> hankees)
but the if statement that follows is properly taken into account.
I would very much appreciate it if someone could explain why.
EDIT:
This is a code from a book and it is originally formatted as how everyone is pointing out(if-> else if-> else ).
I was just changing a few things around and i ran into some confusing results.
With the changed up code(first code posted) when I put in 10 for hankees and 90 for socks, the result i get is this.
Hankees and Socks scores? 10 90
Socks win...
Socks: 90
Hankees: 10
As if the else statement is not being executed(Which I do expect to be executed since the conditions are met before the last if statement)
My question is : why it is not being executed?
There is a little mistake in your algorithm. Regardless the coding language you will use the if statement will be handled from top to bottom. Then, in case of (socks > hankees) the first else block code will be executed cause the first if condition is false. Then the second else will be true so the third block code will be executed too.
It is a good time to use the else if keyword.
if(hankees > socks){
//hankees won
}
else if(hankees == socks){
//it's a tie
}
else{
//socks won
}
When I run this I get the result:
It's a tie...
Hankees: 10
Socks: 90
Socks win...
Socks: 90
Hankees: 10
So to answer your question, the else statement should and does run. You must have a slightly different code than what you posted here if you aren't getting the "It's a tie..." part.
Then your else statemnet should be the first statement then following the "if condition" or you can add a while loop.

How to pull numbers from an array

I currently have java homework that I would appreciate some help with. We are to calculate a team record scenario.
We are given the following numbers:
Team1 Points
{23,45,65,20}
Opponent Points
{20,30,20,18}
I threw these into an array. I also created a public boolean. Basically, you are to pull these points from the array to the boolean? And let the boolean decide which team won? Obviously team1 has won, but we are supposed to let the computer decide, not the human.
Here is my code:
public class TeamScore {
public static boolean Winner(int team1Points, int opponentPoints) {
if (team1Points > opponentPoints) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
// Scanner in = new Scanner(System.in);
int[] team1Points = { 23, 45, 65, 20 };
int[] opponentPoints = { 20, 30, 20, 18 };
int team1 = 1;
int opponent = 1;
for (int i = 0; i < 5; i++) {
if (Winner(team1Points[i], opponentPoints[1])) {
team1 += 1;
} else {
opponent += 1;
}
}
for (int i = 0; i < 5; i++) {
if (team1 > 0 && opponent == 0) {
System.out.println("Team 1 has the perfect record!");
} else {
System.out.println("Win" + Arrays.toString(team1Points));
System.out.println("Loss" + Arrays.toString(opponentPoints));
}
}
}
Could anyone possibly help me? I am currently in programming II, but I did not have the best teacher in programming I. Any help would be appreciated!
EDIT:
I do not think this is a duplicate question because I already can fix it by changing the variable i-->1. My problem is that the computer thinks that team1 has already won regardless of the score.
When I run the code I am getting an java.lang.ArrayIndexOutOfBoundsException error. However when I change team1Points[i] to team1Points[1] then it goes okay and tells me that "Team 1 has the perfect record!". However, if I change some of the array values for team1Points to be less than opponentPoints then it still says "Team 1 has the perfect record!".
Not sure why you have a method Winner (also as Kevin said, it should be winner because of naming conventions) which turns ´(a > b)´ into a large if-statement. Similar stuff appear elsewhere in your code.
Your variables ´team1, opponent = 1´ inexplicably start with the value 1, am I to understand this as a way for your code to imply to a reader that both teams initialize at a win? Using 0 would probably make more sense.
Your game ought to crash from an indexoutofboundsexception at ´team1Points[i]´, as you have arrays of length 4, but your loops runs 5 times (the currently used range is [0-4], inclusive). Changing your loops to i=1 won't help, as the issue is that you eventually encounter team1Points[4] due to the i < 5 statement.
I don't know what game you are modelling or how it works, but the comparison ´Winner(team1Points[i],opponentPoints[1])´ looks like a blatant error to me (you always look at the opponents score for their second round).
Why are you printing your results 5 times? If you want to print the first message only when team1 won all rounds and the point for each round otherwise, you would need to use the loops counter as an index to the arrays in second case. First case should break loop so its not written five times, in addition you don't need to check team1>0 && opponent==0 as it's enough to only check if ´opponent==0´ (speaking of this conditional, it only works if you initialize the variables at 0 as I mentioned before). You could have checked if team1 equals size of the array instead, but imo thats more of a hassle than opponent==0.
Lastly, please fix your indenting. use the preview system so you can make double sure before posting.
Edit: Kevin also brings up a good point that you should be using the length of the array in your loops second statement.

Issue with do-while loop

Please note that I while I am comfortable with Java, I am not exceptionally gifted nor do I know all the jargon, so please explain your answers with very little coder jargon and as much normal English, or explain what the jargon means after you use it. Also, this is my first time with Stackoverflow, so let me know if this was a decent question and give me some pointers.
I am taking an AP Computer Science class at my high school. We use Java. We were recently taught do-while loops and I just completed the "lab" that uses do-while loops, however, there is an issue.
Firstly, let me explain the lab. The program generates a random integer between 1-10 which the user must guess (guess is stored as an int using a scanner), there are a few integer values which track number of guesses, how many guesses were greater than the computer integer, and how many were too low. When you look at my code, you will notice that I have a System.out.println(compGen);//compGen is the computer generated int. The purpose was to test the code.
The issue is in the if-statement that compares userGen (user guess) and compGen.
if(userGen==compGen)
{
//do a lot of stuff
}
In this if-statement, it is not printing the correct SOPs that I have written IF the user guesses more than once. HOWEVER, I did not write this into the program, it seems to do it on its own. I used the SOP I mentioned early where the compGen int is printed, and I typed that in as my first guess and it worked perfectly. Everything in the if-statement block executed perfectly and printed everything correctly. However, when I did it as my second guess, third guess, or any guess that was not the first one, NOTHING was printed. See code below and run it. I don't believe this should make a difference, but the IDE that I use is Eclipse, hence the package statement. Please help.
package Chapter_3.Lab03_Chapter3;
import java.util.*;
public class Guess
{
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in);//Scanner
int compGen = (int)(Math.random()* 10 + 1);//compGen is computer number
System.out.println(compGen); //USED TO VERIFY FAILURE. VALUE WAS ENTERED TO TEST CODE
int guessTrack = 0;//tracks number of guesses
int tooHighTrack = 0;//CREATING INTS TO TRACK STUFF
int tooLowTrack = 0;
System.out.println("Welcome to the integer guessing game that everyoone loves!");//PROMPT
System.out.println("Please enter your guess for the integer. Remeber, it is between one and ten.");//GREETING
int userGen = userInput.nextInt();//USER GUESS
do
{
guessTrack++;//Increase guess value
if(userGen > compGen)//checks user value in relation to computer generated int
{
System.out.println("Try again! Your guess was too high!");//inform user of bad guess
userGen = userInput.nextInt();//new guess
tooHighTrack++;//if guess is too high, this int tracker increases
}
else if(userGen < compGen)//checks user value in relation to computer generated int
{
System.out.println("Try again! Your guess was too low!");//inform user of guess
userGen = userInput.nextInt();//new guess
tooLowTrack++;//increases if user guess is too low
}
else if(userGen==compGen)//if both values are equivalent, execute THIS IS THE PROBLEM STATEMENT!!
{
System.out.println("Great job! You guessed the right number!");//congratulate
if(guessTrack>1)
{
System.out.println("It took you: "+guessTrack+" guess to get the right answer.");//print guess tracked int
}
else
{
System.out.println("It took you: "+guessTrack+" guesses to get the right answer.");//print guess tracked int
}
System.out.println(tooHighTrack +" guesses were too high and "+ tooLowTrack+ " were too low.");//print how many guess were too big or too low
System.out.println("HELLO"); //Used to verify failure of code
userInput.close();//close scanner object
}
}
while (userGen != compGen);//condition to be ultimately checked
}
}
I haven't been able to figure out what is wrong. At one point I deleted the entire if-statement and re-typed it (I knew it wouldn't do anything, but I had to try). This issue makes no sense to me. There are no errors or anything that pop up, nothing pops up on the console which scares me a little. Thanks in advance.
First off, a lot of text you put here. Maybe try to minimize the problem next time as a suggestion ;) Otherwise everything is fine
To your problem. Let me minimize your code and then explain to you, what happens.
1. The Code
int val = scanner.nextInt();
do {
if (val < 5) {
// too low
val = scanner.nextInt();
} else if (val > 5) {
// too high
val = scanner.nextInt();
} else {
// correct
// THIS CODE DOESN'T RUN?!
}
} while (val != 5);
2. What does your code do?
You read your first number before your loop. That's fine. Then, you enter an if-elseif-else statement. Note, that once inside one of those blocks, the other blocks won't get executed. Now the problem is, that you read your next user inputs inside of the if-elseif! The program reads the next value and leaves the whole if-elseif-else. Your code does not execute, because the loop then ends before the next iteration, therefore the correct user input is not going through the if-elseif-else at all.
3. The solution
Remove all nextInt() reads and just have one as the first thing inside the loop:
int val;
do {
val = scanner.nextInt();
if (val < 5) {
// too low
} else if (val > 5) {
// too high
} else {
// correct
// THIS CODE RUNS NOW!
}
} while (val != 5);
Such things, structures that need to do something at least once before checking the loop condition, are usually done with do while loops rather than while loops
You are setting user input during the loop, and it is then checked afterwards. Try moving the body of the else if(userGen==compGen) block to after the loop like this:
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in);//Scanner
int compGen = (int)(Math.random()* 10 + 1);//compGen is computer number
System.out.println(compGen); //USED TO VERIFY FAILURE. VALUE WAS ENTERED TO TEST CODE
int guessTrack = 0;//tracks number of guesses
int tooHighTrack = 0;//CREATING INTS TO TRACK STUFF
int tooLowTrack = 0;
System.out.println("Welcome to the integer guessing game that everyoone loves!");//PROMPT
System.out.println("Please enter your guess for the integer. Remeber, it is between one and ten.");//GREETING
int userGen = userInput.nextInt();//USER GUESS
do
{
guessTrack++;//Increase guess value
if(userGen > compGen)//checks user value in relation to computer generated int
{
System.out.println("Try again! Your guess was too high!");//inform user of bad guess
userGen = userInput.nextInt();//new guess
tooHighTrack++;//if guess is too high, this int tracker increases
}
else if(userGen < compGen)//checks user value in relation to computer generated int
{
System.out.println("Try again! Your guess was too low!");//inform user of guess
userGen = userInput.nextInt();//new guess
tooLowTrack++;//increases if user guess is too low
}
}
while (userGen != compGen);//condition to be ultimately checked
//The numbers have matched since it exited the loop.
System.out.println("Great job! You guessed the right number!");//congratulate
if(guessTrack>1)
{
System.out.println("It took you: "+guessTrack+" guess to get the right answer.");//print guess tracked int
}
else
{
System.out.println("It took you: "+guessTrack+" guesses to get the right answer.");//print guess tracked int
}
System.out.println(tooHighTrack +" guesses were too high and "+ tooLowTrack+ " were too low.");//print how many guess were too big or too low
System.out.println("HELLO"); //Used to verify failure of code
userInput.close();//close scanner object
}
The while condition is checked as soon as the program reaches the end of the code inside the loop. So suppose they enter the wrong number; the program says it's too low or too high, and then asks for another number:
userGen = userInput.nextInt();//new guess
Now suppose this new number is the correct one. The program finishes your if statement, then gets to the end of the loop. Then, at that point, userGen is equal to compGen. So the while condition fails, and the program exits the loop immediately, without ever getting to the code that prints the results.
One way to solve it would be to move the logic for userGen == compGen, that prints the results, outside the loop--that is, after the end of the loop. That way, it will be executed whenever the loop is exited. Note that when you exit the loop, we know that userGen == compGen, because if it weren't, the loop would go back.
Let's say the computer generated number was 3, and you guess 5.
5>3, so the if(userGen > compGen) statement executes:
System.out.println("Try again! Your guess was too high!");//inform user of bad guess
userGen = userInput.nextInt();//new guess
tooHighTrack++;//if guess is too high, this int tracker increases
you print the message, get a new guess, then increment your counter... but when you get the new guess, say it was the correct answer 3, userGen is now equal to CompGen (both are 3) and now the
while condition is evaluated:
while (userGen != compGen)
this is now false because userGen == compGen (both are 3). Your code never gets a chance
to print the correct message because the loop exits before it can happen. hope that helps
Your userGen is not being checked after every user input.
The problem is that you have your check inside an else-if block, which will check the end of the while statement before it loops back through again.
If you change
else if(userGen==compGen)
to
if(userGen==compGen)
then because it is not apart of the if-else block, it will be checked after every input (before the while condition is checked)
Alternatively you could move your user-input to the start of the do-while block like so:
package Chapter_3.Lab03_Chapter3;
import java.util.*;
public class Guess
{
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in);//Scanner
int compGen = (int)(Math.random()* 10 + 1);//compGen is computer number
System.out.println(compGen); //USED TO VERIFY FAILURE. VALUE WAS ENTERED TO TEST CODE
int guessTrack = 0;//tracks number of guesses
int tooHighTrack = 0;//CREATING INTS TO TRACK STUFF
int tooLowTrack = 0;
System.out.println("Welcome to the integer guessing game that everyoone loves!");//PROMPT
System.out.println("Please enter your guess for the integer. Remeber, it is between one and ten.");//GREETING
int userGen = -1;//USER GUESS
do
{
userGen = userInput.nextInt();
guessTrack++;//Increase guess value
if(userGen > compGen)//checks user value in relation to computer generated int
{
System.out.println("Try again! Your guess was too high!");//inform user of bad guess
userGen = userInput.nextInt();//new guess
tooHighTrack++;//if guess is too high, this int tracker increases
}
else if(userGen < compGen)//checks user value in relation to computer generated int
{
System.out.println("Try again! Your guess was too low!");//inform user of guess
userGen = userInput.nextInt();//new guess
tooLowTrack++;//increases if user guess is too low
}
else if(userGen==compGen)//if both values are equivalent, execute THIS IS THE PROBLEM STATEMENT!!
{
System.out.println("Great job! You guessed the right number!");//congratulate
if(guessTrack>1)
{
System.out.println("It took you: "+guessTrack+" guess to get the right answer.");//print guess tracked int
}
else
{
System.out.println("It took you: "+guessTrack+" guesses to get the right answer.");//print guess tracked int
}
System.out.println(tooHighTrack +" guesses were too high and "+ tooLowTrack+ " were too low.");//print how many guess were too big or too low
System.out.println("HELLO"); //Used to verify failure of code
userInput.close();//close scanner object
}
}
while (userGen != compGen);//condition to be ultimately checked
}
}
This will cause your if-else block to be checked everytime a user inputs data before the conditions for the do-while are checked.

Java boolean if question

I am making a lottery program where I am asking if basically they would like a quick pick ticket. The numbers for their ticket of course would be random since it is a quick pick but the first four numbers range from 0-9 while the fifth number only goes up to 0-4. I am trying to ask them to input a button such as either "1" for no or "2" for yes if they don't want one then it would skip this step. But I am doing the boolean part incorrectly though. Could someone help me out?
Here is an example
System.out.println("Do you want Quick pick, 1 for no or 2 for yes? The first four numbers is from a separate set of 0 to 9 and the fifth number is from a set of 0 to 4.");
QuickPick=keyboard.nextInt();
if((QuickPick==1)){
return false;
}
if((QuickPick==2)){
return true;
int n = (int)(Math.random()*9+0);
System.out.println("Your QuickPick numbers are: " + kickerNumbers + kickerPowerball);
}
I still haven't gotten around to making the line of code for the final number of 0-4, just the first four numbers, so I haven't forgotten that.
Your code for case 2 immediately does a return true; which ends the method (I assume this is in a method) right then and there. Your other lines don't get execute at all.
Consider using a switch() statement here, it'll make it easier to read:
switch(QuickPick)
{
case 1:
return false;
case 2:
int n = (int)(Math.random()*9+0); // Why is n here? You don't do anything with it?
System.out.println("Your QuickPick numbers are: " + kickerNumbers + kickerPowerball);
return true;
default:
// Uh oh - someone did something bad maybe just return false?
return false;
}
Also your code for case 2 is definitely wrong, you need to generate a total of five numbers, using bounds 0-9 for the first 4 and 0-4 for the last one. You'll want to use Java's Random to do this (not Math.Random) something like:
Random rand = new Random();
int somethingRandom = rand.nextInt(10);
// Will give you an integer value where 0 < val < 10
// You can call rand.nextInt as many times as you want
To avoid doing your homework for you -- I'll follow the typical CS textbook line and say "Implementation left as an exercise."
The code after return true will not be executed - you need to put that prior to the return statement
Like Marvo said, you dropped a brace in your if.
But you also have faulty logic. I'm not quite sure what the purpose of the method you're in is (that returns a boolean value). But your last few lines will never be reached unless the user types in something like 3 or 42.
Assuming the method is supposed to a) Ask if the user wants a Quick Pick b) Calculate the Quick Pick, if desired c) Return true/false depending on whether the Quick Pick happened or not, you should have:
public boolean doQuickPick()
{
System.out.println("Do you want Quick pick, 1 for no or 2 for yes? The first four numbers is from a separate set of 0 to 9 and the fifth number is from a set of 0 to 4.");
QuickPick=keyboard.nextInt();
if((QuickPick==1)){
return false;
}
if((QuickPick==2)){
int n = (int)(Math.random()*9+0);
System.out.println("Your QuickPick numbers are: " + kickerNumbers + kickerPowerball);
return true;
}
}
As a separate issue, it'd be much better style to break that into several methods. boolean yesNoPrompt(String message), generateQuickPick(), etc.
Your question is kind of unclear, so I'm afraid I can't be much more help than that. Do post any clarifications / further questions if you have them.
if((QuickPick==2)){
return true;
int n = (int)(Math.random()*9+0);
System.out.println("Your QuickPick numbers are: " + kickerNumbers + kickerPowerball);
}
In the above copied code from your question, I see that you will be getting compilation errors in your IDE. Your IDE will complain about "Unreachable Code" for the line that is just below the return statement. So, you need to put the return statement at the end of the if block.

Categories