Program ignoring "If Else" and printing everything - java

I'm trying to create a Random Number Generator program which tracks a player's wins, losses, winning percentage and total winnings. The logic of the program is that a player gets 3 chances per session and the computer generates a random number which the player needs to guess or rather should match.
I've tried to use if & else statements to tell the user if he needs to guess a higher number or a lower number within the 3 allowed guesses. What's happening is that it completely ignores the conditions and prints all three chances at once and ends the game.
Any inputs on this would be highly appreciated.
Game Class:
import java.util.Scanner;
public class Game {
Player player;
LuckyNumberGenerator lng;
public Game() {
player = new Player();
lng = new LuckyNumberGenerator();
}
public void eventLoop() {
Scanner scanner = new Scanner(System.in);
int choice = 0;
boolean exit = false;
while (!exit) {
System.out.println("Welcome to the Guessing Game");
System.out.println("==============================");
System.out.println("(1) Set Up New Player");
System.out.println("(2) Play One Round");
System.out.println("(3) Player Win Statistics");
System.out.println("(4) Display Game Help");
System.out.println("(5) Exit Game");
System.out.println("Choose an option: ");
try {
choice = Integer.parseInt(scanner.nextLine());
if (choice < 1 || choice > 5) {
System.err.println("Error : Choose an option between 1 and 5");
choice = 0;
}
} catch (NumberFormatException e) {
System.err.println("Error : Choose an option between 1 and 5");
choice = 0;
}
switch (choice) {
case 1:
createNewPlayer(scanner);
break;
case 2:
guessNumber(scanner);
break;
case 3:
printStatistics();
break;
case 4:
printHelp();
break;
case 5:
exit = true;
}
}
scanner.close();
}
public void printHelp() {
System.out.println(" ");
}
public void printStatistics() {
try {
if (player.getName() == null || player.getName().trim().length() < 1) {
System.out.println("Player has not been set up!");
} else {
System.out.println("Player statistics are: ");
System.out.println("Name: " + player.getName());
System.out.println("Wins: " + player.getGamesWon());
System.out.println("Losses: " + player.getGamesLost());
System.out.println("Amount won so far: " + player.getTotalWinnings());
System.out.println("Winnings percentage : "
+ (((player.getGamesWon()) / (player.getGamesWon() + player.getGamesLost())) * 100));
}
} catch (ArithmeticException ae) {
System.out.println("wins and loss both are 0: divide by zero exception");
}
}
public void guessNumber(Scanner scanner) {
int compGuess = lng.generate();
int userGuess = 0;
int numAttempts = 0;
int cnum = lng.generateConsole();
do {
try {
System.out.println("Guess a number between 1-100: ");
userGuess = Integer.parseInt(scanner.nextLine());
if (userGuess < 1 || userGuess > 100) {
System.err.println("Error : your Guess must be between 1-100");
}
} catch (Exception e) {
System.err.println("Error : your Guess must be between 1-100");
}
} while (userGuess < 1 && userGuess > 100);
do {
if (userGuess > compGuess) {
System.out.println("Your Guess is: " + userGuess + "and the random number: " + compGuess);
System.out.println("Sorry, you need to go LOWER :");
} else if (userGuess < compGuess) {
System.out.println("Your Guess is: " + userGuess + "and the random number: " + compGuess);
System.out.println("Sorry, you need to go HIGHER :");
}
numAttempts++;
if (userGuess == compGuess) {
System.out.println("Lucky Number was : " + compGuess + "your guess was : " + userGuess);
System.out.println("Congratulations you won " + 10 + "$");
player.setGamesWon(1);
player.setTotalWinnings(10);
}
if (userGuess != compGuess && (userGuess <= (compGuess + 5)) && (userGuess >= (compGuess - 5))) {
System.out.println("Lucky Number was : " + compGuess + "your FINAL guess was : " + userGuess);
System.out.println("Congratulations you won " + cnum + "$");
player.setTotalWinnings(5);
} else if (userGuess != compGuess) {
System.out.println("Lucky Number was : " + compGuess + "your guess was : " + userGuess);
System.out.println("Sorry better Luck Next time");
player.setGamesLost(1);
player.setTotalWinnings(-1);
}
} while (userGuess != compGuess && numAttempts < 3);
}
public void createNewPlayer(Scanner scanner) {
String name = null;
do {
try {
System.out.println("Enter the name of the player: ");
name = scanner.nextLine();
if (name.isEmpty()) {
System.err.println("Name cannot be empty");
}
} catch (Exception e) {}
} while (name.isEmpty());
this.player = new Player(name);
}
public static void main() {
Game game = new Game();
game.eventLoop();
}
}

do {
try {
System.out.println("Guess a number between 1-100: ");
userGuess = Integer.parseInt(scanner.nextLine());
if (userGuess < 1 || userGuess > 100) {
System.err.println("Error : your Guess must be between 1-100");
}
} catch (Exception e) {
System.err.println("Error : your Guess must be between 1-100");
}
} while(userGuess < 1 && userGuess > 100);//incorrect
//correct condition -> while(userGuess < 1 || userGuess > 100);
a number cannot be less than 1 and greater than 100 at the same time.
Edit 1 : In your 2nd loop the following two condition
1) if (userGuess != compGuess && (userGuess <= (compGuess + 5))
&& (userGuess >= (compGuess - 5)))
2)else if (userGuess != compGuess)
should only be evaluated if the number of guesses by player exceeds the number of attempts, therefore the two if conditions should be written outside the loop.
Also you need the first while loop to keep the user input valid between 1-100, And your second while loop will be inside it.
The final code will look something like this.
do {
do {
try {
System.out.println("Guess a number between 1-100: ");
userGuess = Integer.parseInt(sc.nextLine());
if (userGuess < 1 || userGuess > 100) {
System.err
.println("Error : your Guess must be between 1-100");
}
} catch (Exception e) {
System.err
.println("Error : your Guess must be between 1-100");
}
} while (userGuess < 1 || userGuess > 100);
System.out.println(" " + userGuess);
if (userGuess > compGuess) {
System.out.println("Your Guess is: " + userGuess
+ "and the random number: " + compGuess);
System.out.println("Sorry, you need to go LOWER :");
}
if (userGuess < compGuess) {
System.out.println("Your Guess is: " + userGuess
+ "and the random number: " + compGuess);
System.out.println("Sorry, you need to go HIGHER :");
System.out.println("if 1");
}
numAttempts++;
if (userGuess == compGuess) {
System.out.println("Lucky Number was : " + compGuess
+ "your guess was : " + userGuess);
System.out.println("Congratulations you won " + 10 + "$");
// player.setGamesWon(1);
// player.setTotalWinnings(10);
}
} while (userGuess != compGuess & numAttempts < 3);
if (userGuess != compGuess && (userGuess <= (compGuess + 5))
|| (userGuess >= (compGuess - 5))) {
System.out.println("Lucky Number was : " + compGuess
+ " your FINAL guess was : " + userGuess);
// System.out.println("Congratulations you won " + cnum + "$");
// player.setTotalWinnings(5);
} else if (userGuess != compGuess) {
System.out.println("Lucky Number was : " + compGuess
+ "your guess was : " + userGuess);
System.out.println("Sorry better Luck Next time");
// player.setGamesLost(1);
// player.setTotalWinnings(-1);
}
}

Try to put the first do-while in the second do-while at the top.

while(userGuess < 1 && userGuess > 100);
do{
This contains the error. The loop should run while the userGuess is between 1 and 100, you have excluded it.
It should be
while(userGuess >= 1 && userGuess <= 100);
do{

AND condition needs to be changed to an OR condition. Because you want to loop only when the user inputs something lower than 1 or higher than 100.
while(userGuess < 1 && userGuess > 100); ===> while(userGuess < 1 || userGuess > 100);
Again, another AND needs to be changed to OR.
// Issue with logic
if (userGuess != compGuess && (userGuess <= (compGuess + 5)) &&
(userGuess >= (compGuess - 5))) {
// Corrected Code
if (userGuess != compGuess && (userGuess <= (compGuess + 5)) ||
(userGuess >= (compGuess - 5))) {

Related

Calcu: How to add the operator before each number like a real calc

I'm just trying to build a calculator and I have no idea how to prompt an operator before each number. I'm trying to build a calculator and have as many number inputs as specified but they can cancel out of it by pressing -1 and it will still return the final value.
But i tried using a string statements but I'm new to coding and don't know where to start.
int operator;
int howmany;
int i=0;
int all = 0;
double div;
int scan;
System.out.println("Press 1 for addition, 2 for subtraction, 3 for \n
multiplication 4 for division or 5 for modules");
operator=scanner.nextInt();
if(operator < 1 || operator >5) {System.out.println("Restart
calculator");System.exit(0);}
System.out.println("How many numbers will you be using?");
howmany = scanner.nextInt() -1 ;
if (operator == 1){
System.out.println("Press -1 to cancel ");
while(i <=howmany) {
i++;
System.out.println("Enter number" + i);
System.out.println("So far your numbers is " + all);
scan = scanner.nextInt();
all += scan;
if(i-1 == howmany ) {
System.out.println("Your final answer is " + all);
}
if(scan == -1) {
System.out.println("No more inputs, final answer was " + all);
break;
}
}
}
if (operator == 2){
System.out.println("Press -1 to cancel ");
while(i <=howmany) {
i++;
System.out.println("Enter number" + i);
System.out.println("So far your numbers is " + all);
scan = scanner.nextInt();
all -= scan;
if(i-1 == howmany ) {
System.out.println("Your final answer is " + all);
}
if(scan == -1) {
System.out.println("No more inputs, final answer was " + all);
break;
}
}
}
if (operator == 3){
all = 1;
System.out.println("Press -1 to cancel ");
while(i <=howmany) {
i++;
System.out.println("Enter number" + i);
System.out.println("So far your numbers is " + all);
scan = scanner.nextInt();
all *= scan;
if(i-1 == howmany ) {
System.out.println("Your final answer is " + all);
}
if(scan == -1) {
System.out.println("No more inputs, final answer was " + all);
break;
}
}
}
if (operator == 4){
System.out.println("Press -1 to cancel ");
while(i <=howmany) {
i++;
System.out.println("Enter number" + i);
System.out.println("So far your numbers is " + all);
scan = scanner.nextInt();
all = scan;
if(i-1 == howmany ) {
System.out.println("Your final answer is " + all);
}
if(scan == -1) {
System.out.println("No more inputs, final answer was " + all);
break;
}
}
}
if (operator == 5){
System.out.println("Press -1 to cancel ");
while(i <=howmany) {
i++;
System.out.println("Enter number" + i);
System.out.println("So far your numbers is " + all);
scan = scanner.nextInt();
all %= scan;
if(i-1 == howmany ) {
System.out.println("Your final answer is " + all);
}
if(scan == -1) {
System.out.println("No more inputs, final answer was " + all);
break;
}
}
}
}
}
When you don't know where to start when coding, it can help to write the algorithm in sentences first, and then convert into code. For a calculator program for example, I would start with this basic structure:
// need a data structure to hold all numbers
// need a data structure to hold all operations
while(the user wishes to continue) {
while(the user has not hit =) {
// use the scanner to get the next number (if it's -1, exit program)
// use the scanner to get the next operator (if it's = then exit inner
// loop to report result)
}
// need variable to hold calculation result, instantiate to first number
for(loop through numbers data structure) {
// apply next operator to the running result and next number
}
// report result to user
}
Something else to consider: a calculator should be able to use -1 in calculations. I'm not sure if this is a requirement of what you're working on, so I left it as you described, but what would be more in line with the spirit of a calculator would be to do something like ask the user after each successful calculation if they'd like to continue (y/n).

Do While loop with Yes = start again No = exit Program

I have to add a do-while loop to my project so after the program iterates it says: "You want a run this program again? (Yes or No)"
If user inputs are Yes or YEs or YES or yEs or yES or yeS
It runs a program again.
If it's no, program should automatically exit.
import java.text.DecimalFormat;
import java.util.Scanner;
public class CalculatePay {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String Name = " ";
int hours;
double payRate;
char F;
char P;
char T;
String input = " ";
char repeat = input.charAt(0);
double grossPay;
int attempt = 0;
System.out.print("What is your name? ");
Name = reader.nextLine();
System.out.print("How many hours did you work? ");
hours = reader.nextInt();
while (hours < 0 || hours > 280)
{
System.out.println("That's not possible, try again!");
hours = reader.nextInt();
attempt++;
if(attempt >= 2) {
System.out.println("You are Fired!");
return ;
}
}
System.out.print("What is your pay rate? ");
payRate = reader.nextDouble();
System.out.print("What type of employee are you? ");
F = reader.next().charAt(0);
grossPay = hours * payRate;
DecimalFormat decFor = new DecimalFormat("0.00");
switch (F)
{
case 'F' :
case 'f' :
System.out.println("Hi " + Name + ", you made $" + decFor.format(grossPay) + " this week"+" as a full-time employee");
if (hours < 0)
{
System.out.println(" That's not possible ");
}
else if (hours > 280)
{
System.out.print(" That's not possible ");
}
else if (grossPay >= 100)
{
System.out.print(" You must be a Java programmer!");
}
else
{
System.out.print(" this week");
}
break;
case 'P' :
case'p' :
System.out.println("Hi " + Name + ", you made $" + decFor.format(grossPay) + " this week"+" as a part- time employee");
if (hours < 0)
{
System.out.println(" That's not possible ");
}
else if (hours > 280)
{
System.out.print(" That's not possible ");
}
else if (grossPay >= 100)
{
System.out.print(" You must be a Java programmer!");
}
else
{
System.out.print(" this week");
}
break;
case 'T' :
case 't' :
System.out.println("Hi " + Name + ", you made $" + decFor.format(grossPay) + " this week"+" as a temporary employee");
if (hours < 0)
{
System.out.println(" That's not possible ");
}
else if (hours > 280)
{
System.out.print(" That's not possible ");
}
else if (grossPay >= 100)
{
System.out.print(" You must be a Java programmer!");
}
else
{
System.out.print(" this week");
}
break;
default:
System.out.println(" unknown employee type");
if (hours < 0)
{
System.out.println(" That's not possible ");
}
else if (hours > 280)
{
System.out.print(" That's not possible ");
}
else if (grossPay >= 100)
{
System.out.print(" You must be a Java programmer!");
}
else
{
System.out.print(" this week");
}
}
System.out.println("Do you want to run this program again? (Yes or No)");
}
}
I suggest yo to wrap your logic in another method, so you can call it later:
import java.text.DecimalFormat;
import java.util.Scanner;
public class CalculatePay {
private static void doStuff() {
Scanner reader = new Scanner(System.in);
String Name = " ";
int hours;
double payRate;
char F;
char P;
char T;
String input = " ";
char repeat = input.charAt(0);
double grossPay;
int attempt = 0;
System.out.print("What is your name? ");
Name = reader.nextLine();
System.out.print("How many hours did you work? ");
hours = reader.nextInt();
while (hours < 0 || hours > 280)
{
System.out.println("That's not possible, try again!");
hours = reader.nextInt();
attempt++;
if(attempt >= 2) {
System.out.println("You are Fired!");
return ; }
}
System.out.print("What is your pay rate? ");
payRate = reader.nextDouble();
System.out.print("What type of employee are you? ");
F = reader.next().charAt(0);
grossPay = hours * payRate;
DecimalFormat decFor = new DecimalFormat("0.00");
switch (F)
{
case 'F' :
case 'f' :
System.out.println("Hi " + Name + ", you made $" + decFor.format(grossPay) + " this week"+" as a full-time employee");
if (hours < 0)
{
System.out.println(" That's not possible ");
}
else if (hours > 280)
{
System.out.print(" That's not possible ");
}
else if (grossPay >= 100)
{
System.out.print(" You must be a Java programmer!");
}
else
{
System.out.print(" this week");
}
break;
case 'P' :
case'p' :
System.out.println("Hi " + Name + ", you made $" + decFor.format(grossPay) + " this week"+" as a part- time employee");
if (hours < 0)
{
System.out.println(" That's not possible ");
}
else if (hours > 280)
{
System.out.print(" That's not possible ");
}
else if (grossPay >= 100)
{
System.out.print(" You must be a Java programmer!");
}
else
{
System.out.print(" this week");
}
break;
case 'T' :
case 't' :
System.out.println("Hi " + Name + ", you made $" + decFor.format(grossPay) + " this week"+" as a temporary employee");
if (hours < 0)
{
System.out.println(" That's not possible ");
}
else if (hours > 280)
{
System.out.print(" That's not possible ");
}
else if (grossPay >= 100)
{
System.out.print(" You must be a Java programmer!");
}
else
{
System.out.print(" this week");
}
break;
default:
System.out.println(" unknown employee type");
if (hours < 0)
{
System.out.println(" That's not possible ");
}
else if (hours > 280)
{
System.out.print(" That's not possible ");
}
else if (grossPay >= 100)
{
System.out.print(" You must be a Java programmer!");
}
else
{
System.out.print(" this week");
}
}
}
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
do {
//Call your bussines logic.
doStuff();
System.out.println("Do you want to run this program again? (Yes or No)");
}
while(reader.nextLine().toLowerCase().equals("yes"));
} }
Note that the function is static. This is because you can not call a non-static method from a static context (main is static).

How do I get the break command to go back to my for each loop

I know I asked a similar question like this earlier (I figured it out though)
*while(!newWord.equalsIgnoreCase(guess))
forloop:
{ while(!newWord.equalsIgnoreCase(guess))
for ( String a : spaces.split("\\s"))
{
count++;
int x = Integer.valueOf(a);
if (x > guess.length())
{
System.out.println("Your input is not valid, try again");
break innerloop;
}
if (Character.toLowerCase(newWord.charAt(x)) == letterInput.charAt(0))
{
//System.out.println("Guess is correct for position " + x);
guess = guess.substring(0, x) + letterInput + guess.substring(x + 1, guess.length());
}
if (Character.toLowerCase(newWord.charAt(x)) != letterInput.charAt(0))
{
if(count < spaces.split("\\s").length - 1)
{
break forloop;
}
}
if (count == spaces.split("\\s").length)
guesses= guesses - 1;
System.out.println("Your letter was not found in spaces you provided");
System.out.println("Guesses Remaining: " + guesses);
break;
}*
but now the break command that I have at the third if statement after the for loop just takes me back to the loop towards the beginning of my whole code
*while(!newWord.equalsIgnoreCase(guess))
innerloop:
{ while(true)
{
System.out.println("Please enter the letter you want to guess");
String letterInput = keyboard.next();
letterInput = Character.toString(letterInput.charAt(0));
if(!Character.isLetter(letterInput.charAt(0)))
{
System.out.println("Your input is not valid, try again");
break;
}
if(letterInput.equalsIgnoreCase("solve"))
{
System.out.println("Please solve the answer:");
String userSolve = keyboard.next();
if (!userSolve.equalsIgnoreCase(newWord))
{
System.out.println("That is not the secret word");
guesses = guesses - 1;
System.out.println("Guesses remaining: " + guesses);
}
else
{
System.out.println("You win!");
System.out.println("You have guessed the word! Congratulations");
System.out.println("Would you like to play again? Yes(y) or No (n)");
response = keyboard.next();
if (response.equalsIgnoreCase("n"))
{
System.exit(0);
}
if(response.equalsIgnoreCase("y"))
{
continue;
}
As you can see I placed labels on the loops I specifically want to go back to. My break is currently taking me back to my innerloop label BUT I want it to take me back to my forloop label. How exactly do I do that? I tried wrapping the for loop with while loops because thats what worked for me last time but it is not working here. Here is my whole code for reference, I apologize if its hard to read I've only started coding 2 months ago.
package e;
import java.util.Scanner;
public class HangmanBeta{
private static final boolean testingMode = true;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
keyboard.useDelimiter("\\n");
while (true) {
System.out.println("Enter your difficulty: Easy (e), Intermediate (i), or Hard (h)");
String diff = keyboard.next();
int amountOfSpaces = 0;
String response = "";
String guess = "";
String newGuess = "";
String s = "";
int count = 0;
String newWord = "loops";//RandomWord.newWord();
int guesses = 0;
for (int i = 0; i < newWord.length(); i++) {
guess = newWord.replaceAll("[^#]", "-");
}
if ((diff.equalsIgnoreCase("e")) || (diff.equalsIgnoreCase("i")) || (diff.equalsIgnoreCase("h"))) {
if (diff.equalsIgnoreCase("e"))
{
guesses = 15;
}
if(diff.equalsIgnoreCase("i"))
{
guesses = 12;
}
if(diff.equalsIgnoreCase("h"))
{
guesses = 15;
}
if (testingMode == true)
{
System.out.println("The secret word is:" + " " + newWord);
}
System.out.println("The word is:" + " " + guess);
while(!newWord.equalsIgnoreCase(guess))
innerloop:
{ while(true)
{
System.out.println("Please enter the letter you want to guess");
String letterInput = keyboard.next();
letterInput = Character.toString(letterInput.charAt(0));
if(!Character.isLetter(letterInput.charAt(0)))
{
System.out.println("Your input is not valid, try again");
break;
}
if(letterInput.equalsIgnoreCase("solve"))
{
System.out.println("Please solve the answer:");
String userSolve = keyboard.next();
if (!userSolve.equalsIgnoreCase(newWord))
{
System.out.println("That is not the secret word");
guesses = guesses - 1;
System.out.println("Guesses remaining: " + guesses);
}
else
{
System.out.println("You win!");
System.out.println("You have guessed the word! Congratulations");
System.out.println("Would you like to play again? Yes(y) or No (n)");
response = keyboard.next();
if (response.equalsIgnoreCase("n"))
{
System.exit(0);
}
if(response.equalsIgnoreCase("y"))
{
continue;
}
}
}
System.out.println("Please enter the spaces you want to check (seperated by spaces)");
String spaces = keyboard.next();
amountOfSpaces = spaces.length();
if (diff.equalsIgnoreCase("e"))
{
if(amountOfSpaces != 7)
{
System.out.println("Your input is not valid, try again");
break innerloop;
}
}
if (diff.equalsIgnoreCase("i"))
{
if(amountOfSpaces != 5)
{
System.out.println("Your input is not valid, try again");
break innerloop;
}
}
if (diff.equalsIgnoreCase("h"))
{
if(amountOfSpaces != 3)
{
System.out.println("Your input is not valid, try again");
break innerloop;
}
{
while(!newWord.equalsIgnoreCase(guess))
forloop:
{ while(!newWord.equalsIgnoreCase(guess))
for ( String a : spaces.split("\\s"))
{
count++;
int x = Integer.valueOf(a);
if (x > guess.length())
{
System.out.println("Your input is not valid, try again");
break innerloop;
}
if (Character.toLowerCase(newWord.charAt(x)) == letterInput.charAt(0))
{
//System.out.println("Guess is correct for position " + x);
guess = guess.substring(0, x) + letterInput + guess.substring(x + 1, guess.length());
}
if (Character.toLowerCase(newWord.charAt(x)) != letterInput.charAt(0))
{
if(count < spaces.split("\\s").length - 1)
{
break forloop;
}
if (count == spaces.split("\\s").length)
guesses= guesses - 1;
System.out.println("Your letter was not found in spaces you provided");
System.out.println("Guesses Remaining: " + guesses);
break;
}
if (guesses == 0)
{
System.out.println("You have failed to guess the word....:(");
System.out.print("Would you like to play again? Yes(y) or No(n)");
response = keyboard.next();
if (response.equalsIgnoreCase("n"))
{
System.exit(0);
}
if(response.equalsIgnoreCase("y"))
{
continue;
}
} }
if (newWord.equalsIgnoreCase(guess))
{
System.out.println("You win!");
System.out.println("You have guessed the word! Congratulations");
System.out.println("Would you like to play again? Yes(y) or No (n)");
response = keyboard.next();
if (response.equalsIgnoreCase("n"))
{
System.exit(0);
}
if (response.equalsIgnoreCase("y"))
{
continue;
}
}
}
System.out.println("Your Guess is in the word");
}
if(guesses == guesses - 1)
{
System.out.println("Your letter was not found in spaces you provided");
System.out.println("Guesses Remaining: " + guesses);
break innerloop;
//System.out.print(spaces.split("\\s").length);
//System.out.println("Your Guess is in the word");
//System.out.println();
//System.out.println("Updated word " + guess);
//System.out.println("Guesses Remaining: " + guesses);
}
}
}
}
}
}
}
}
... but now the break command that I have at the third if statement after the for loop just takes me back to the loop towards the beginning of my whole code.
Actually, no.
A break never takes you back. It always takes you forward. In this case it takes you forward to immediately after the block with the label that you broke. For example:
while (....) {
label: while (...) {
...
if (...) break label;
...
}
// Breaks to HERE
}
You may then go back because of something in the context you went to. But it is the context that does it, not the break.
Unfortunately, I can't figure out how to apply this to your example because 1) you don't explain what the code is supposed to do, 2) it is hard to figure out which of the versions you refer to, 3) the code is not compilable, and 4) the readability issues make my head hurt.
So unless you can figure out how to make your code more readable, that is all the help I can give you.

trying to understand my error in my pig java game

I am working on my final project for my intro to java class and i am having a hard time understanding the errors in my project and why it will not run if you could tell me why i would greatly appreciate it
public static void main(String[] args) {
Scanner scanner1;
int dice, dice2;
int pScore, cScore = 0;
int pTotalScore = 0;
int cTotalScore = 0;
final int maxScore = 750;
String input = "R";
String input2 = "R";
char repeat;
Random randomNumbers = new Random();
System.out.println("Welcome to Our version of the dice game Pig");
System.out.println("Here are the instructions");
System.out.println("On a turn, the player or computer rolls the die repeatedly");
System.out.println("Until either a 1,7,12, or 17 is rolled");
System.out.println("or the player or computer holds");
System.out.println("If a 1,7,12, or 17 is rolled, that player's turn ends");
System.out.println("and no points are earned");
System.out.println("If the player chooses to hold, all of the points rolled during");
System.out.println("that turn are added to his or her score.");
System.out.println("First player to 750 points or more WINS!");
System.out.print("\nPlease enter your name: ");
scanner1 = new Scanner(System.in);
String pName = scanner1.nextLine();
System.out.print("\nI Hope You have fun," + pName);
do { // run at least once. Start of loop
dice = randomNumbers.nextInt(6) + 1;
System.out.println();
System.out.printf("%s you rolled a %d %n", pName, dice);
if (dice == 1 || dice == 7 || dice == 12 || dice == 17) // if these numbers, end
{
pScore = 0;
System.out.println("Turn over.");
System.out.println(" " + pName + " total is " + pScore + " ");
break;
} else { // else ask for re-roll
pScore = dice;
pTotalScore += pScore;
System.out.print(+pScore + " Your turn total is " + pTotalScore + " ");
System.out.print("Enter (R) to roll or (H)to hold: ");
input = scanner1.nextLine();
repeat = input.charAt(0);
}
if (repeat != 'R') { // if something other than R, end
break;
}
} while (pTotalScore < 750 || cTotalScore < 750); // allow repeat so long as scores are less than 750
if (repeat == 'H') {
System.out.println("Turn over.");
System.out.print("Current score: " + pname + " has " + pTotalScore);
System.out.println("The Computer has " + cTotalScore);
break;
}
while (input.equalsIgnoreCase("R"));
if (pTotalScore >= maxScore) {
System.out.println("Your total Score is " + totalScore);
System.out.println(+pname + "WINS!");
break;
}
System.out.println();
System.out.println("It is the Computer's turn.");
do {
dice2 = randomNumbers.nextInt(6) + 1;
System.out.println("The Computer rolled: " + dice2);
if (dice2 == 1 || dice2 == 7 || dice2 == 12 || dice2 == 17) {
cScore = 0;
System.out.print("Turn over");
System.out.println("The Computer total is " + cTotalScore);
break;
} else {
cScore = dice2;
cTotalScore += cScore;
System.out.print("The Computer's total is " + cTotalScore + " ");
System.out.print("Enter (r) to Roll or (H)to Hold: ");
input = keyboard.nextLine();
repeat = input.charAt(0);
}
if (repeat == 'H') {
System.out.println("Turn over");
System.out.print("Current score:" + pName + " has " + pTotalScore);
System.out.println(", The Computer has " + cTotalScore);
break;
}
} while (input2.equalsIgnoreCase("R"));
if (cTotalScore >= maxScore) {
System.out.println("The Computer's score is " + cTotalScore + "\n");
System.out.println("The Computer wins!!!!");
System.out.printl("Run The uprisng has begun!!!!!!");
break;
}
Final3.java:112: error: reached end of file while parsing } ^ 1 error
now the problem is i get the error basically means im missing a } but i cant see where it would be nd no matter where i put it it still says
Final3.java:112: error: reached end of file while parsing } ^ 1 error
You have one while loop that does nothing - while (input.equalsIgnoreCase("R")); - and you didn't close your main method. Add } at the end.
Add a closing brace "}" in the end.I hope this will solve your purpose.

Trying to make a lottery program which asks the user how many people want to enter the lottery

The program should output the name, email, and phone number. I need help so far I have a lottery for each individual user... I would need help trying to have one winning lottery and have each person input their numbers. Also, there is a problem when inputting two or more people. It just shows the winning lottery plus the numbers of the previous winning lottery numbers.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean error = true;
int customerAmount;
String name, phone, email, lottery = "";
String lotteryNum = "";
String userGuess;
double pickedNumber;
String stringOfPickedNumber = "";
int correct;
int counter;
customerAmount = Integer.parseInt(JOptionPane.showInputDialog("How many people would you like to enter?"));
for (int i = 0; i < customerAmount; i++) {
name = JOptionPane.showInputDialog("Please enter person " + (i + 1) + "'s name");
phone = JOptionPane.showInputDialog("Please enter person " + (i + 1) + "'s phone number");
email = JOptionPane.showInputDialog("Please enter person " + (i + 1) + "'s email");
JOptionPane.showMessageDialog(null, "Please type in the output box below.");
System.out.println("Guess person " + (i + 1) + "'s three digit number (e.g. 123): ");
userGuess = input.next();
System.out.println("");
System.out.println("Name: " + name);
System.out.println("Phone Number: " + phone);
System.out.println("Email: " + email);
//Identify the repeated steps and use a for loop structure
//Input: Ask user to guess 3 digit number
//Generate a 3-digit "lottery" number composed of random numbers
for (counter = 1; counter <= 3; counter++) {
pickedNumber = Math.random();
if (pickedNumber < 0.1) {
stringOfPickedNumber = "0";
} else if (pickedNumber < 0.2) {
stringOfPickedNumber = "1";
} else if (pickedNumber < 0.3) {
stringOfPickedNumber = "2";
} else if (pickedNumber < 0.4) {
stringOfPickedNumber = "3";
} else if (pickedNumber < 0.5) {
stringOfPickedNumber = "4";
} else if (pickedNumber < 0.6) {
stringOfPickedNumber = "5";
} else if (pickedNumber < 0.7) {
stringOfPickedNumber = "6";
} else if (pickedNumber < 0.8) {
stringOfPickedNumber = "7";
} else if (pickedNumber < 0.9) {
stringOfPickedNumber = "8";
} else if (pickedNumber < 1) {
stringOfPickedNumber = "9";
}
System.out.println(counter + ": " + stringOfPickedNumber);
lotteryNum += stringOfPickedNumber;
}
//print the lottery number
System.out.println("The winning lotto number for person " + (i + 1) + " was: " + lotteryNum);
//convert each string to appropriate substrings
//Compare the user's guess to the lottery number and report results
correct = 0;
for (counter = 0; counter <= 2; counter++) {
if (lotteryNum.substring(counter, (counter + 1)).equals(userGuess.substring(counter, (counter + 1)))) {
correct++;
}
}
if (correct == 2 && !(lotteryNum.substring(0, 1).equals(userGuess.substring(0, 1)) && (lotteryNum.substring(2, 3).equals(userGuess.substring(2, 3))))) {
System.out.println("One pair matched, congrats!");
} else if (correct == 3) {
System.out.println("All numbers matched - you WIN!");
} else if (correct == 1) {
System.out.println("One number matched, but you aren't a winner, sorry.");
} else if (correct == 2) {
System.out.println("Two numbers matched, but they weren't adjacent so you aren't a winner, sorry");
} else {
System.out.println("No numbers matched, sorry.");
}
}
}
}

Categories

Resources