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");
}
I am new around here but let’s get straight to the question:
When I was writing the following code for a class project calculator I came across a «token error». This is the full error message:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Syntax error on token "else", delete this token
at calculatorApplet.main(calculatorApplet.java:42)
I wrote this code:
import java.util.Scanner;
import javax.swing.JOptionPane;
public class calculatorApplet
{
Scanner sc = new Scanner(System.in);
public static void main(String[] args)
{
JOptionPane.showMessageDialog(null, "Welcome to the Calculator!");
String option = JOptionPane.showInputDialog(null, "Which calculator mode do you want?");
if (option.equals("Addition"))
{
Double add1 = Double.parseDouble(JOptionPane.showInputDialog(null, "Okay type the first number(s) of your addition problem."));
Double add2 = Double.parseDouble(JOptionPane.showInputDialog(null, "Now type the second number(s) of your addition problem."));
Double preAdd = add1+add2;
Double Add = preAdd;
JOptionPane.showMessageDialog(null, "The sum is " + Add + ".");
}
else
{
JOptionPane.showMessageDialog(null, "Huh?");
}
if (option.equals("Subtraction"))
{
Double sub1 = Double.parseDouble(JOptionPane.showInputDialog(null, "Okay type the first number(s) of your subtraction problem."));
Double sub2 = Double.parseDouble(JOptionPane.showInputDialog(null, "Now type the second number(s) of your subtraction problem."));
Double preSub = sub1-sub2;
Double Sub = preSub;
JOptionPane.showMessageDialog(null, "The difference is " + Sub + ".");
}
else
{
JOptionPane.showMessageDialog(null, "Huh?");
}
if (option.equals("Multiplication"));
{
Double mult1 = Double.parseDouble(JOptionPane.showInputDialog(null, "Okay type the first number(s) of your multiplication problem."));
Double mult2 = Double.parseDouble(JOptionPane.showInputDialog(null, "Now type the second number(s) of your multiplication problem."));
Double preMult = mult1*mult2;
Double Mult = preMult;
JOptionPane.showMessageDialog(null, "The product is " + Mult + ".");
}
else //Here is the error.
{
JOptionPane.showMessageDialog(null, "Huh?");
} //Here ends the error.
if (option.equals("Division"))
{
Double div1 = Double.parseDouble(JOptionPane.showInputDialog(null, "Okay type the first number(s) of your division problem."));
Double div2 = Double.parseDouble(JOptionPane.showInputDialog(null, "Now type the second number(s) of your division problem."));
Double preDiv = div1/div2;
Double Div = preDiv;
JOptionPane.showMessageDialog(null, "The quotient is " + Div + ".");
}
else
{
JOptionPane.showMessageDialog(null, "Huh?");
}
//End of if statements.
}
}
That’s the code and I commented the area where the token error is. Maybe the solution is right in my face. I want my code to be a calculator so if you guys can fix my code to not conflict with the math operations. Thanks and I appreciate any help.
sashacui 0 / 0 / 0 Регистрация: 27.07.2022 Сообщений: 16 |
||||
1 |
||||
27.07.2022, 18:53. Показов 852. Ответов 4 Метки нет (Все метки)
только начал изучение java. решил написать простейший конвертер валюты.
__________________
0 |
Folian 1702 / 1102 / 337 Регистрация: 25.01.2019 Сообщений: 2,890 |
||||
27.07.2022, 19:43 |
2 |
|||
Тут? У тебя блок if закончился, else не последовало, пошли другие инструкции.
Syntax error on token «else», delete this token. К чему этот else привязывать-то? Добавлено через 4 минуты
1 |
0 / 0 / 0 Регистрация: 27.07.2022 Сообщений: 16 |
|
27.07.2022, 19:47 [ТС] |
3 |
уже сам с этим разобрался — спасибо! но вот второй вопрос остается открытым — почему он не хочет никак воспринимать второе условие, которое не равно рублю? при любых условиях выдает рубль. Добавлено через 19 секунд
0 |
Нарушитель 14042 / 8230 / 2485 Регистрация: 21.10.2017 Сообщений: 19,708 |
|
27.07.2022, 20:09 |
4 |
0 |
Folian 1702 / 1102 / 337 Регистрация: 25.01.2019 Сообщений: 2,890 |
||||
27.07.2022, 20:17 |
5 |
|||
Решение
почему он не хочет
+ сюда почитай,
0 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
27.07.2022, 20:17 |
Помогаю со студенческими работами здесь
Ошибка There was an error parsing the query. [ Token line number = 1,Token line offset = 43,Token in error = записи ] using System; Ошибка при разборе запроса. [ Token line number = 1,Token line offset = 26,Token in error = Наименование ] Ошибка компиляции «parse error before `>>’ token» using namespace std; int… Ошибка syntax error before `(‘ token
Работа с файлами и ошибка Syntax error before `{‘ token говорит здесь ошибка: Искать еще темы с ответами Или воспользуйтесь поиском по форуму: 5 |
posted 11 years ago
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
I can’t seem to figure out why this is happening. Any tips at all will be very appreciated.
syntax error on token «else», delete this token.
I’ll post all the code if requested.
posted 11 years ago
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
Welcome to the Ranch!
After the word «else» there shouldn’t be any guard anymore — just the { or statement. That statement can be another «if», which is what I think you want:
Also, are you aware of method
equalsIgnoreCase
? You can use that to shorten your code:
Abel Gonza
Greenhorn
Posts: 3
posted 11 years ago
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
Rob Spoor wrote:Welcome to the Ranch!
After the word «else» there shouldn’t be any guard anymore — just the { or statement. That statement can be another «if», which is what I think you want:
Also, are you aware of methodequalsIgnoreCase
? You can use that to shorten your code:
What do you mean guard?
lowercase baba
Posts: 13086
posted 11 years ago
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
and else statement doesn’t have a condition on it. The idea is that on the IF and IF-ELSE lines, you have handled most conditions. the ELSE is for everything that wasn’t caught by the previous statements. the general flow should be:
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Abel Gonza
Greenhorn
Posts: 3
posted 11 years ago
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
got it thanks
Rob Spoor
Sheriff
Posts: 22716
posted 11 years ago
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
Abel Gonza wrote:What do you mean guard?
Sorry, that’s the term I once learned for it. I guess in Java it’s more often called the condition.
posted 11 years ago
-
2
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
I’m surprised nobody noticed this yet: you have a ; after your if-statements that should not be there.
This must be:
Rob Spoor
Sheriff
Posts: 22716
posted 11 years ago
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
Didn’t even notice these.
-
March 19th, 2013, 12:07 PM
#1
Junior Member
Syntax error on Token else?
So I wrote this program for a lab assignment and I tried to compile it and I got this syntax error — «1 error found: File: C:UsersDocumentsUnit6myName.java [line: 34] Error: Syntax error on token «else», ) expected» Could anyone help me out with this?
import java.util.*; public class Unit6MYNAME { public static final double SAVE_INTEREST = .04; public static final double NORM_CHECK_INTEREST = .015; public static final double MAX_CHECK_INTEREST = .03; public static final double CHECK_FEE = 25.00; public static final double SAVE_FEE = 10.00; public static final double CHECK_MINI_BAL = 25.00; public static final double SAVE_MINI_BAL = 500.00; public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); String accountNumber, accountType, continuation; double preAccountBalance, accountBalance, interest; while (continuation.equalsIgnoreCase("y")) { System.out.println("Please enter y to continue, "); System.out.println("otherwise enter n to quit."); continuation = keyboard.nextString; if (accountNumber.matches("\d{10}") else System.out.println("Invalid Entry"); System.exit(0); System.out.println("Please enter the letter c to enter information"); System.out.println(" for a checking account."); System.out.println("Otherwise, enter s for a savings account."); accountType = keyboard.nextLine; if (accountType.equalsIgnoreCase("c")) { System.out.println("Please enter the account balance."); preAccountBalance = keyboard.nextDouble; if (preAccountBalance < CHECK_MINI_BAL) { preAccountBalance = preAccountBalance - CHECK_FEE; interest = 0; } else interest = preAccountBalance * NORM_CHECK_INTEREST; accountBalance = preAccountBalance + interest; } else if (accountBalance >= 5500) interest = preAccountBalance * MAX_CHECK_INTEREST; accountBalance = preAccountBalance + interest; System.out.println("Account Number:" + accountNumber); System.out.println("Type of Account:" + accountType); System.out.printf("Previous Balance: .2f" , preAccountBalance); System.out.printf("Interest Earned: .2f" , interest); if (preAccountBalance < CHECK_MINI_BAL) System.out.printf("Service Fee: .2f" , CHECK_FEE); System.out.println("New Balance: .2f" , accountBalance); } if (accountType.equalsIgnoreCase("s")) { System.out.println("Please enter the account balance."); accountBalance = keyboard.nextDouble; if (preAccountBalance < SAVE_MINI_BAL) { preAccountBalance = accountBalance - SAVE_FEE; interest = 0; } else interest = preAccountBalance * SAVE_INTEREST; accountBalance = preAccountBalance + interest; System.out.println("Account Number:" + accountNumber); System.out.println("Type of Account:" + accountType); System.out.printf("Previous Balance: .2f" , preAccountBalance); System.out.printf("Interest Earned: .2f" , interest); if (preAccountBalance < SAVE_MINI_BAL) System.out.printf("Service Fee: .2f" , CHECK_FEE); System.out.println("New Balance: .2f" , accountBalance); } } }
-
Related threads:
-
March 19th, 2013, 12:34 PM
#2
Re: Syntax error on Token else?
I think this is the key part of the message. The compiler thinks there should be a ) at the indicated location.
Check the code for properly pairing of ( and ) and see why the compiler thinks there is a missing ).If you don’t understand my answer, don’t ignore it, ask a question.
-
March 19th, 2013, 12:40 PM
#3
Junior Member
Re: Syntax error on Token else?
I tried adding an additional parentheses, but then the error changed to saying that there is an error on the else token, delete this token.
-
March 19th, 2013, 12:45 PM
#4
Re: Syntax error on Token else?
The compiler often only finds one error at a time because that error hides the next error(s). A missing ) is a big deal and needs to be fixed so the rest of the tokens can be properly placed.
What is the new error on the else token? Please copy the full text of the error message and paste it here.
One problem I see with the code is there are some if statements that do NOT have {}s following them to enclose the statements controlled by the if. You should ALWAYS use {}s with if and else statements.
If you don’t understand my answer, don’t ignore it, ask a question.
-
March 19th, 2013, 01:15 PM
#5
Junior Member
Re: Syntax error on Token else?
1 error found:
File: C:UsersDocumentsMYNAME.java [line: 34]
Error: Syntax error on token «else», delete this token
-
March 19th, 2013, 01:18 PM
#6
Re: Syntax error on Token else?
The compiler thinks that the else is misplaced and should be removed.
Did you see the following?
One problem I see with the code is there are some if statements that do NOT have {}s following them to enclose the statements controlled by the if. You should ALWAYS use {}s with if and else statements.
If you don’t understand my answer, don’t ignore it, ask a question.
-
March 19th, 2013, 01:43 PM
#7
Junior Member
Re: Syntax error on Token else?
Don’t I need an else there?
And yes, I added more {}s.
-
March 19th, 2013, 01:45 PM
#8
Re: Syntax error on Token else?
Don’t I need an else there?
I don’t know. Are the compiler errors fixed now?
Post your current code if you have questions about it.
If you don’t understand my answer, don’t ignore it, ask a question.
-
March 19th, 2013, 02:20 PM
#9
Junior Member
Re: Syntax error on Token else?
Alright, I did a lot of fiddling with my code and got it to compile, but now it is shutting down prematurely. For some reason, my program seems to skip over several segments of code and immediately perform System.exit.
import java.util.*; public class Unit6ParkerTom { public static final double SAVE_INTEREST = .04; public static final double NORM_CHECK_INTEREST = .015; public static final double MAX_CHECK_INTEREST = .03; public static final double CHECK_FEE = 25.00; public static final double SAVE_FEE = 10.00; public static final double CHECK_MINI_BAL = 25.00; public static final double SAVE_MINI_BAL = 500.00; public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); String accountNumber = "0000000000"; String accountType = "g"; int continuation; double preAccountBalance =0, accountBalance = 0, interest = 0; System.out.println("Please enter a non zero integer to continue, "); System.out.println("otherwise enter 0 to quit."); continuation = keyboard.nextInt(); while (continuation != 0) { System.out.println("Please enter an account number."); accountNumber = keyboard.nextLine(); if (accountNumber.matches("\d{10}")) { System.out.println("Please enter the letter c to enter information"); System.out.println(" for a checking account."); System.out.println("Otherwise, enter s for a savings account."); accountType = keyboard.nextLine(); } else { System.out.println("Invalid Entry"); System.exit(0); } if (accountType.equalsIgnoreCase("c")) { System.out.println("Please enter the account balance."); preAccountBalance = keyboard.nextDouble(); if (preAccountBalance < CHECK_MINI_BAL) { preAccountBalance = preAccountBalance - CHECK_FEE; interest = 0; } else { interest = preAccountBalance * NORM_CHECK_INTEREST; accountBalance = preAccountBalance + interest; } } else if (accountBalance >= 5500) interest = preAccountBalance * MAX_CHECK_INTEREST; accountBalance = preAccountBalance + interest; System.out.println("Account Number:" + accountNumber); System.out.println("Type of Account:" + accountType); System.out.printf("Previous Balance: .2f" , preAccountBalance); System.out.printf("Interest Earned: .2f" , interest); if (preAccountBalance < CHECK_MINI_BAL) System.out.printf("Service Fee: .2f" , CHECK_FEE); System.out.printf("New Balance: .2f" , accountBalance); } if (accountType.equalsIgnoreCase("s")) { System.out.println("Please enter the account balance."); accountBalance = keyboard.nextDouble(); if (preAccountBalance < SAVE_MINI_BAL) { preAccountBalance = accountBalance - SAVE_FEE; interest = 0; } else interest = preAccountBalance * SAVE_INTEREST; accountBalance = preAccountBalance + interest; System.out.println("Account Number:" + accountNumber); System.out.println("Type of Account:" + accountType); System.out.printf("Previous Balance: .2f" , preAccountBalance); System.out.printf("Interest Earned: .2f" , interest); if (preAccountBalance < SAVE_MINI_BAL) System.out.printf("Service Fee: .2f" , CHECK_FEE); System.out.printf("New Balance: .2f" , accountBalance); System.out.println("Please enter a non zero integer to continue, "); System.out.println("otherwise enter 0 to quit."); continuation = keyboard.nextInt(); } } }
-
March 19th, 2013, 02:23 PM
#10
Re: Syntax error on Token else?
I still see lots of if and else statements that do NOT have the following statements enclosed in {}s.
If you don’t understand my answer, don’t ignore it, ask a question.
-
March 19th, 2013, 02:43 PM
#11
Junior Member
Re: Syntax error on Token else?
All curly brackets added. Program is still skipping to System.exit.
import java.util.*; public class Unit6ParkerTom { public static final double SAVE_INTEREST = .04; public static final double NORM_CHECK_INTEREST = .015; public static final double MAX_CHECK_INTEREST = .03; public static final double CHECK_FEE = 25.00; public static final double SAVE_FEE = 10.00; public static final double CHECK_MINI_BAL = 25.00; public static final double SAVE_MINI_BAL = 500.00; public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); String accountNumber = "0000000000"; String accountType = "g"; int continuation; double preAccountBalance =0, accountBalance = 0, interest = 0; System.out.println("Please enter a non zero integer to continue, "); System.out.println("otherwise enter 0 to quit."); continuation = keyboard.nextInt(); while (continuation != 0) { System.out.println("Please enter an account number."); accountNumber = keyboard.nextLine(); if (accountNumber.matches("\d{10}")) { System.out.println("Please enter the letter c to enter information"); System.out.println(" for a checking account."); System.out.println("Otherwise, enter s for a savings account."); accountType = keyboard.nextLine(); } else { System.out.println("Invalid Entry"); System.exit(0); } if (accountType.equalsIgnoreCase("c")) { System.out.println("Please enter the account balance."); preAccountBalance = keyboard.nextDouble(); if (preAccountBalance < CHECK_MINI_BAL) { preAccountBalance = preAccountBalance - CHECK_FEE; interest = 0; } else { interest = preAccountBalance * NORM_CHECK_INTEREST; accountBalance = preAccountBalance + interest; } } else if (accountBalance >= 5500) { interest = preAccountBalance * MAX_CHECK_INTEREST; accountBalance = preAccountBalance + interest; } System.out.println("Account Number:" + accountNumber); System.out.println("Type of Account:" + accountType); System.out.printf("Previous Balance: .2f" , preAccountBalance); System.out.printf("Interest Earned: .2f" , interest); if (preAccountBalance < CHECK_MINI_BAL) { System.out.printf("Service Fee: .2f" , CHECK_FEE); } System.out.printf("New Balance: .2f" , accountBalance); } if (accountType.equalsIgnoreCase("s")) { System.out.println("Please enter the account balance."); accountBalance = keyboard.nextDouble(); if (preAccountBalance < SAVE_MINI_BAL) { preAccountBalance = accountBalance - SAVE_FEE; interest = 0; } else { interest = preAccountBalance * SAVE_INTEREST; accountBalance = preAccountBalance + interest; } System.out.println("Account Number:" + accountNumber); System.out.println("Type of Account:" + accountType); System.out.printf("Previous Balance: .2f" , preAccountBalance); System.out.printf("Interest Earned: .2f" , interest); if (preAccountBalance < SAVE_MINI_BAL) { System.out.printf("Service Fee: .2f" , CHECK_FEE); } System.out.printf("New Balance: .2f" , accountBalance); System.out.println("Please enter a non zero integer to continue, "); System.out.println("otherwise enter 0 to quit."); continuation = keyboard.nextInt(); } } }
-
March 19th, 2013, 02:58 PM
#12
Re: Syntax error on Token else?
what value of input is causing the code to execute the System.exit()? Add the variable at the end of the println() so it is printed out.
Can you copy the full contents of the console window from when you execute the program that shows everything printed out by the program and everything entered by the user?
If you are using the Scanner methods nextInt() and nextLine() intermixed then you are probably having a problem with the endline char being left in the Scanner’s buffer . Add a call to nextLine() after a call to nextInt() to clear the endline char.
If you don’t understand my answer, don’t ignore it, ask a question.
-
March 19th, 2013, 03:09 PM
#13
Junior Member
Re: Syntax error on Token else?
It should end if a ten digit account number is not entered properly, however it executes System.exit() after the first prompt to continue. As for the second part, not sure what you are referencing.
Entering any non zero digit at the input box causes the program to execute System.exit and everything disappears from the console window.
> run Unit6MYNAME
Please enter a non zero integer to continue,
otherwise enter 0 to quit.
[DrJava Input Box]How do I do that?
-
March 19th, 2013, 03:16 PM
#14
Re: Syntax error on Token else?
Sorry, I don’t know anything about DrJava.
What prints out for the invalid input that causes the program to exit?
Invalid Entry ???????If you don’t understand my answer, don’t ignore it, ask a question.
-
The Following User Says Thank You to Norm For This Useful Post:
SgtGarrison (March 19th, 2013)
-
March 19th, 2013, 09:29 PM
#15
Junior Member
Re: Syntax error on Token else?
Originally Posted by Norm
Sorry, I don’t know anything about DrJava.
What prints out for the invalid input that causes the program to exit?
Invalid Entry ???????Yeah, Invalid Entry is supposed to print out if the account number is not ten digits and then System.exit is supposed to execute. However, it skips from the first prompt past the account number segment in the while loop all the way to the System.exit command without even displaying the invalid entry message.
Edit: I can see the invalid entry message now. :/
-
March 20th, 2013, 06:26 AM
#16
Re: Syntax error on Token else?
I can see the invalid entry message now
What prints out at the end of the invalid input messages that shows what causes the program to exit?
Invalid Entry ???????If you don’t understand my answer, don’t ignore it, ask a question.