I was working on a simple program and the same problem would keep coming up. It underlines the word close in input.close();
and I’d search through my program to try and find any errors but to no avail. Here’s my code:
import java.util.Scanner;
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String runProgram = "";
String itemDesc = "";
char cookieType = ' ';
char shirtType = ' ';
char itemChoice = ' ';
char sizeChoice = ' ';
double itemPrice = 0.0;
double totalSales = 0.0;
int totalSigned = 0;
int totalLemonade = 0;
int totalChocChip = 0;
int totalOatmeal = 0;
int totalRegShirt = 0;
int totalTrans = 0;
//Prime read of item selection
itemChoice = getMenuSelection(input);
while (itemChoice != 'Q')
{
if (itemChoice == 'L')
{
sizeChoice = getCupSize(input);
}
else if (itemChoice == 'C')
{
cookieType = getCookieType(input);
}
else
{
shirtType = getShirtType(input);
}
//displayResults(i
System.out.print("Great, your order is as follows: ");
System.out.print("Item Purchased " + itemDesc);
System.out.print("Item Price $" + itemPrice);
System.out.print(" ");
totalTrans = totalTrans + 1;
totalSales = totalSales + itemPrice;
itemChoice = getMenuSelection(input);
} //END WHILE
System.out.printf("n%-30s%30sn", "Total Number of Transactions", totalTrans);
System.out.printf("n%-30s%30sn", "ITEM DESCRIPTION", "QUANTITY SOLD");
System.out.printf("%-30s%23s%sn", "Lemonade", totalLemonade, " ounces");
System.out.printf("%-30s%30sn", "Chocolate Chip Cookies", totalChocChip);
System.out.printf("%-30s%30sn", "Oatmeal Cookies", totalOatmeal);
System.out.printf("%-30s%30sn", "Plain Shirts", totalRegShirt);
System.out.printf("%-30s%30sn", "Autographed Shirts", totalSigned);
System.out.printf("n%-30s%25s%.2fnn", "TOTAL SALES", "$", totalSales);
//displayResults(totalSales, totalSigned, totalLemonade, totalChocChip, totalOatmeal, totalRegShirt, totalTrans);
System.out.println("Goodbye and thank you for visiting Lemonade Express.");
}//END MAIN
/**
* Input the itemChoice. Accept only Q, L, C, or T
*
*@return One of four characters, shown above
*/
static char getMenuSelection(Scanner consoleInput)
{
Scanner input = new Scanner(System.in);
char itemChoice;
System.out.print("Please enter purchase selection: ");
System.out.print(" (L) Lemonade");
System.out.print(" (C) Cookie");
System.out.print(" (T) T-Shirt");
System.out.print(" (Q) Quit");
itemChoice = consoleInput.nextLine().charAt(0);
itemChoice = Character.toUpperCase(itemChoice);
//tests for valid entry
while (itemChoice != 'L' && itemChoice != 'C' && itemChoice != 'T' && itemChoice != 'Q')
{
System.out.print("Entered wrong item choice! ");
System.out.print("Enter item choice: ");
itemChoice = consoleInput.nextLine().charAt(0);
itemChoice = Character.toUpperCase(itemChoice);
}
return itemChoice;
} //END getMenuSelection
/**
* Input and return Cup Size
* @param consoleInput object to recieve read from console
* @return for one lemonade sale
*/
static char getCupSize(Scanner consoleInput)
{
Scanner input = new Scanner(System.in);
char sizeChoice;
System.out.print("What size lemonade would you prefer:");
System.out.print(" (S) 12 ounce");
System.out.print(" (L) 16 ounce");
sizeChoice = consoleInput.nextLine().charAt(0);
sizeChoice = Character.toUpperCase(sizeChoice);
//tests for valid entry
while (sizeChoice != 'S' && sizeChoice != 'L')
{
System.out.print("Entered wrong item choice! ");
System.out.print("Enter size choice: ");
sizeChoice = input.nextLine().charAt(0);
sizeChoice = Character.toUpperCase(sizeChoice);
}
String itemDesc;
double itemPrice;
int totalLemonade;
if (sizeChoice == 'S')
{
itemDesc = "12 ounce lemonade";
itemPrice = 1.50;
totalLemonade = totalLemonade + 12;
}
else
{
itemDesc = "16 ounce lemonade";
itemPrice = 2.00;
totalLemonade = totalLemonade + 16;
}
return sizeChoice;
}
/**
* Input and return Cookie Type
* @param getCookieType to find price for cookies
* @return for one cookie sale
*/
static char getCookieType(Scanner consoleInput)
{
Scanner input = new Scanner(System.in);
char cookieType;
System.out.print("Which kind of cookie would you prefer?");
System.out.print(" (C) chocolate chip");
System.out.print(" (O) oatmeal");
cookieType = consoleInput.nextLine().charAt(0);
cookieType = Character.toUpperCase(cookieType);
double itemPrice = .75;
while (cookieType != 'S' && cookieType != 'L')
{
System.out.print("Entered wrong item choice! ");
System.out.print("Enter cookie choice: ");
cookieType = input.nextLine().charAt(0);
cookieType = Character.toUpperCase(cookieType);
}
String itemDesc;
if (cookieType == 'S')
{
itemDesc = "Chocolate Chip Cookie";
int totalChocChip = totalChocChip + 1;
}
else
{
itemDesc = "Oatmeal Cookie";
int totalOatmeal = totalOatmeal + 1;
}
return cookieType;
}
/**
* Input and return Shirt Type
* @param getShirtType to find price for shirts
* @return for one shirt sale
*/
static char getShirtType(Scanner consoleInput)
{
Scanner input = new Scanner(System.in);
char shirtType;
System.out.print("Which kind of shirt would you prefer?");
System.out.print(" (A) autographed t-shirt");
System.out.print(" (N) normal t-shirt");
shirtType = input.nextLine().charAt(0);
shirtType = Character.toUpperCase(shirtType);
while (shirtType != 'A' && shirtType != 'N')
{
System.out.printf("n%s", "Entered wrong item choice! ");
System.out.print("Enter shirt choice: ");
shirtType = input.nextLine().charAt(0);
shirtType = Character.toUpperCase(shirtType);
}
double itemPrice;
String itemDesc;
if (shirtType == 'Y')
{
itemPrice = 15.00;
itemDesc = "Autographed T-shirt";
int totalSigned = totalSigned + 1;
}
else
{
itemPrice = 8.00;
itemDesc = "Regular T-Shirt";
int totalRegShirt = totalRegShirt + 1;
}
return shirtType;
}
input.close();
}
Thanks for the help in advance!
In this post, I will be sharing how to fix the syntax error on token «,», { expected after this token error in Java. It is a compile-time error. As the name suggests, this error is syntax-based and mostly faced by Java beginners.
Read Also: [Fixed] Unclosed String Literal Error
As always, first, we will produce the syntax error on token «,», { expected after this token error before moving on to the solution. Let’s dive deep into the topic:
Note: This compiler error can be produced only in the Eclipse IDE.
[Fixed] Syntax error on token «,», { expected after this token
1. Producing the error
We can easily produce this error in the Eclipse IDE by writing code or executable statements outside the method as shown below:
import java.util.*; public class SyntaxError { String str = "Alive is Awesome"; Random rand = new Random(); for (int i = 0; i < 3; i++) { System.out.println(str); } }
Output:
2. Explanation:
The cause of this error is due to the code or executable statements not present inside the method. You can not directly write the code in a class in Java. Only variables declaration/initialization are allowed outside the method.
3. Solution:
The above compilation error can be resolved by moving the code inside a method. In simple words, you can’t call a class you have to call a method that is declared inside a class. We can easily avoid this error by using one of the solutions given below:
Solution 1: Using public static void main() method
We have moved the code inside the public static void main() method as shown below in the code:
import java.util.*; public class SyntaxError { public static void main(String args[]) { String str = "Alive is Awesome"; Random rand = new Random(); for (int i = 0; i < 3; i++){ System.out.println(str); } } }
Solution 2: Using any method
We can move the executable code inside any method, for example, the printString() method as shown below in the code:
import java.util.*; public class SyntaxError { public static void printString() { String str = "Alive is Awesome"; Random rand = new Random(); for (int i = 0; i < 3; i++){ System.out.println(str); } } public static void main(String args[]) { printString(); } }
Solution 3: Using block
Any executable code inside {} without any method name is called a block. We can move the executable code inside the block also as shown below:
import java.util.*; public class SyntaxError { // Using block { String str = "Alive is Awesome"; Random rand = new Random(); for (int i = 0; i < 3; i++){ System.out.println(str); } } public static void main(String args[]) { new SyntaxError(); } }
That’s all for today. Please mention in the comments in case you have any questions related to the syntax error on token «,», { expected after this token error in Java.
posted 10 years ago
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
I have this error after watching exactly someone was doing on YT in a tutorial. His worked but mine didn’t…
Heres my code
Please help!
I’ve only been at Java for a few hours, and I really want to press on!
posted 10 years ago
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
Welcome to the Ranch!
I’ve added code tags and some better indentation to your post. Especially that better indentation should show you that statement is not where you want it to be — inside the logoTimer anonymous class definition.
Daniel Tonks
Greenhorn
Posts: 6
posted 10 years ago
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
Ah! Thank you!
I was doing this in eclipse and the indenting seems a little glitchy for me. I see my error now. Thanks
Rob Spoor
Sheriff
Posts: 22716
posted 10 years ago
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
You’re welcome.
posted 9 years ago
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
Rob Spoor wrote:Welcome to the Ranch!
I’ve added code tags and some better indentation to your post. Especially that better indentation should show you that statement is not where you want it to be — inside the logoTimer anonymous class definition.
Im having the same problem can you post the updated code?
Bartender
Posts: 3323
posted 9 years ago
-
1
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
Welcome to the Ranch.
Why don’t you post your code and we will help you find the problem.
Jeff Mezzanotte
Greenhorn
Posts: 3
posted 9 years ago
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
Tony Docherty wrote:Welcome to the Ranch.
Why don’t you post your code and we will help you find the problem.
Tony Docherty
Bartender
Posts: 3323
posted 9 years ago
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
To fix the code do as Rob suggested to the original poster.
If it’s not immediately obvious, then starting at the line where you create a new Thread object, count +1 for each opening brace and -1 for each closing brace. When you are back to 0 you have finished the local class definition and after the final closing brace is where the errant line goes. If your count goes to -1 rather than going positive then you are starting the block with a closing brace instead of an opening brace.
Jeff Mezzanotte
Greenhorn
Posts: 3
posted 9 years ago
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
Tony Docherty wrote:To fix the code do as Rob suggested to the original poster.
If it’s not immediately obvious, then starting at the line where you create a new Thread object, count +1 for each opening brace and -1 for each closing brace. When you are back to 0 you have finished the local class definition and after the final closing brace is where the errant line goes. If your count goes to -1 rather than going positive then you are starting the block with a closing brace instead of an opening brace.
looks like it was the brace on line 18 thanks
Marshal
Posts: 77299
posted 9 years ago
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
It is deceptively easy to suffer that sort of error, if you write your code forwards. Set up automatic indentation on your text editor and life will be a lot easier. Then you need to learn to write code backwards (at least in part). Writing backwards makes it much easier to ensure you have matched {}, and correct indentation allows you always to see how many {} you have got.
posted 9 years ago
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
Jeff and Daniel,
Try removing the semicolon after the closing braces which is present before logoTimer.start();, the place where you get your error
And can you tell me why have you used }; after the error line?
«Any fool can write code that a computer can understand. Good programmers write code that humans can understand.»
— Martin Fowler
Я получаю синтаксическую ошибку в своем основном классе, когда вызываю конструктор из другого класса, который мне нужен для запуска основной программы. Эта программа ориентирована на наследование и соответствующий вызов конструкторов и аргументов. Это сообщение об ошибке, которое я получаю во время компиляции:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Syntax error on token "public", record expected after this token
at a6main.main(a6main.java:7)
Это строка кода, вызывающая ошибку:
PreferredCustomer c = new PreferredCustomer("Al", "222BurdSt", "2102223321", "46821",
"2000", true, "1000");
Остальной код можно найти ниже:
class person {
String Name;
String Address;
String Telephone;
person (String Name, String Address, String Telephone) {
this.Name = Name;
this.Address = Address;
this.Telephone = Telephone;
}
String getName() {
return Name;
}
String getAddress() {
return Address;
}
String getTelephone() {
return Telephone;
}
void setName(String Name) {
this.Name = Name;
}
void setAddress(String Address) {
this.Address = Address;
}
void setTelephone(String Telephone) {
this.Telephone = Telephone;
}
}
public class customer extends person {
String number;
boolean OnMailingList;
//constructor and getters and setters
customer (String Name, String Address, String Telephone, String number, boolean OnMailingList) {
//inherit persons information
super(Name, Address, Telephone);
this.number = number;
this.OnMailingList = OnMailingList;
}
String getnumber() {
return number;
}
void setnumber(String number) {
this.number = number;
}
boolean OnMailingList () {
return OnMailingList;
}
void setOnMailingList(boolean OnMailingList) {
this.OnMailingList = OnMailingList;
}
}
public class PreferredCustomer extends customer {
private int purchase;
double discount;
/**public constructor so its accessible to main
* else ifs for certain percentage of discounts
* getters and setters for purchase and discount
* super to inherit other features from other classes */
public int getpurchase() {
return purchase;
}
public double getdiscount () {
return this.discount;
}
public void setPurchase(int purchase) {
this.purchase = purchase;
}
public PreferredCustomer(String Name, String Address, String Telephone, String number, int pur,
boolean OnMailingList, double Discount, PreferredCustomer preferredCustomer) {
super(Name, Address, Telephone, number, OnMailingList);
this.purchase = pur;
preferredCustomer.discount = discount;
if (this.purchase>= 2000) {
this.discount = 10;
} else if (this.purchase>= 1500) {
this.discount = 7;
} else if (this.purchase>= 1000) {
this.discount = 6;
} else if (this.purchase >= 500) {
this.discount = 5;
}
}
}
public class a6main {
public static void main (String [] args) {
public PreferredCustomer() {
}
PreferredCustomer c = new PreferredCustomer("Al", "222BurdSt", "2102223321", "46821","2000", true, "1000");
System.out.println("Name: " + c.getName());
System.out.println("Address: " + c.getAddress());
System.out.println("Telephone number: " + c.getTelephone());
System.out.println("Customer ID: " + c.getnumber());
System.out.println("Amount spent: " + c.getpurchase());
System.out.println("On mailing list: " + c.OnMailingList());
System.out.println("Discount: " + c.getdiscount());
}
}
1 ответ
Лучший ответ
У вас здесь несколько ошибок. Я их исправил, программа запускается и выдаёт результат:
Имя: Эл
Адрес: 222BurdSt
.
Телефонный номер: 2102223321
Идентификатор клиента: 46821
Потрачено: 2000
В списке рассылки: верно
Скидка: 10.0
Удалите конструктор PreferredCustomer из основного метода. Это не может быть частью метод, он является частью класса. Затем конструктор PreferredCustomer уже присутствует в классе PreferredCustomer.
Надеюсь, классы вашего клиента и PreferredCustomer находятся в отдельных файлах? Если нет, поместите их в отдельные файлы с именами customer.java и PreferredCustomer.java. В конструкторе класса PreferredCustomer
удалите PreferredCustomer preferredCustomer
из аргументов. Это излишне: зачем передавать одного клиента другому? Есть ли у клиентов какие-либо отношения друг с другом? Теперь количество аргументов будет совпадать при вызове конструктора (и не использовать строки «2000», «1000», где должны быть целые числа):
PreferredCustomer c = new PreferredCustomer("Al", "222BurdSt", "2102223321", "46821",
2000, true, 1000);
Далее в конструкторе PreferredCustomer используйте this
вместо preferredCustomer
здесь: this.discount = Discount;
и выведите Discount
в верхнем регистре, как в сигнатуре конструктора.
В результате код конструктора должен быть:
public PreferredCustomer(String Name, String Address, String Telephone, String number, int pur, boolean OnMailingList, double Discount) {
super(Name, Address, Telephone, number, OnMailingList);
this.purchase = pur;
this.discount = Discount;
if (this.purchase>= 2000) {
this.discount = 10;
} else if (this.purchase>= 1500) {
this.discount = 7;
} else if (this.purchase>= 1000) {
this.discount = 6;
} else if (this.purchase >= 500) {
this.discount = 5;
}
}
Основной метод в классе a6main:
public static void main (String [] args) {
PreferredCustomer c = new PreferredCustomer("Al", "222BurdSt", "2102223321", "46821", 2000, true, 1000);
System.out.println("Name: " + c.getName());
System.out.println("Address: " + c.getAddress());
System.out.println("Telephone number: " + c.getTelephone());
System.out.println("Customer ID: " + c.getnumber());
System.out.println("Amount spent: " + c.getpurchase());
System.out.println("On mailing list: " + c.OnMailingList());
System.out.println("Discount: " + c.getdiscount());
}
И позаботьтесь об именах, как указывали другие люди.
1
HoRn
6 Апр 2021 в 08:01