variable from if statement doesn't correctly count up - java

I made a quiz program in java. Everything works, but the counter at the end that counts the amount of questions that have been answered correctly doesn't correctly count up, and always says "3 out of 3" even if all questions are answered wrong. What did I do wrong?
import java.util.Scanner;
class quiz {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
int q1, q2, q3, result;
boolean onepoint, twopoint, threepoint;
result = 0;
onepoint = false;
twopoint = false;
threepoint = false;
System.out.println("Interactive quiz");
System.out.println("");
System.out.println("Q1) Which country is new york located in?");
System.out.println(" 1) Canada");
System.out.println(" 2) United States");
System.out.println(" 3) China");
System.out.println(" 4) Russia");
System.out.println("");
System.out.print("> ");
q1 = input.nextInt();
if (q1 == 2) {
System.out.println("Your answer is correct.");
onepoint = true;
}
else if (q1 != 2) {
System.out.println("Your answer is incorrect.");
threepoint = false;
}
System.out.println("");
System.out.println("Q2) Which of these animals are not warm blooded?");
System.out.println(" 1) Bear");
System.out.println(" 2) Crow");
System.out.println(" 3) Elephant");
System.out.println(" 4) Frog");
System.out.println("");
System.out.print("> ");
q2 = input.nextInt();
if (q2 == 4) {
System.out.println("Your answer is correct.");
twopoint = true;
}
else if (q2 != 4) {
System.out.println("Your answer is incorrect.");
threepoint = false;
}
System.out.println("");
System.out.println("Q3) Which of these plants are carnivorous?");
System.out.println(" 1) Dandelion");
System.out.println(" 2) rafflesia");
System.out.println(" 3) cape sundew");
System.out.println(" 4) titan arum");
System.out.println("");
System.out.print("> ");
q3 = input.nextInt();
if (q3 == 3) {
System.out.println("Your answer is correct.");
threepoint = true;
}
else if (q3 != 3) {
System.out.println("Your answer is incorrect.");
threepoint = false;
}
System.out.println("");
if (onepoint = true) {
result = result + 1;
}
if (twopoint = true) {
result = result + 1;
}
if (threepoint = true) {
result = result + 1;
}
System.out.println("Your final score is " + result + " out of 3.");
}
}
I have a feeling that it probably has to do with my if statements near the end. I tried playing around with them, but still couldn't get it to work.

These are all assignments, point = true. Use the equality operator or the boolean as the condition
if (onepoint == true) {
result = result + 1;
}
or
if (onepoint) {
result = result + 1;
}
If you are using the booleans as point trackers you could consider adding the point values immediately after judging the answer. ex:
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
int result = 0;
System.out.println("Interactive quiz\n");
System.out.println("Q1) Which country is new york located in?");
System.out.println(" 1) Canada");
System.out.println(" 2) United States");
System.out.println(" 3) China");
System.out.println(" 4) Russia");
System.out.println("");
System.out.print("> ");
if(input.nextInt() == 2){
System.out.println("Your answer is correct.");
result++
}else
System.out.println("Your answer is incorrect.");
System.out.println("");
System.out.println("Q2) Which of these animals are not warm blooded?");
System.out.println(" 1) Bear");
System.out.println(" 2) Crow");
System.out.println(" 3) Elephant");
System.out.println(" 4) Frog");
System.out.println("");
System.out.print("> ");
if (input.nextInt() == 4) {
System.out.println("Your answer is correct.");
result++;
}else
System.out.println("Your answer is incorrect.");
System.out.println("");
System.out.println("Q3) Which of these plants are carnivorous?");
System.out.println(" 1) Dandelion");
System.out.println(" 2) rafflesia");
System.out.println(" 3) cape sundew");
System.out.println(" 4) titan arum");
System.out.println("");
System.out.print("> ");
if (input.nextInt() == 3) {
System.out.println("Your answer is correct.");
result++;
}else
System.out.println("Your answer is incorrect.");
System.out.println("");
System.out.println("Your final score is " + result + " out of 3.");
}

Related

Throws Exception when trying to break loop because a condition has been met

I am trying to figure out why I cannot get the loop to break if either "n" is input for playAgain or when the total is below $10. If you see how I can break the loop to run the gameOver function without having an exception thrown that would be a great help. I have noted in the code below that I am having trouble with. I am unsure why this exception is being thrown. If you are able to find out how to break the loop when total is less than 10 or when playAgain is false please let me know!
import java.util.Random;
import java.util.Scanner;
public class GameOfCrapsTester {
static Scanner in = new Scanner(System.in);
static Random rand = new Random();
public static void main(String[] args) {
System.out.println("Welcome to the game of Craps");
System.out.println(" ");
System.out.println("The house has given you a starting balance of $500");
System.out.println("On each round, you will make a whole number wager.");
System.out.println("The minimum wager is $10, and the maximum wager is your remaining balance.");
System.out.println(" ");
System.out.println("You may keep playing until you decide to cash in, or");
System.out.println(" you can't cover the minimum wager.");
System.out.println("Good Luck!");
boolean win;
double wins = 0, numOfGames = 0;
int total = 500;
// Come out roll and set point value
int pointValue = 0;
boolean playAgain = true;
while (playAgain && total > 0)
{
System.out.println(" ");
System.out.println("Your balance is $" + total);
System.out.println(" ");
System.out.println("Place your bet: $");
// Get and check wager placed
int bet = in.nextInt();
while (bet > total || bet < 10)
{
if (bet < 10)
{
System.out.println("Bet must be larger than $10.");
}
System.out.println("I'm sorry, that's not a valid wager; please re-enter: ");
bet = in.nextInt();
}
int num = rollDice();
if ((num >= 4 && num <= 10 && num != 7) || num == 0)
{
pointValue = num;
System.out.println(" ");
System.out.println("Your point value is " + pointValue);
System.out.println(" ");
win = rollWithPoint(pointValue);
if (win)
{
total = wonGame(bet, total);
wins++;
numOfGames++;
System.out.println("Wins: " + wins + " Number of games: " + numOfGames);
}
else if (!win)
{
total = lostGame(bet, total);
numOfGames++;
System.out.println("Wins: " + wins + " Number of games: " + numOfGames);
}
}
else if (num == 7 || num == 11)
{
total = wonGame(bet, total);
wins++;
numOfGames++;
System.out.println("Wins: " + wins + " Number of games: " + numOfGames);
}
else
{
total = lostGame(bet, total);
numOfGames++;
System.out.println("Wins: " + wins + " Number of games: " + numOfGames);
}
if (total <= 9) // THIS IS WHERE I AM HAVING TROUBLE
{
break;
}
System.out.println("Keep playing (y/Y or n/N)? ");
in.nextLine();
String again = in.nextLine();
if (again.equalsIgnoreCase("y"))
{
playAgain = true;
}
else if (again.equalsIgnoreCase("n")) // THIS IS WHERE I AM HAVING TROUBLE
{
break;
}
else
{
System.out.println("Invalid character input, try again:");
again = in.nextLine();
}
}// end of loop
gameOver(wins, numOfGames);
} // END of main
public static int rollDice() {
int dice1, dice2, total;
dice1 = rand.nextInt(6) + 1;
dice2 = rand.nextInt(6) + 1;
total = dice1 + dice2;
System.out.print("Your roll: ");
System.out.print("Dice1: " + dice1);
System.out.print(", Dice2: " + dice2);
System.out.println("; Roll Value: " + total);
return total;
} // END of rollDice
public static boolean rollWithPoint(int point) {
int total = rollDice();
boolean winner = false;
while(total != 7 && winner == false)
{
total = rollDice();
if (total == point)
{
winner = true;
}
else
{
winner = false;
}
}
return winner;
} // END of rollWithPoint
public static int lostGame(int bet, int total) {
System.out.println("Oh, I'm sorry, you lost.");
System.out.println(" ");
total = total - bet;
System.out.println("Your current balance: $" + total);
System.out.println(" ");
return total;
} // END of lostGame
public static int wonGame(int bet, int total) {
System.out.println("A winner!");
System.out.println(" ");
total = total + bet;
System.out.println("Your current balance: $" + total);
System.out.println(" ");
return total;
} // END of wonGame
public static void gameOver(double win, double tot) {
double winPercent = (win / tot) * 100;
System.out.println(" ");
System.out.printf("Based on your play, the probability of winning is %.2%", winPercent);
System.out.println(" ");
System.out.println("Seems you lost your shirt; better luck next time.");
System.out.println("Have a nice day! Hope to see you soon!");
} // END of gameOver
} // END of GameOfCraps
There is no error when you change this (without using String.format()):
System.out.printf("Based on your play, the probability of winning is %.2%", winPercent);
To this:
System.out.println("Based on your play, the probability of winning is " + winPercent + "%.");
Example with a little bet (console):
Your balance is $11
Place your bet: $
10
Your roll: Dice1: 1, Dice2: 2; Roll Value: 3
Oh, I'm sorry, you lost.
Your current balance: $1
Wins: 0.0 Number of games: 2.0
Based on your play, the probability of winning is 0.0%.
Seems you lost your shirt; better luck next time.
Have a nice day! Hope to see you soon!
I cannot get the loop to break if either "n" is input for playAgain or
when the total is below $10.
It works fine too. If I put a bet below 10 it asks me to put another bit. What

Can't get my code to repeat the questions for the game to continue

I have to write a code for my class I'm taking. It is a game based on betting on 2 colors and numbers from 1 - 36. The user has a set amount of chips already given to them which is 100. I have already written most of the code, however, I can't get my code to repeat the process. I am currently using a Do-While loop. but it just isn't working.
Here is my code:
import java.util.Scanner;
import java.lang.Math;
public class Program_8 {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
int chipsNow = 100;
int userChoice;
int chipsBetted = 0;
//welcome message
welcome();
do {
int spinNum = (int)(Math.random() * 36) + 0;
userChoice = getMenuChoice(userInput);
//get user choice
if (userChoice == 1) {
int getNum = getNumber(userInput);
int getBet = getBet(userInput, chipsNow);
String determineColor = determineColor(spinNum);
System.out.println("\nSpinning Wheel....");
System.out.println("Spin Number: " + spinNum);
System.out.println("Spin Color: " + determineColor);
if (getNum == spinNum) {
chipsNow += getBet;
chipsBetted += getBet;
System.out.println("Congrats, you won!");
System.out.println("\nYou now have: " + chipsNow + " chips");
;
}
else {
chipsNow -= getBet;
System.out.println("\nSorry, you lost!");
System.out.println("You now have: " + chipsNow + " chips");
}
}
if (userChoice == 2) {
String getColor = getColor(userInput);
int getBet = getBet(userInput, chipsNow);
String determineColor = determineColor(spinNum);
System.out.println("Spinning Wheel....");
System.out.println("Spin Number: " + spinNum);
System.out.println("Spin Color: " + determineColor);
if (getColor.equals(determineColor)) {
chipsNow += getBet;
chipsBetted += getBet;
System.out.println("\nCongrats, you won!");
System.out.println("You now have: " + chipsNow + " chips");
}
else {
chipsNow -= getBet;
System.out.println("\nSorry, you lost!");
System.out.println("You now have: " + chipsNow + " chips");
}
}
}while (userChoice != 3 && chipsNow > 0);
}
//welcome message
public static void welcome() {
int chipsNow = 100;
System.out.println("############################");
System.out.println("# Welcome To Roulette #");
System.out.println("############################");
System.out.println("# Number Bets Payout: 35:1 #");
System.out.println("# Color Bets Payout: 1:1 #");
System.out.println("############################\n");
System.out.println("Chips owned: " + chipsNow + "\n");
System.out.println("1. Pick a number to bet on");
System.out.println("2. Pick a color to bet on");
System.out.println("3. Cash Out\n");
}
//get menu choice
public static int getMenuChoice(Scanner userInput) {
int getMenuChoice;
System.out.println("\nChoose an option [1-3]: ");
getMenuChoice = userInput.nextInt();
return getMenuChoice;
}
public static int getNumber(Scanner userInput) {
int getNumber;
do {
System.out.println("Enter a number to bet on [0-36]: ");
getNumber = userInput.nextInt();
}while (getNumber < 0 || getNumber > 36);
return getNumber;
}
public static String getColor(Scanner userInput) {
String getColor = "";
do{
System.out.println("Enter a color to bet on [Red or Black]: ");
getColor = userInput.next();
}while (!(getColor.equals("Red") || getColor.equals("Black")));
return getColor;
}
public static int getBet(Scanner userInput, int chipsNow) {
int getBet;
do{
System.out.println("Enter the number of chips to bet [1 - " + chipsNow + "]: ");
getBet = userInput.nextInt();
}while (getBet < 1 || getBet > chipsNow);
return getBet;
}
public static String determineColor(int spinNum) {
if (spinNum % 2 == 0) {
if (spinNum == 0) {
return "Green";
}
//even
else {
return "Red";
}
}
return "Black";
}
public static void report(int chipsNow) {
System.out.println("\nThanks for Playing!");
System.out.println("You Won a total of: " + chipsNow + " chips today");
}
}
So just looking at the code I'd:
Declare int userChoice = 0; outside the do while. This is needed for the while condition to work.
welcome(); and userChoice = getMenuChoice(userInput); should move into the do while thus it will repeat the welcome message and ask for a user choice everything the do while executes
Simplify your while loop like this while(userChoice != 3 && chipsNow > 0). This is just to make it more readable.
Lastly remove the break;s in your if(getNum == spinNum) { } else { }. A break will force the while loop to be exited regardless of whether the while condition is met. So basically if you win or lose a game your loop will exit, which I don't think is what you want. You only want the loop to exit if the chipsNow < 0 or the userChoice == 3

Java while loop not closing when getting specific input

I have a decent sized while loop that is supposed end when the answer to the following prompt is answered 'N' for no. Adding Break; after the last line of code causes my program to spit out error codes after reaching this prompt and entering a character. The issue may have to do when formatting as I get errors stating things like " Enter 'Y' to add another laptop to your purchase or 'N' to exit: y
Exception in thread "main" java.util.IllegalFormatConversionException: f != java.lang.String
Here is the while loop:
while (Character.toUpperCase(cont) == 'Y') {
dateTime = Calendar.getInstance();//Obtains current year
System.out.printf("%nTOP LAPTOPS OF %tY"
+ "%n%n1. %-23s %7s $%,9.2f"
+ "%n2. %-23s %8s %,9.2f"
+ "%n3. %-23s %8s %,9.2f"
+ "%n4. %-23s %8s %,9.2f"
+ "%n5. %-23s %8s %,9.2f"
+ "%n%nEnter your choice: ",
dateTime,
"HP Envy 13", " ", 799.99,
"Asus Zen Book 13 UX33FA", " ", 849.99,
"Dell XPS 13", " ", 989.99,
"Alienware Area 51-m", " ", 1999.99,
"Razer Blade Stealth", " ", 1299.00); //Prompt 1
choice = input.nextInt(); //Input is assigned to choice.
if (choice == 5) {
laptop = "Razer Blade Stealth";
price = 1299.00;
} else {
if (choice == 4) {
laptop = "Alienware Area 51 -m";
price = 1999.99;
} else {
if (choice == 3) {
laptop = "Dell XPS 131";
price = 989.99;
} else {
if (choice == 2) {
laptop = "Asus zenbook 13 UX33FA";
price = 849.99;
} else {
if (choice == 1) {
laptop = "HP Envy 13";
price = 799.99;
} else {
System.out.printf("%nInvalid choice! Try again");
}
}
}
}
}
if (choice > 0) {
if (choice < 6) {
System.out.printf("Enter the quantity for %s: ", laptop);
qty = input.nextInt();
lineItem = qty * price;
subtotal = subtotal + tax;
if (trigger == 1) {
orderSummary += String.format("%n%,-9d %-30s %9s %,17.2f", qty, laptop, " ", lineItem);
trigger = 0;
}//END if for $ sign.
else {
orderSummary += String.format("%n%,-9d %-30s %9s %,17.2f", qty, laptop, " ", lineItem);
}
}
}
//Empty call to nextLine()
input.nextLine();
System.out.printf("%nEnter 'Y' to add another laptop to your purchase or 'N' to exit: ");
char y = input.nextLine().charAt(0);
}//END while
Try this, since you didn't show the while block in full,
char y = 'Y';
while(y == 'Y' || y == 'y')
{
// do whatever you want...
// ..................
System.out.println("Enter Y to add another laptop to your purchase or any other char to exit: ");
y = input.next().charAt(0);
}

How can I handle input string, during the process of if, else if, else including Integer.parseInt?

I would like to handle this situation about inputting wrong string, but error keeps happening because of the else if argument.
Tried try, catch but don't know how to apply it to this code.
import java.util.Scanner;
public class game
{
public static void main(String[] args) {
System.out.println("let's start the multiplication game.");
System.out.println("which times table do you want to choose?");
System.out.println("if you want to do it by your choice, please input number among 2~9. Or if you want to do it randomly, please input number 0");
System.out.println("press \"q\" if you want to quit");
System.out.println("==>");
String input;
Scanner s = new Scanner(System.in);
input = s.nextLine();
int answer;
int multiplier = (int)(Math.random()*8+2);
int random = (int)(Math.random()*8+2);
if (input.equals("q"))
{
System.out.print("quit the game.");
}
else if (Integer.parseInt(input) == 0)
{
System.out.println(random+"times table has been made automatically.");
System.out.print(random+" X "+multiplier+" = "+"? input your answer ==> ");
answer = s.nextInt();
if (answer == random*multiplier)
{
System.out.print("You're right!");
}
else
{
System.out.print("Wrong! The right answer is "+random*multiplier+".");
}
}
else if (Integer.parseInt(input)>=2 && Integer.parseInt(input)<=9)
{
int number = Integer.parseInt(input);
System.out.println("You chose"+number+" times table.");
System.out.print(number+" X "+multiplier+" = "+"? input your answer ==> ");
answer = s.nextInt();
if (answer == number*multiplier)
{
System.out.print("You're right!");
}
else
{
System.out.print("Wrong! The right answer is "+number*multiplier+".");
}
}
else
{
System.out.print("Error. Please try again.");
}
}
}
I expect the result from the else block, but when I input wrong string like "c" or "f" and etc, number format exception error: For input string: "c" (or "f" and etc) happens. Thanks for reading this, and hope you solve this problem.
int check = 0;
try{
check = Integer.parseInt(input);
}catch(NumberFormatException e){
System.out.println("Wrong input");
continue;
}
If you loop this input processing,if it enters catch,you may take input again or you can do what you want when invalid input is entered.If there is no exception,check is your input value,then you can use it in your if and else-if statements like
if(check>0){
...
}
Before Else blocks, you can parse the input like this:
if (input.equals("q")) {
System.out.print("quit the game.");
return;
}
int parsedInput = 0;
try {
parsedInput = Integer.parseInt(input);
} catch (NumberFormatException ex) {
System.out.print("Error. Please try again.");
return;
}
Then you can write if-else for integer input like below:
if (parsedInput == 0) { ... }
else if (parsedInput >= 2 && parsedInput <= 9) {...}
Last else is not needed because I moved it to catch block.
try this it can handle exception
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
System.out.println("let's start the multiplication game.");
System.out.println("which times table do you want to choose?");
System.out.println(
"if you want to do it by your choice, please input number among 2~9. Or if you want to do it randomly, please input number 0");
System.out.println("press \"q\" if you want to quit");
System.out.println("==>");
String input;
Scanner s = new Scanner(System.in);
input = s.nextLine();
int answer;
int multiplier = (int) (Math.random() * 8 + 2);
int random = (int) (Math.random() * 8 + 2);
if (input.equals("q")) {
System.out.print("quit the game.");
}
try {
int check_input = Integer.parseInt(input);
if (check_input == 0) {
System.out.println(random + "times table has been made automatically.");
System.out.print(random + " X " + multiplier + " = " + "? input your answer ==> ");
answer = s.nextInt();
if (answer == random * multiplier) {
System.out.print("You're right!");
} else {
System.out.print("Wrong! The right answer is " + random * multiplier + ".");
}
} else if (check_input >= 2 && check_input <= 9) {
int number = Integer.parseInt(input);
System.out.println("You chose" + number + " times table.");
System.out.print(number + " X " + multiplier + " = " + "? input your answer ==> ");
answer = s.nextInt();
if (answer == number * multiplier) {
System.out.print("You're right!");
} else {
System.out.print("Wrong! The right answer is " + number * multiplier + ".");
}
}
else {
System.out.print("Error. Please try again.");
}
} catch (Exception e) {
System.out.print("Error. Please try again.");
}
}
}
You just need to check the user provided input is number or not. Before parsing it.
I have added new isNumberic method which is returning boolean flag depending user's input and verify it.
public class Game {
public static void main(String[] args) {
System.out.println("let's start the multiplication game.");
System.out.println("which times table do you want to choose?");
System.out.println(
"if you want to do it by your choice, please input number among 2~9. Or if you want to do it randomly, please input number 0");
System.out.println("press \"q\" if you want to quit");
System.out.println("==>");
String input;
Scanner s = new Scanner(System.in);
input = s.nextLine();
int answer;
int multiplier = (int) (Math.random() * 8 + 2);
int random = (int) (Math.random() * 8 + 2);
Game game = new Game();
boolean isvalid = game.isNumeric(input);
if (input.equals("q")) {
System.out.print("quit the game.");
}
else if (isvalid && Integer.parseInt(input) == 0) {
System.out.println(random + "times table has been made automatically.");
System.out.print(random + " X " + multiplier + " = " + "? input your answer ==> ");
answer = s.nextInt();
if (answer == random * multiplier) {
System.out.print("You're right!");
} else {
System.out.print("Wrong! The right answer is " + random * multiplier + ".");
}
}
else if (isvalid && Integer.parseInt(input) >= 2 && Integer.parseInt(input) <= 9) {
int number = Integer.parseInt(input);
System.out.println("You chose" + number + " times table.");
System.out.print(number + " X " + multiplier + " = " + "? input your answer ==> ");
answer = s.nextInt();
if (answer == number * multiplier) {
System.out.print("You're right!");
} else {
System.out.print("Wrong! The right answer is " + number * multiplier + ".");
}
}
else {
System.out.print("Error. Please try again.");
}
}
public static boolean isNumeric(String str)
{
for (char c : str.toCharArray())
{
if (!Character.isDigit(c)) return false;
}
return true;
}
}
You can't send values like a , b, c etc for
Integer.parseInt(String s)
https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String)
I have try catch block to catch numberformat exception with message to enter valid integer
public static void main(String args[]) {
System.out.println("let's start the multiplication game.");
System.out.println("which times table do you want to choose?");
System.out.println("if you want to do it by your choice, please input number among 2~9. Or if you want to do it randomly, please input number 0");
System.out.println("press \"q\" if you want to quit");
System.out.println("==>");
String input;
Scanner s = new Scanner(System.in);
input = s.nextLine();
int answer;
int multiplier = (int)(Math.random()*8+2);
int random = (int)(Math.random()*8+2);
try {
if (input.equals("q"))
{
System.out.print("quit the game.");
}
else if (Integer.parseInt(input) == 0)
{
System.out.println(random+"times table has been made automatically.");
System.out.print(random+" X "+multiplier+" = "+"? input your answer ==> ");
answer = s.nextInt();
if (answer == random*multiplier)
{
System.out.print("You're right!");
}
else
{
System.out.print("Wrong! The right answer is "+random*multiplier+".");
}
}
else if (Integer.parseInt(input)>=2 && Integer.parseInt(input)<=9)
{
int number = Integer.parseInt(input);
System.out.println("You chose"+number+" times table.");
System.out.print(number+" X "+multiplier+" = "+"? input your answer ==> ");
answer = s.nextInt();
if (answer == number*multiplier)
{
System.out.print("You're right!");
}
else
{
System.out.print("Wrong! The right answer is "+number*multiplier+".");
}
}
else
{
System.out.print("Error. Please try again.");
}
}
catch (NumberFormatException e ) {
System.out.print("pleae enter Valid integer");
}
It's obvious that you are getting this error because you are calling Integer.parseInt on a string variable which doesn't contain an Integer. What you should be doing is putting a check once you get the input to check if the string contains what you need. Something like below
while (true)
{
// Check that the input is between 0 and 9 or q.
if (!((input.charAt(0) >= '0' && input.charAt(0) <= '9') || input.charAt(0) == 'q'))
{
// If it is not, ask for input again.
System.out.println("Input is not correct. If you want to do it by your choice, please input number among 2~9. Or if you want to do it randomly, please input number 0");
input = s.nextLine();
}
else {
// If input is correct, break this look.
break;
}
}
Below is the whole code
public class game
{
public static void main(String[] args)
{
System.out.println("let's start the multiplication game.");
System.out.println("which times table do you want to choose?");
System.out.println("if you want to do it by your choice, please input number among 2~9. Or if you want to do it randomly, please input number 0");
System.out.println("press \"q\" if you want to quit");
System.out.println("==>");
String input;
Scanner s = new Scanner(System.in);
input = s.nextLine();
while (true)
{
if (!((input.charAt(0) >= '0' && input.charAt(0) <= '9') || input.charAt(0) == 'q'))
{
System.out.println("Input is not correct. If you want to do it by your choice, please input number among 2~9. Or if you want to do it randomly, please input number 0");
input = s.nextLine();
}
else {
break;
}
}
int answer;
int multiplier = (int) (Math.random() * 8 + 2);
int random = (int) (Math.random() * 8 + 2);
if (input.equals("q"))
{
System.out.print("quit the game.");
}
else if (Integer.parseInt(input) == 0)
{
System.out.println(random + "times table has been made automatically.");
System.out.print(random + " X " + multiplier + " = " + "? input your answer ==> ");
answer = s.nextInt();
if (answer == random * multiplier)
{
System.out.print("You're right!");
}
else
{
System.out.print("Wrong! The right answer is " + random * multiplier + ".");
}
}
else if (Integer.parseInt(input) >= 2 && Integer.parseInt(input) <= 9)
{
int number = Integer.parseInt(input);
System.out.println("You chose" + number + " times table.");
System.out.print(number + " X " + multiplier + " = " + "? input your answer ==> ");
answer = s.nextInt();
if (answer == number * multiplier)
{
System.out.print("You're right!");
}
else
{
System.out.print("Wrong! The right answer is " + number * multiplier + ".");
}
}
else
{
System.out.print("Error. Please try again.");
}
}
}
Verify input in two separate if/else blocks. Add this code to your "else" statement to catch strings other than "q".
else{
try {
int inputNumber = Integer.parseInt(input);
if(inputNumber == 0) {
// code..
} else if (inputNumber >= 2 && inputNumber <= 9) {
// code..
}
} catch(java.lang.NumberFormatException e) {
System.out.print("Error. Please try again.");
}
}
why don't use try catch?
if (input.equals("q")) {
System.out.print("quit the game.");
}
try {
Integer i = Integer.parseInt(input);
}catch (NumberFormatException e){
System.out.print("Error. Please try again.");
return;
}

I'm having trouble outputing the user's amount of guesses in a Hangman game

This is basically just a hangman project for my class and I'm not allowed to use arrays. The word is hidden with dashes to the user.The user has to pick a letter and the number of spaces they would like to check. The user has a certain amount of guess depending on the difficulty they choose. If the letter they guessed is in at least one of the spaces they chose then the user loses no guesses, if the letter they guessed is in none of the spaces they chose then the user loses a guess.
for example the output should look like
The secret word is: loops
The word is: -----
Please enter the letter you want to guess
k
Please enter the spaces you want to check (separated by spaces)
0 1 2 3
Your letter was not found in spaces you provided
Guesses Remaining: 14
But it currently looks like this
The secret word is: loops
The word is: -----
Please enter the letter you want to guess
k
Please enter the spaces you want to check (separated by spaces)
0 1 2 3
Your letter was not found in spaces you provided
Guesses Remaining: 14
Your letter was not found in spaces you provided
Guesses Remaining: 13
Your letter was not found in spaces you provided
Guesses Remaining: 12
Your letter was not found in spaces you provided
Guesses Remaining: 11
Here is what I have so far
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 letterInput = "";
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");
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 (separated 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;
}
}
for ( String a : spaces.split("\\s"))
{
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))
{
guesses= guesses - 1;
System.out.println("Your letter was not found in spaces you provided");
System.out.println("Guesses Remaining: " + guesses);
}
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.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);
}
}
}
}
In the example I used the difficulty was set to easy.
There is a bug here:
if (Character.toLowerCase(newWord.charAt(x)) != letterInput.charAt(0))
{
guesses= guesses - 1;
System.out.println("Your letter was not found in spaces you provided");
System.out.println("Guesses Remaining: " + guesses);
}
You cannot print the message directly because you need to make sure all spaces are not matched. This should be work:
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 letterInput = "";
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");
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 (separated 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;
}
}
int numSpacesLeft = spaces.split("\\s").length;
for (String a : spaces.split("\\s")) {
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());
}
numSpacesLeft--;
if (Character.toLowerCase(newWord.charAt(x)) != letterInput.charAt(0)) {
if (numSpacesLeft == 0) {
guesses = guesses - 1;
System.out.println("Your letter was not found in spaces you provided");
System.out.println("Guesses Remaining: " + guesses);
}
}
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.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);
}
}
}
}
Hop this could help you!

Categories