Syntax error on token "else", delete this [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I keep on getting this error and I tried mixing it around. But then when I choose the option, it does the option, but then said "you did not enter 1, 2 or 3".
This is the the full code. How to fix it?
The error is at
} else {
System.out.println("You did not enter 1, 2 or 3");
} else {
System.out.println("The Pin You Entered Was Wrong");
}

This is an incorrect syntax:
}else{
System.out.println("You did not enter 1, 2 or 3");
}else{
System.out.println("The Pin You Entered Was Wrong");
Just do it this way:
else {
System.out.println("You did not enter 1, 2 or 3");
System.out.println("The Pin You Entered Was Wrong");
}

The problem is in the code you provided on your paste bin.
You use two else statements, so Java complains as it doesn't know which to go to after the initial if statement.
You need to enter in another conditional statement using else if, then else. For example:
if (option == 1){
Option_1 Optionone = new Option_1();
Optionone.Withdraw();
}
etc
}else if (nothing entered) {
System.out.println("You did not enter 1, 2 or 3");
}else{
System.out.println("The Pin You Entered Was Wrong");
}
You also have another major problem with your code. You declare the variable option and set it in an if statement, so it only has scope within that if statement. You then come out of the if statement and declare a brand new option variable before the code I provided above. This will not function, as the option integer has no value.
Instead, you need to declare your initial option int outside of your if statement, like so:
int number;
int password = 7123;
int amount = 4000;
int option;
if (number == password) {
etc...
option = userInput.nextInt();
}
Furthermore, you come out of the if statement checking the entered number against the stored password to take input on withdrawing cash etc. This is no good. It means that after the if statement checking number against password is finished, it will automatically proceed to the next block of code.
As the scanner object hasn't been created, the first three if statements will come back false and your else statement will be printed (regardless of whether the input password was correct).
Therefore, I would advise you to put that check in a separare else statement and use a while loop to confirm a correct selection ahs been entered. For example:
System.out.println("Please Enter Your Bank Pin.");
Scanner userInput = new Scanner (System.in);
int number;
int password = 7123;
int amount = 4000;
int option;
number = userInput.nextInt();
if (number == password) {
System.out.println("Pin Accepted");
System.out.println("You Have Now Entered Harry's Bank!");
System.out.println("Press The Number Of The Option You Would Like.");
System.out.println("1.Withdraw Money.");
System.out.println("2.Put In Money");
System.out.println("3.Exit Bank");
Scanner Options = new Scanner (System.in);
option = userInput.nextInt();
while (option != 1 || option != 2 || option != 3) {
System.out.println("You didn't enter a valid number. Try again");
option = userInput.nextInt();
}
if (option == 1){
Option_1 Optionone = new Option_1();
Optionone.Withdraw();
}
else if (option == 2){
Option_2 Optiontwo = new Option_2();
Optiontwo.Deposit();
}
else if (option == 3){
Option_3 Optionthree = new Option_3();
Optionthree.Exit();
}
}
else
System.out.println("The Pin You Entered Was Wrong");
}

your second else statement does not close no if statement.
Also, the option variable is not in the right scope:
try this
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("Welcome To Harry's Bank");
//Pin System
System.out.println("Please Enter Your Bank Pin.");
Scanner userInput = new Scanner (System.in);
int number;
int password = 7123;
int amount = 4000;
number = userInput.nextInt();
int option;
if (number == password) {
System.out.println("Pin Accepted");
System.out.println("You Have Now Entered Harry's Bank!");
System.out.println("Press The Number Of The Option You Would Like.");
System.out.println("1.Withdraw Money.");
System.out.println("2.Put In Money");
System.out.println("3.Exit Bank");
Scanner Options = new Scanner (System.in);
option = userInput.nextInt();
}else{
System.out.println("The Pin You Entered Was Wrong");
}
if (option == 1){
Option_1 Optionone = new Option_1();
Optionone.Withdraw();
}
if (option == 2){
Option_2 Optiontwo = new Option_2();
Optiontwo.Deposit();
}
if (option == 3){
Option_3 Optionthree = new Option_3();
Optionthree.Exit();
}else{
System.out.println("You did not enter 1, 2 or 3");
}
}
}

The problem is that you the 'else' statement twice in your if-else construct.
You have:
if { }
else { }
else { }
But you probably want:
if { }
else if { }
else { }

You cannot have TWO else in a if-else case.
Your nested If statement is not proper. Use it as below
if (number == password) {
.....
.....
if (option == 1) {
}
else if (option == 2) {
}
else if (option == 3) {
} else {
System.out.println("You did not enter 1, 2 or 3");
}
} else {
System.out.println("The Pin You Entered Was Wrong");
}

You can't have two else blocks added to an if
} else {
System.out.println("You did not enter 1, 2 or 3");
} else {
System.out.println("The Pin You Entered Was Wrong");
}
Either drop one or club the two println()s into one else block
} else {
System.out.println("You did not enter 1, 2 or 3");
System.out.println("The Pin You Entered Was Wrong");
}
Take a look at how to use the if-then and if-then-else statements.
Alternatively, I suggest you to make use of the Switch statements for better clarity of code.
switch (option) {
case 1: Option_1 OptionOne = new Option_1();
OptionOne.Withdraw();
break;
case 2: Option_2 OptionTwo = new Option_2();
OptionTwo.Withdraw();
break;
case 3: Option_3 OptionThree = new Option_3();
OptionThree.Withdraw();
break;
default: System.out.println("You did not enter 1, 2 or 3");
System.out.println("The Pin You Entered Was Wrong");
}

Related

How do you limit input to "yes" "no"

If a user answers "yes" one of the 4 quotes print, randomly generate a number between 1 out of 4 and not print it, if a user answers "no" it prints "No quotes " and if it's neither it prints "Invalid", Should i use switch? if/else?
This is Java.
public static void main(String[] args) {
Scanner keyedInput = new Scanner(System.in);
String answer;
System.out.println("Do you want to be inspired? (Enter Yes/No)");
var Gen = Math.floor(Math.random() * 4 + 1);
answer = keyedInput.nextLine();
if (answer.equals("Yes")) {
System.out.println("Quote1");
}
else if (answer.equals("Yes")) {
System.out.println("Quote2");
}
else if (answer.equals("Yes")) {
System.out.println("Quote3");
}
else if (answer.equals("Yes")) {
System.out.println("Quote3");
}
if (answer.equals("No")) {
System.out.println("No quotes");
}
else {
System.out.println("Invalid");
}
}
This is a complex task: You want to ask the user yes/no, then if they answer neither 'yes' nor 'no', print something indicating that it's not valid and ask again.
So, make a method! And this method should loop - after all, it needs to keep doing the same thing, over and over again, until the user manages to provide a valid answer.
As a side-note, never use .nextLine(), it doesn't do what you think it does. Only use .next() if you want a string, .nextInt() if you want an int, etcetera. If you want whole lines of input (and you usually do), after making your scanner configure it to read lines at a time with scanner.useDelimiter("\\R");
public static boolean askBoolean(String prompt, Scanner scanner) {
while (true) {
System.out.print(prompt + " (yes/no): ");
String answer = scanner.next();
if (answer.equalsIgnoreCase("Yes")) return true;
if (answer.equalsIgnoreCase("No")) return false;
System.out.println("Please enter yes or no.");
}
}
Let's not use a switch, because equalsIgnoreCase sounds useful here.
and to use:
boolean wantsToBeInspired = askBoolean("Do you want to be inspired?", scanner);
if (wantsToBeInspired) {
showAQuote();
} else {
System.out.println("No quote for you");
}
I believe this is what you are trying to achieve:
int Gen = Math.floor(Math.random() * 4) + 1;
if(answer.equals("Yes")){
switch(Gen){
case 1: System.out.println("Quote 1"); break;
case 2: System.out.println("Quote 2"); break;
case 3: System.out.println("Quote 3"); break;
case 4: System.out.println("Quote 4"); break;
}
}else if(answer.equals("No")){
System.out.println("No quotes");
}else{
System.out.println("Invalid");
}

How do I include a question asking the user if they want to play again?

I am still new to Java and as such I am still figuring some things out. I have been having issues with including code asking the user if they want to play again. I have attempted putting it in the main class in a print statement which gave me an error. After that, I attempted putting it in the Guess.java class in multpile places but I just recieved errors. I have read up on the issue and some sites have suggested a while loop but I am unsure how to implement it into my current code. I have included both the main class which is called GuessingGame.java and the Guess.java class below. Thank you for any assistance that can be provided.
GuessingGame.java
public class GuessingGame {
public static void main(String[] args) {
new Guess().doGuess();
}
}
Guess.java
class Guess {
private int answer = 0;
int tries = 0;
Scanner input = new Scanner(System.in);
int guess, i;
boolean win = false;
int amount = 10;
public Guess() {
answer = generateRandomNumber();
}
//Generate a private number between 1 and a thousand
private int generateRandomNumber() {
Random rand = new Random();
return rand.nextInt(1000) + 1;
}
public void doGuess() {
while (!win) {
System.out.println("You are limited to ten attempts."
+ " Guess a number between 1 and 1000: ");
guess = input.nextInt();
if (tries > 9) {
System.out.println("You should be able to do better!"
+ " You have hit your ten guess limit. The number"
+ " was: " + answer);
System.out.println("Do you want to play again?: ");
return;
}
if (guess > 1000) {
System.out.println("Your guess is out of the range!");
} else if (guess < 1) {
System.out.println("Your guess is out of the range!");
} else if (guess == answer) {
win = true;
tries++;
} else if (guess < answer && i != amount - 1) {
System.out.println("Your guess is too low!");
tries++;
} else if (guess > answer && i != amount - 1) {
System.out.println("Your guess is too high!");
tries++;
}
}
System.out.println("Congragulations! You guessed the number!"
+ "The number was: " + answer);
System.out.println("It took you " + tries + " tries");
}
}
You already found a good position for adding this functionality:
System.out.println("Do you want to play again?: ");
The first step now is to also tell the user what he/she should enter after that question:
System.out.println("Do you want to play again? (enter 0 for yes and 1 for no): ");
After that we need to get the user input of course:
int number;
//If the user enters e.g. a string instead of a number, the InputMismatchException
//will be thrown and the catch-block will be executed
try {
number = input.nextInt();
//If number < 0 OR number > 1
if(number < 0 || number > 1) {
//The rest of the try-block will not be executed.
//Instead, the following catch-block will be executed.
throw new InputMismatchException();
}
break;
}
catch(InputMismatchException e) {
System.out.println("Enter 0=yes or 1=no");
//Clears the scanner to wait for the next number
//This is needed if the user enters a string instead of a number
input.nextLine();
}
If you don't know about try-catch-statements yet, I suggest to read this explanation. For details about the InputMismatchException, please see the documentation.
The problem now is that the user only has one chance to enter 0 or 1. If the user makes a wrong input the program will just stop. One solution to this problem is to just put the code in a while-loop:
int number;
while(true) {
try {
number = input.nextInt();
if(number < 0 || number > 1) {
throw new InputMismatchException();
}
break;
}
catch(InputMismatchException e) {
System.out.println("Enter 0=yes or 1=no");
input.nextLine();
}
}
After this block, we can be sure that number is either 0 or 1. So now we can add a simple if-statement to check the value:
if(number == 0) {
new Guess().doGuess();
}
return;
So all in all the code looks like this:
System.out.println("Do you want to play again? (enter 0 for yes and 1 for no): ");
int number;
while(true) {
try {
number = input.nextInt();
if(number < 0 || number > 1) {
throw new InputMismatchException();
}
break;
}
catch(InputMismatchException e) {
System.out.println("Enter 0=yes or 1=no");
input.nextLine();
}
}
if(number == 0) {
new Guess().doGuess();
}
return;
Don't forget to add the following import-statements:
import java.util.Scanner;
import java.util.InputMismatchException;
import java.util.Random;
Try this. Basically, if the user responds with "yes" , we will call the function again.
if (tries > 9) {
System.out.println("You should be able to do better!"
+ " You have hit your ten guess limit. The number" + " was: " + answer);
System.out.println("Do you want to play again? (yes/no): "); // modified line
if("yes".equalsIgnoreCase(input.next())){ // newly added if block
answer = generateRandomNumber();
tries=0;
i=0;
win = false;
doGuess();
}
return;
}

Why doesn't my Scanner work with 2 different if statements?

New to Java here. I made the following simple code that asks the user to choose between option 1 or 2. If the selected option is 1, then it should print "You said hi", which it works well, also if selected option is 2, it should prints "you said goodbye" which it doesn't, Am I missing something here? Maybe the If statement is wrong?
the Code:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please type 1 to say hi");
System.out.println("Please type 2 to say goodbye");
if (input.nextInt() == 1) {
System.out.println("You said hi");
} else if (input.nextInt() == 2) {
System.out.println("you said goodbye");
}
}
Every time you call nextInt() it stops to wait for an int. Here you want to compare a single int from the user with one or two. Save the int you get from the user. Like,
int v = input.nextInt();
if (v == 1) {
System.out.println("You said hi");
} else if (v == 2) {
System.out.println("you said goodbye");
}
Every time you call nextInt() on your scanner, input is being consumed. So in your case, when the else if condition is checked, the next input is consumed, not the previous one compared. You need to cache your scanner's state:
int answer = input.nextInt();
if (answer == 1) {
System.out.println("You said hi");
} else if (answer == 2) {
System.out.println("you said goodbye")
}
For your specific case, converting to a switch statement would be another option, which evaluates its operand only once:
switch (input.nextInt()) {
case 1:
System.out.println("You said hi");
break;
case 2:
System.out.println("you said goodbye")
break;
}
Every call to input.nextInt() will wait for the new key from input(here it is the user input).
the input.nextInt() == 1 will wait for the user input.
If it is validates to true, the thread will successfully execute System.out.println("You said hi").
Else if it validates to false, it will execute the condition in the input.nextInt() ==2 where the thread will keep waiting for the next input from the user because of the input.nextInt().
If you wish to get input from user only once, execute input.nextInt() only once and store it in a variable and run cases against it. Like,
// input from user
int selection = input.getInt();
if (selection == 1) {
System.out.println("the user entered 1");
}
else if (selection == 2) {
System.out.println("the user entered 2");
}
Please get input first then check it. (Don't get input in condition statement).
Your edited code is as follows:
Added one line (int selectedOption = input.nextInt())
edit condition statement (selectedOption == 1 and selectedOption == 2)
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please type 1 to say hi");
System.out.println("Please type 2 to say goodbye");
//Get input
int selectedOption = input.nextInt() ;
//Check
if (selectedOption == 1) {
System.out.println("You said hi");
} else if (selectedOption == 2) {
System.out.println("you said goodbye");
}
}

While loop NoSuchElementException integer input java

I'm having some trouble with a menu program I am writing for my java class. After one program is run, when the program goes to do a second loop it throws a NoSuchElementException on the line where it is supposed to take the user's input for the next program they want to run. I'm assuming it has something to do with the scanner getting messed up but I can't find the issue. Anyone have any ideas?
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
String pin;
int selection = 0;
boolean valid = false;
do {
System.out.print("Please enter the password: ");
pin = console.nextLine();
valid = checkPassword(pin);
} while (!valid);
while (selection != 4 && valid == true) {
System.out.printf("%nPlease select a number from the menu below %n1: Wage "
+ "Calculator 2: Tip Calculator 3: Grocery Discount 4: Exit %n");
selection = console.nextInt();
if (selection == 1) {
calc_wages();
} else if (selection == 2) {
calc_tip();
} else if (selection == 3) {
System.out.print("We haven't gotten this far yet");
} else if (selection == 4){
System.out.print("Thank you for using the program.");
break;
} else {
System.out.print("There is no option for what you entered. Try again");
}
selection = 0;
}
}//main
Your code so far is fine.
From what you're saying the problem starts after the user makes a selection.
In calc_wages() and/or calc_tip() it's possible that you use another Scanner object to get the user's input.
This is a source of problems.
Declare 1 Scanner object at the class level and use it throughout you code and close it only when it is no longer needed.

Last questions: Mastermind Java program

I have two questions regarding my code.
Why does is the output "Oops please enter a number between 1 and 6" when I enter a number between 1 and 6. When I try to be more specific and make an else if statement, nothing happens when I enter a number NOT between 1 and 6.
How do I restart my program? In my code, there is an if statement
when the user inputs "play again" My commented out line reads
Mastermind.main() to re run the program, but that didn't work.
Here is the code:
import java.util.Scanner;
public class Mastermind {
public static void main (String [] args) {
// boolean variable to signal when the game is over.
boolean done = false;
// Scanner object
Scanner scanner = new Scanner(System.in);
// sets the value to twelve outside the loop so it doesn't set back each time.
int guesses = 12;
System.out.println("Please enter a number between 1-6 to begin (or \"quit\") to exit.");
// while loop for the game
while (!done) {
//System.out.println("Please enter a number between 1-6 (or \"quit\") to exit the game:");
// user input
String input = scanner.nextLine();
int number = 0; //Just initialized to some number
// checks to see if the user wants to quit the game.
if (input.equalsIgnoreCase("quit")) {
System.out.println("Goodbye!");
done = true;
scanner.close();
}
else{
try{
//Trying to see if the input was a number
number = Integer.parseInt(input);
}
catch(Exception e){
//The input wasn't an integer, it's invalid the starts loop again.
System.out.println("Invalid input.");
continue;
}
}
// defines necessary int variables
int random1 = (int) (Math.random() * 7);
int random2 = (int) (Math.random() * 7);
int random3 = (int) (Math.random() * 7);
int random4 = (int) (Math.random() * 7);
// If the user doesn't and decides to play, it runs this code.
// checks to see if the user enters a number between 1-6
if (number >= 1 && number <= 6) {
if (number == random1) {
System.out.println("You guessed a correct number!");
guesses--;
System.out.println("guesses = " + guesses);
}
else if (number == random2) {
System.out.println("You guessed a correct number!");
guesses--;
System.out.println("guesses = " + guesses);
}
else if (number == random3) {
System.out.println("You guessed a correct number!");
guesses--;
System.out.println("guesses = " + guesses);
}
else if (number == random4) {
System.out.println("You guessed a correct number!");
guesses--;
System.out.println("guesses = " + guesses);
}
else {
System.out.println("Sorry that's not one of the numbers! Try again.");
guesses--;
System.out.println("guesses = " + guesses);
}
}
if (guesses == 0){
System.out.println("You've run out of guesses. To play again, enter \"play again\". Otherwise, enter or \"quit\")");
if (input.equalsIgnoreCase("play again")){
// how do I restart the program?
//Mastermind.main(); // QUESTION 2
}
else if (input.equalsIgnoreCase("quit")){
System.out.println("Goodbye!");
done = true;
scanner.close();
}
else {
System.out.println("Goodbye!");
done = true;
scanner.close();
}
}
else { //QUESTION 1
System.out.println("Oops! Please choose a number between 1 and 6");
}
}
}
}
You're printing that message every time through the loop whenever guesses == 0 evaluates to false. You probably just need to switch the order of the two blocks. Instead of this:
if (number >= 1 && number <= 6) {
...
}
if (guesses == 0) {
...
}
else { //QUESTION 1
System.out.println("Oops! Please choose a number between 1 and 6");
}
Use this:
if (number >= 1 && number <= 6) {
...
}
else { //QUESTION 1
System.out.println("Oops! Please choose a number between 1 and 6");
}
if (guesses == 0) {
...
}
Regarding restarting your program: if I'm reading the logic correctly, all you need to do is keep done set to false and reset guesses to 12.
Two other logic points. First, you should probably either continue or break after detecting that the user has entered "quit". Second, it seems like you are generating four new random integers for every user guess. I don't know if that's what you intended, but you might want to change the logic a bit. That might also affect the restart logic.

Categories

Resources