Can't figure out why it isn't resolving properly - java

So, I'm working on this assignment for a class. It's a Java class, and I'm supposed to make a game where it rolls two dice, adds them up, and adds them to your turn score. It then asks if you want to keep playing. When your turn score hits 20, or when you decide to pass, it goes to a computer. It's supposed to print the scores each turn, and then when someone hits 100 points, it announces the winner. However, no matter what, the score at the end of each turn is 0, no matter how many times I run it. When a player rolls a 1, their turn score is cancelled, and it moves on to the other player, and if they roll double 1's, they lose all of their points for the game so far. Here is my code, can you figure out why the score variables don't update? Thank you.
import java.util.Scanner;
import java.util.Random;
public class PlayPig {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int player1 = 0;
int player2 = 0;
int a, b, c, player1turn, player2turn, input;
int pig = 1;
Random r = new Random();
do{
do {
player1turn=0;
a = r.nextInt(6)+1;
b = r.nextInt(6)+1;
if( a==1 || b==1){
if (a == 1 && b == 1){
player1=0;
break;}
else if (a==1 || b==1){
player1turn=0;
break;}
else {
player1turn= a+b ;
}}
player1= player1+player1turn;
System.out.println("Player1 score is " + player1 + " and player2 score is " + player2);
System.out.print("Do you want to keep playing? Enter 1 to continue. Enter any other number to pass.");
input = scan.nextInt();
if (input != 1)
break;
}
while
(player1turn <= 20);
do{
player2turn=0;
a = r.nextInt(6)+1;
b = r.nextInt(6)+1;
if( a==1 || b==1){
if (a == 1 && b == 1){
player2=0;
break;}
else if (a==1 || b==1){
player2turn=0;
break;}
else {
player1turn= a+b ;
player2= player2+player2turn;}}
}
while
(player2turn<=20);
}
while
(player1 < 100 || player2 < 100);
if (player1>player2)
System.out.print("Player 1 wins");
else
System.out.print("Player 2 wins");
}}

The main problem was, that your else conditions in which you assigned the current score were in the wrong block. (These ones):
else {
player1turn = a+b ;
}
Try this code:
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int player1 = 0;
int player2 = 0;
int a, b, c, player1turn, player2turn, input;
int pig = 1;
Random r = new Random();
do{
do {
player1turn=0;
a = r.nextInt(6)+1;
b = r.nextInt(6)+1;
if( a==1 || b==1){
if (a == 1 && b == 1){
player1 = 0;
break;
}
else if (a==1 || b==1){
player1turn=0;
break;
}
}else {
player1turn = a+b ;
}
player1 += player1turn;
System.out.println("Player1 score is " + player1 + " and player2 score is " + player2);
System.out.print("Do you want to keep playing? Enter 1 to continue. Enter any other number to pass.");
input = scan.nextInt();
if (input != 1){
break;
}
} while (player1turn <= 20);
do{
player2turn=0;
a = r.nextInt(6)+1;
b = r.nextInt(6)+1;
if( a==1 || b==1){
if (a == 1 && b == 1){
player2=0;
break;
} else if (a==1 || b==1){
player2turn=0;
break;
}
}else {
player2turn = a+b ;
player2 += player2turn;
}
}while (player2turn<=20);
} while (player1 < 100 || player2 < 100);
if (player1>player2)
System.out.print("Player 1 wins");
else
System.out.print("Player 2 wins");
}

I have modified the if loop.
You can try this:
import java.util.Scanner;
import java.util.Random;
public class PlayPig {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int player1 = 0;
int player2 = 0;
int a, b, c, player1turn, player2turn, input;
int pig = 1;
Random r = new Random();
do{
do {
player1turn=0;
a = r.nextInt(6)+1;
b = r.nextInt(6)+1;
if (a == 1 && b == 1){
player1=0;
break;
}
else if((a== 1 && b!= 1) || (a!=1 && b== 1){
player1turn=0;
break;
}
else{
player1turn= a+b ;
}
player1= player1+player1turn;
System.out.println("Player1 score is " + player1 + " and player2 score is " + player2);
System.out.print("Do you want to keep playing? Enter 1 to continue. Enter any other number to pass.");
input = scan.nextInt();
if (input != 1)
break;
}
while
(player1turn <= 20);
do{
player2turn=0;
a = r.nextInt(6)+1;
b = r.nextInt(6)+1;
if (a == 1 && b == 1){
player2=0;
break;
}
else if((a== 1 && b!= 1) || (a!=1 && b== 1){
player2turn=0;
break;
}
else{
player2turn= a+b ;
}
player2= player2+player2turn;
}
while
(player2turn<=20);
}
while
(player1 < 100 || player2 < 100);
if (player1>player2)
System.out.print("Player 1 wins");
else
System.out.print("Player 2 wins");
}}

Related

GameContinue() not functioning. should loop back to beginning of main()

I am currently creating a pig game, and have most functions working.
I need the code to work where if player 1 decides to stop rolling, and player two decides to stop rolling, the game will loop back until one player reaches 20 points. Currently, the code ends after 1 run through.
import java.util.Random;
import java.util.Scanner;
public class Project3_Part1_Submit {
static int playerScore = 0;
static int playerTotal = 0;
static int dice = 0;
static final int FINAL_SCORE = 20;
static int playerTwoScore = 0;
static int playerTwoTotal = 0;
static boolean gameOver = false;
static boolean turnOver = false;
static char repeat;
static String input;
static Scanner key = new Scanner(System.in);
static Random rand = new Random();
public static void main(String[] args) {
PlayerOneTurn();
PlayerTwoTurn();
GameContinue();
if (playerTotal >= FINAL_SCORE) {
System.out.print("Current Score: Player 1 has " + playerTotal);
System.out.print(", Player 2 has " + playerTwoTotal);
System.out.println("");
System.out.println("Player 1 wins!");
}
if (playerTwoTotal >= FINAL_SCORE) {
System.out.print("Current Score: Player 1 has " + playerTotal);
System.out.print(", Player 2 has " + playerTwoTotal);
System.out.println("");
System.out.println("Player 2 wins!");
}
}
public static void PlayerOneTurn() {
while (turnOver == false) {
do {
System.out.print("Player 1 turn total is " + playerTotal); // welcome line
System.out.print(". Enter (r)oll or (s)top: ");
System.out.println("");
input = key.next(); // input = next key entered
repeat = input.charAt(0);
if (repeat == 'r') // if input letter = r
{
dice = rand.nextInt(3) + 1; // set dice to number between 1-6
System.out.println("Player 1 rolled: " + dice); // display number, signifying the amount rolled
if (dice == 1) // if the number rolled happens to be 1...
{
playerScore = 0; // reset score to 0
System.out.print("Player 1 lost their turn! ");
System.out.print("Player 1 total is " + playerTotal);
System.out.println("");
return;
}
else
{
playerScore += dice; // add dice amount to player score
System.out.print("Player 1 turn total is " + playerScore);// print out total amount earned
System.out.print(" Enter (r)oll or (s)top: "); // repeat question
System.out.println("");
input = key.next();
repeat = input.charAt(0);
if (playerScore >= 20) {
playerTotal = playerScore;
gameOver = true;
return;
}
}
}
else if (repeat == 's') // if neither option is called
{
return;
}
else
{
System.out.println("Incorrect entry, please try again"); // prompt retry
System.out.println("");
input = key.next();
}
}while(turnOver == false || dice != 1);
playerTotal += playerScore;
playerScore = 0;
if (playerTotal >= FINAL_SCORE) {
// System.out.println("YOU WIN!");
gameOver = true;
while (playerTotal >= FINAL_SCORE)
;
break;
}
}
}
public static void PlayerTwoTurn() {
System.out.println("success");
while (turnOver == false) {
do {
System.out.print("Player 2 turn total is " + playerTwoTotal); // welcome line
System.out.print(". Enter (r)oll or (s)top: ");
System.out.println("");
input = key.next(); // input = next key entered
repeat = input.charAt(0);
if (repeat == 'r') // if input letter = r
{
dice = rand.nextInt(3) + 1; // set dice to number between 1-6
System.out.println("Player 2 rolled: " + dice); // display number, signifying the amount rolled
System.out.println("");
if (dice == 1) // if the number rolled happens to be 1...
{
playerTwoScore = 0; // reset score to 0
System.out.print("Player 2 lost their turn! ");
System.out.print("Player 2 total is " + playerTwoTotal);
System.out.println("");
return;
}
else
{
playerTwoScore += dice; // add dice amount to player score
System.out.print("Player 2 turn total is " + playerTwoScore);// print out total amount earned
System.out.print(" Enter (r)oll or (s)top: "); // repeat question.
System.out.println("");
input = key.next();
repeat = input.charAt(0);
if (playerTwoScore >= 20) {
playerTwoTotal = playerTwoScore;
gameOver = true;
return;
}
}
}
else if (repeat == 's') // if neither option is called
{
turnOver = true;
return;
}
else
{
System.out.println("Incorrect entry, please try again"); // prompt retry
System.out.println("");
input = key.next();
}
}while(turnOver == false || dice != 1);
playerTwoTotal += playerTwoScore;
playerTwoScore = 0;
if (playerTwoTotal >= FINAL_SCORE) {
// System.out.println("YOU WIN!");
gameOver = true;
while (playerTwoTotal >= FINAL_SCORE)
;
break;
}
}
}
public static void GameContinue() {
if (playerTotal < 20 && playerTwoTotal < 20) { //if neither players totals or 20 or greater
PlayerOneTurn(); //go back to playerOne
}
else //if either one is 20 or greater
{
return; //go to main method and finish
}
}
}
My GameContinue() function is what i created to go loop back to PlayerOne.
public static void GameContinue() {
if (playerTotal < 20 && playerTwoTotal < 20) { //if neither players totals or 20 or greater
gameOver = false;
PlayerOneTurn(); //go back to playerOne
}
else //if either one is 20 or greater
{
return; //go to main method and finish
}
}
I know calling PlayerOneTurn(); will not loop it back to the start of the main method. I've tried calling all three methods again like this.
public static void GameContinue() {
if (playerTotal < 20 && playerTwoTotal < 20) { //if neither players totals or 20 or greater
gameOver = false;
PlayerOneTurn(); //go back to playerOne
PlayerTwoTurn();
GameContinue();
}
else //if either one is 20 or greater
{
return; //go to main method and finish
}
}
Obviously that just caused a butload of errors. How should i go about having my code continue to loop back until the if statement in GameContinue() is met?
As Ecto has commented, you could use a while loop in the main function. It is shown here:
public static void main(String[] args) {
while (GameContinue()) {
PlayerOneTurn();
PlayerTwoTurn();
}
if (playerTotal >= FINAL_SCORE) {
System.out.print("Current Score: Player 1 has " + playerTotal);
System.out.print(", Player 2 has " + playerTwoTotal);
System.out.println("");
System.out.println("Player 1 wins!");
}
if (playerTwoTotal >= FINAL_SCORE) {
System.out.print("Current Score: Player 1 has " + playerTotal);
System.out.print(", Player 2 has " + playerTwoTotal);
System.out.println("");
System.out.println("Player 2 wins!");
}
}
Now obviously this would be an error as GameContinue() is a void method. To combat this you can change GameContinue() to this:
public static boolean GameContinue() {
if (playerTotal < 20 && playerTwoTotal < 20) {
gameOver = false;
return true;
} else {
return false;
}
}
This would solve your problems and your code is minimally changed.

Rockpapergame with rounds and counter variables - java

I am creating a rock paper project which has the following requirement:
Continually plays rounds of rock, paper, scissors until one of the players wins three rounds. At that point, the program outputs the winner and the number of rounds it took them to win. If there is no winner after 10 rounds, the competition is declared a tie
Something seems to be missing which I am not quite able to understand or notice. How would I make my game stop after the rounds and declare a winner?
Note: No arrays, external libraries other than scanner, or any built-in methods of java allowed
This is my attempt:
import java.util.Scanner;
public class Rockpaper{
public static void main(String[]args){
Scanner keyboard = new Scanner(System.in);
String player1 = keyboard.next();
String player2 = keyboard.next();
String player = "Player1";
int round = 1;
boolean go = true;
boolean win = false;
while(go){
if (player1.equals("r") && player2.equals("p")){
win = true;
}
else if (player1.equals("p") && player2.equals("r")){
win = true;
}
else if (player1.equals("p") && player2.equals("s")){
win = true;
}
else if (player1.equals("s") && player2.equals("p")){
win = true;
}
else if (player1.equals("s") && player2.equals("r")){
win = true;
}
else if (player1.equals("r") && player2.equals("s")){
win = true;
}
else if (player1.equals("r") && player2.equals("r")){
win = false;
}
else if (player1.equals("p") && player2.equals("p")){
win = false;
}
else if (player1.equals("s") && player2.equals("s")){
win = false;
}
if (round < 5){
System.out.println(win+" after "+round+" rounds!");
go = false;
}else{
System.out.println("Tie - No winner after "+round+" rounds!");
}
if (player.equals("Player1"){
Player = "Player2";
}else{
Player = "Player1";
}
}
}
}
The problem I see is that there needs to be a separate variable that counts each of the win possibilities, for example, "win1" which would count the player1 win possibility and "win2" that would count the player2 wins. I am not quite sure about the rounds variable that would initially start counting the rounds up to 10 which is the maximum.
Sample input/output:
Currently you read the input only once, before the loop:
String player1 = keyboard.next();
String player2 = keyboard.next();
After every match, you should ask if players should continue playing. If so, then you must ask for their input again. This is, just move the "playerX" variable declaration and initialization inside the loop:
//comment/remove these
//String player1 = keyboard.next();
//String player2 = keyboard.next();
//inside the loop
while(go){
String player1 = keyboard.next();
String player2 = keyboard.next();
if (player1.equals("r") && player2.equals("p")){
/* rest of your code */
}
Also, this section:
if (round < 5){
System.out.println(win+" after "+round+" rounds!");
go = false;
}else{
System.out.println("Tie - No winner after "+round+" rounds!");
}
if (player.equals("Player1"){
Player = "Player2";
}else{
Player = "Player1";
}
}
It seems odd for two things:
round is never increased.
The else after round < 5 will be always executed, wrongly stating that there's a tie.
Reassigning Player variable for asking user input is not necessary. Instead, you could use 2 variables to store names of your players that are initialized before the game begins.
One more thing: instance of Scanner is Closeable, so each time you use it to read user input, you make sure that the instance is closed after is not needed anymore, in this case, at the end of the program.
More hints:
Reduce several if/else with the same output to a single if evaluation
You could make use of methods to ease game result.
With all this in mind, your code may look like this:
import java.util.Scanner;
public class RockPaperScizzorGame {
public static int getGameResult(String player1Move, String player2Move) {
int result = 0; //assume the game will be a tie
//player 2 wins
if (player1Move.equals("r") && player2Move.equals("p")
|| player1.equals("p") && player2.equals("s")
|| player1.equals("s") && player2.equals("r")
) {
result = 2;
}
//player 1 wins
if (player1.equals("p") && player2.equals("r")
|| player1.equals("s") && player2.equals("p")
|| player1.equals("r") && player2.equals("s")) {
result = 1;
}
//return the result: 0, 1 or 2
return result;
}
public static void main (String[] args) {
try (Scanner keyboard = new Scanner(System.in)) {
String player1Name = "Player 1";
String player2Name = "Player 2";
int round = 0;
boolean go = true;
int winsPlayer1 = 0;
int winsPlayer2 = 0;
while (go) {
System.out.println("Make your move " + player1Name + ": ");
String player1Move = keyboard.next();
System.out.println("Make your move " + player2Name + ": ");
String player2Move = keyboard.next();
int gameResult = getGameResult(player1Move, player2Move);
switch(gameResult) {
case 1:
winsPlayer1++;
break;
case 2:
winsPlayer2++;
break;
}
round++;
if (winsPlayer1 == 3) {
System.out.println(player1Name + " won after " + round + " rounds!");
go = false;
} else if (winsPlayer2 == 3) {
System.out.println(player2Name + " won after " + round + " rounds!");
go = false;
} else {
if (round == 5 && winsPlayer1 < 3 && winsPlayer2 < 3) {
System.out.println("Tie - No winner after "+round+" rounds!");
go = false;
}
}
} catch (IOException e) {
System.out.println("Issues when trying to accept user input.");
e.printStacktrace();
}
}
}
You can improve the code even more:
Use more methods to ease the code in main method.
Since your main loop depends more on a counter rather than a boolean flag, you may use a for loop rather than a while.
You may ask for user input for the name of the players.
You may create a class to encapsulate data of your players: name, currentMove, number of wins.
Problems with your code:
Not using separate variables for individual players.
Not putting input statements inside the loop as a result of which the input statements run only once.
Not changing the value of the variable, round but using its value in the condition, if (round < 5) which will always evaluate true if the value of round is not increased.
Solution
import java.util.Scanner;
public class Rockpaper {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int round = 1;
boolean go = true;
int player1Score = 0;
int player2Score = 0;
while (go && round <= 10) {
String player1 = keyboard.next();
String player2 = keyboard.next();
if (player1.equals("r") && player2.equals("p")) {
player2Score++;
} else if (player1.equals("p") && player2.equals("r")) {
player1Score++;
} else if (player1.equals("p") && player2.equals("s")) {
player2Score++;
} else if (player1.equals("s") && player2.equals("p")) {
player1Score++;
} else if (player1.equals("s") && player2.equals("r")) {
player2Score++;
} else if (player1.equals("r") && player2.equals("s")) {
player1Score++;
}
if (player1Score >= 3) {
System.out.println("Player1 wins " + " after " + round + " rounds!");
go = false;
}
if (player2Score >= 3) {
System.out.println("Player2 wins " + " after " + round + " rounds!");
go = false;
}
round++;
}
if (round > 10) {
System.out.println("Tie - No winner after " + (round - 1) + " rounds!");
}
}
}
First sample run:
p
r
r
s
s
s
r
r
p
r
Player1 wins after 5 rounds!
Second sample run:
p
p
p
r
r
r
s
s
p
p
s
s
s
s
p
p
r
p
s
p
Tie - No winner after 10 rounds!

Variable not being recognized in method

I am relatively new to Java, and I am writing a simple program to play rock, paper, scissors. This is the code:
import java.util.Random;
import java.util.Scanner;
public class Main {
public static String comChoice() {
Random rand = new Random();
int num = rand.nextInt(299) + 1;
if (num >= 1 && num <= 99) {
String pick = "SCISSORS";
} else if (num >= 100 && num <= 199) {
String pick = "ROCK";
} else if (num >= 200 && num <= 299) {
String pick = "PAPER";
}
return pick;
}
public static void main(String args[]) {
int wins = 0;
int losses = 0;
int ties = 0;
while (1 == 1) {
Scanner s = new Scanner(System.in);
System.out.println("Would you like to play Rock Paper Scissors? Y/N");
String n = s.next();
if (n.equalsIgnoreCase("Y")) {
Scanner t = new Scanner(System.in);
System.out.println("Enter your pick: rock, paper, or scissors");
String userChoice = t.next();
String pick = comChoice();
if (userChoice.equalsIgnoreCase("SCISSORS") && pick.equalsIgnoreCase("SCISSORS")) {
System.out.println("TIE");
ties++;
} else if (userChoice.equalsIgnoreCase("ROCK") && pick.equalsIgnoreCase("SCISSORS")) {
System.out.println("WIN");
wins++;
} else if (userChoice.equalsIgnoreCase("PAPER") && pick.equalsIgnoreCase("SCISSORS")) {
System.out.println("LOSE");
losses++;
} else if (userChoice.equalsIgnoreCase("SCISSORS") && pick.equalsIgnoreCase("ROCK")) {
System.out.println("LOSE");
losses++;
} else if (userChoice.equalsIgnoreCase("SCISSORS") && pick.equalsIgnoreCase("PAPER")) {
System.out.println("WIN");
wins++;
} else {
System.out.println("Enter a valid choice");
}
} else {
System.out.println("You won " + wins + " matches");
System.out.println("You tied " + ties + " matches");
System.out.println("You lost " + losses + " matches");
break;
}
}
}
}
I'm getting an error in my method which says this:
Main.java:23: error: cannot find symbol
return pick;
^
symbol: variable pick
location: class Main
1 error
exit status 1
I can't figure out how to fix this error. I would appreciate your input as well as any other general advice
Thanks
Your variable is only visible in the if statement. Read about scopes.
Change to:
import java.util.Scanner;
import java.util.Random;
public class Main {
public static String comChoice() {
Random rand = new Random();
int num = rand.nextInt(299) + 1;
String pick = null;
if (num >= 1 && num <= 99) {
pick = "SCISSORS";
} else if (num >= 100 && num <= 199) {
pick = "ROCK";
} else if (num >= 200 && num <= 299) {
pick = "PAPER";
}
return pick;
}
....
}
pick is out of scope. Try declaring at the start of the comChoice method.
Hence :
public static String comChoice() {
String pick=null;
Random rand = new Random();
int num = rand.nextInt(299) + 1;
if (num >= 1 && num <= 99) {
pick = "SCISSORS";
} else if (num >= 100 && num <= 199) {
pick = "ROCK";
} else if (num >= 200 && num <= 299) {
pick = "PAPER";
}
return pick;
}
variable pick is out of scope. You have to declare it outside the all if else statements. if all if else condition fail then comChoice method will not be able to find variable pick (as it is declared inside the if else block only)which it has to return.
corrected code
import java.util.Scanner;
import java.util.Random;
public class Main
{
public static String comChoice()
{
Random rand = new Random();
int num = rand.nextInt(299) + 1;
String pick = "";
if(num >= 1 && num <= 99)
{
pick = "SCISSORS";
}
else if (num >= 100 && num <= 199)
{
pick = "ROCK";
}
else if (num >= 200 && num <= 299)
{
pick = "PAPER";
}
return pick;
}
public static void main (String args[])
{
int wins = 0;
int losses = 0;
int ties = 0;
while (1 == 1)
{
Scanner s = new Scanner (System.in);
System.out.println("Would you like to play Rock Paper Scissors? Y/N");
String n = s.next();
if (n.equalsIgnoreCase("Y"))
{
Scanner t = new Scanner (System.in);
System.out.println("Enter your pick: rock, paper, or scissors");
String userChoice = t.next();
String pick = comChoice();
if (userChoice.equalsIgnoreCase("SCISSORS") && pick.equalsIgnoreCase("SCISSORS"))
{
System.out.println("TIE");
ties++;
}
else if (userChoice.equalsIgnoreCase("ROCK") && pick.equalsIgnoreCase("SCISSORS"))
{
System.out.println("WIN");
wins++;
}
else if (userChoice.equalsIgnoreCase("PAPER") && pick.equalsIgnoreCase("SCISSORS"))
{
System.out.println("LOSE");
losses++;
}
else if (userChoice.equalsIgnoreCase("SCISSORS") && pick.equalsIgnoreCase("ROCK"))
{
System.out.println("LOSE");
losses++;
}
else if (userChoice.equalsIgnoreCase("SCISSORS") && pick.equalsIgnoreCase("PAPER"))
{
System.out.println("WIN");
wins++;
}
else
{
System.out.println("Enter a valid choice");
}
}
else
{
System.out.println("You won " + wins + " matches");
System.out.println("You tied " + ties + " matches");
System.out.println("You lost " + losses + " matches");
break;
}
}
}
}
You declared your variable pick in the if else structure. Doing this causes the problem that your variable cannot be accessed from outside that if else structure. In simple words, the variable pick's scope is limited to your if else structure. You have to declare your variable (and initialize it as well, otherwise you'll get an error in your case) outside of the if else structure. Like this:
String pick = null;
if(num >= 1 && num <= 99) {
...
...
...// All your if's and else's
}
return pick;
Hope this helps!

While loop ignores or statement

I am trying to run the while loop below for my Programming I class extra credit. It's supposed to simulate a game of craps however I can't figure out why the bottom while loop runs no matter what.
import java.util.Random;
import java.util.Scanner;
public class ExtraCredit {
public static void main(String[] args)
{
Scanner scan = new Scanner( System.in );
Random random = new Random( );
int die1, die2, roll;
int dice = 0;
int point = 0;
int finish = 0;
int play = 1;
while (play == 1)
{
System.out.println ("Enter 0 to roll the dice");
roll = scan.nextInt( );
if (roll == 0)
{
die1 = random.nextInt( 6 ) + 1;
die2 = random.nextInt( 6 ) + 1;
dice = die1+die2;
}
if (dice == 7 || dice == 11)
{
System.out.println ("\nYou rolled a " + dice + " on your first roll!");
System.out.println ("You win!");
finish = 1;
}
else if (dice == 2 || dice == 3 || dice == 12)
{
System.out.println ("You rolled a " + dice + " on your first roll!");
System.out.println ("You lose!");
finish = 1;
}
else
{
point = dice;
System.out.println ("\nYour point is " + point);
System.out.println ("You need to roll a " + point + " to win");
System.out.println ("Enter 0 to Roll again");
roll = scan.nextInt( );
if (roll == 0)
{
die1 = random.nextInt( 6 ) + 1;
die2 = random.nextInt( 6 ) + 1;
dice = die1+die2;
}
}
while (dice != point || dice != 7 || finish != 1)
{
System.out.println ("\nYou rolled a " + dice);
System.out.println ("Roll again");
roll = scan.nextInt( );
if (roll == 0)
{
die1 = random.nextInt( 6 ) + 1;
die2 = random.nextInt( 6 ) + 1;
dice = die1+die2;
}
}
if (dice == point)
{
System.out.println ("\nYou rolled your point (" + point +")");
System.out.println ("You won!");
}
if (dice == 7)
{
System.out.println ("\nYou rolled a 7 before you could match your point");
System.out.println ("You Lose!");
}
System.out.println ("\nEnter 1 to play again");
play = scan.nextInt( );
}
}
}
(dice != point || dice != 7 || finish != 1)
This will never be false.
Try this
(dice != point && dice != 7 && finish != 1)
You want to change the ||'s to &&'s
while (dice != point && dice != 7 && finish != 1)

int variable remains at 0, while loop not running properly as a result

What I really am stuck with is the second to last variable userGuessDifference. It remains at zero making my second while loop not run properly as it just keeps going back to the first else if statement.
public class GuessingGame {
/**
* #param args
*/
public static void main(String[] args)
{
Scanner keyboard = new Scanner (System.in);
Random generator = new Random();
int difficulty = 0;
int guesses = 0;
int userGuess = 0;
int correctAnswer = 0;
int counter = 0;
int userGuessDifference = (Math.abs(correctAnswer) - Math.abs(userGuess));
boolean flag = false;
System.out.println("We are going to play a number guessing game.");
System.out.println(" ");
System.out.println("Choose your difficulty:");
System.out.println("Pick a number - 10 is easy, 25 is medium, 50 is hard.");
difficulty = keyboard.nextInt();
if (difficulty == 10)
{
guesses = 3;
System.out.println("You have 3 guesses, make them count!");
}
else if (difficulty == 25)
{
guesses = 5;
System.out.println("You have 5 guesses, make them count!");
}
else if (difficulty == 50)
{
guesses = 6;
System.out.println("You have 6 guesses, make them count!");
}
else
{
System.out.println("If you can't follow instructions, I'm going to make this very difficult for you!");
difficulty = (difficulty * 100);
guesses = 1;
}
System.out.println(" ");
System.out.println("Ok, I have my number. Time to play.");
correctAnswer = generator.nextInt(difficulty) + 1;
System.out.println("Pick a whole number between 1 and " + difficulty + ":");
userGuess = keyboard.nextInt();
while (!flag || (counter <= guesses))
{
if (userGuess == correctAnswer)
{
System.out.println("CONGRATS YOU WIN!");
flag = true;
}
else if ((userGuessDifference <= (difficulty * .10)))
{
System.out.println("HOT!");
userGuess = keyboard.nextInt();
counter++;
}
else if ((userGuessDifference < (difficulty * .25)) && (userGuessDifference > (difficulty * .10)))
{
System.out.println("Warm...");
userGuess = keyboard.nextInt();
counter++;
}
else
{
System.out.println("Ice cold.");
userGuess = keyboard.nextInt();
counter++;
}
}
}
}
As #SotiriosDelimanolis wrote, you never reassign userGuessDifference. This should be done inside the while loop.
Moreover, there is another problem with your code: if you guess the number, the program just prints "CONGRATS YOU WIN!" forever, but it seems to me that you wanted to quit from the while loop once the user guesses the number (I guess the flag variable was introduced for this reason).
I slightly changed your code in order to meet this requirement:
import java.util.Random;
import java.util.Scanner;
public class GuessingGame {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
Random generator = new Random();
int difficulty = 0;
int guesses = 0;
int userGuess = 0;
int correctAnswer = 0;
int counter = 0;
System.out.println("We are going to play a number guessing game.");
System.out.println(" ");
System.out.println("Choose your difficulty:");
System.out.println("Pick a number - 10 is easy, 25 is medium, 50 is hard.");
difficulty = keyboard.nextInt();
if (difficulty == 10) {
guesses = 3;
System.out.println("You have 3 guesses, make them count!");
} else if (difficulty == 25) {
guesses = 5;
System.out.println("You have 5 guesses, make them count!");
} else if (difficulty == 50) {
guesses = 6;
System.out.println("You have 6 guesses, make them count!");
} else {
System.out.println("If you can't follow instructions, I'm going to make this very difficult for you!");
difficulty = (difficulty * 100);
guesses = 1;
}
System.out.println(" ");
System.out.println("Ok, I have my number. Time to play.");
correctAnswer = generator.nextInt(difficulty) + 1;
System.out.println("Pick a whole number between 1 and " + difficulty + ":");
userGuess = keyboard.nextInt();
while (counter <= guesses) {
// int userGuessDifference = (Math.abs(correctAnswer) - Math
// .abs(userGuess));
int userGuessDifference = Math.abs(correctAnswer - userGuess);
if (userGuess == correctAnswer) {
System.out.println("CONGRATS YOU WIN!");
break;
}
else if ((userGuessDifference <= (difficulty * .10))) {
System.out.println("HOT!");
}
else if ((userGuessDifference < (difficulty * .25))
&& (userGuessDifference > (difficulty * .10))) {
System.out.println("Warm...");
}
else {
System.out.println("Ice cold.");
}
userGuess = keyboard.nextInt();
counter++;
}
}
}

Categories