My Eclipse worked fine a couple of days ago before a Windows update. Now I get error messages whenever I’m trying to do anything in Eclipse. Just a simple program as this will display a bunch of error messages:
package lab6;
public class Hellomsg {
System.out.println("Hello.");
}
These are the errors I receive on the same line as I have my
"System.out.println":
"Multiple markers at this line
- Syntax error, insert ")" to complete MethodDeclaration
- Syntax error on token ".", @ expected after this token
- Syntax error, insert "Identifier (" to complete MethodHeaderName"
Mureinik
290k52 gold badges300 silver badges337 bronze badges
asked Oct 12, 2016 at 13:44
3
You can’t just have statements floating in the middle of classes in Java. You either need to put them in methods:
package lab6;
public class Hellomsg {
public void myMethod() {
System.out.println("Hello.");
}
}
Or in static
blocks:
package lab6;
public class Hellomsg {
static {
System.out.println("Hello.");
}
}
answered Oct 12, 2016 at 13:46
MureinikMureinik
290k52 gold badges300 silver badges337 bronze badges
3
You can’t have statements outside of initializer blocks or methods.
Try something like this:
public class Hellomsg {
{
System.out.println("Hello.");
}
}
or this
public class Hellomsg {
public void printMessage(){
System.out.println("Hello.");
}
}
answered Oct 12, 2016 at 13:45
Adam AroldAdam Arold
28.6k21 gold badges110 silver badges199 bronze badges
You have a method call outside of a method which is not possible.
Correct code Looks like:
public class Hellomsg {
public static void main(String[] args) {
System.out.println("Hello.");
}
}
answered Oct 12, 2016 at 13:46
JensJens
66.3k15 gold badges97 silver badges113 bronze badges
0
Just now I too faced the same issue, so I think I can answer this question.
You have to write the code inside the methods not on the class, class are generally used to do some initialization for the variables and writing methods.
So for your issue, I’m just adding your statement inside the main function.
package lab6;
public class Hellomsg {
public static void main(String args[]){
System.out.println("Hello.");
}
}
Execute the above, the code will work now.
answered Jan 3 at 8:59
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.
13 Years Ago
why do i get this syntax error at the line shown below
package org.temp2.cod1;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.io.*;
public class Code1 {
byte[] plaintext = new byte[32]; // <<<<<<<<<<<<<<<<<<<<<<<<<< syntax error
for (int i = 0; i < 32; i++) {
plaintext[i] = (byte) (i % 16);
}
byte[] key = new byte[16];
SecureRandom r = new SecureRandom();
r.nextBytes(key);
//byte[] key = ;//... secret sequence of bytes
//byte[] dataToSend = ; //...
Cipher c = Cipher.getInstance("AES");
SecretKeySpec k = new SecretKeySpec(key, "AES");
c.init(Cipher.ENCRYPT_MODE, k);
byte[] encryptedData = c.doFinal(plaintext);
}
}
-
5
Contributors -
4
Replies -
21K
Views -
2 Years
Discussion Span -
Latest Post
10 Years Ago
Latest Post
by LaughingOtter
Recommended Answers
The reason you get a syntax error in that code is that you have an extra bracket.
Try the following code:
1. package org.temp2.cod1; 2. import java.security.*; 3. import javax.crypto.*; 4. import javax.crypto.spec.*; 5. import java.io.*; 6. 7. public class Code1 { 8. 9. 10. byte[] …
Jump to Post
All 4 Replies
13 Years Ago
The reason you get a syntax error in that code is that you have an extra bracket.
Try the following code:
1.
package org.temp2.cod1;
2.
import java.security.*;
3.
import javax.crypto.*;
4.
import javax.crypto.spec.*;
5.
import java.io.*;
6.
7.
public class Code1 {
8.
9.
10.
byte[] plaintext = new byte[32]; // <<<<<<<<<<<<<<<<<<<<<<<<<< syntax error
11.
for (int i = 0; i < 32; i++) {
12.
plaintext[i] = (byte) (i % 16);
13.
}
14.
15.
16.
17.
byte[] key = new byte[16];
18.
SecureRandom r = new SecureRandom();
19.
r.nextBytes(key);
20.
21.
22.
//byte[] key = ;//... secret sequence of bytes
23.
//byte[] dataToSend = ; //...
24.
25.
Cipher c = Cipher.getInstance("AES");
26.
SecretKeySpec k = new SecretKeySpec(key, "AES");
27.
c.init(Cipher.ENCRYPT_MODE, k);
28.
byte[] encryptedData = c.doFinal(plaintext);
29.
}
masijade
1,351
Industrious Poster
Team Colleague
Featured Poster
13 Years Ago
Nope. The real problem is that that code needs to be inside a method. You can’t simply code loops and other actions as part of the class definition, but rather as method/constructor/block definitions inside the class.
13 Years Ago
Java class construct:
public class Foo {
private String datum;
private int datum2;
private void helperMethod() { ... }
public String exposedMethod(int param) { helperMethod(); }
public void main(String[] args) { //Special method invoked when java Foo is run; }
}
You need to study the Java syntax a little more carefully, I think.
10 Years Ago
I guess I do, since masijade’s and Cronless’ answers were the right ones.
Edited
10 Years Ago
by LaughingOtter
Reply to this topic
Be a part of the DaniWeb community
We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.
Содержание
- Как избавиться от синтаксической ошибки на токене «public» в основном классе?
- 1 ответ
- Как избавиться от синтаксической ошибки на токене «public» в основном классе?
Как избавиться от синтаксической ошибки на токене «public» в основном классе?
Я получаю синтаксическую ошибку в своем основном классе, когда вызываю конструктор из другого класса, который мне нужен для запуска основной программы. Эта программа ориентирована на наследование и соответствующий вызов конструкторов и аргументов. Это сообщение об ошибке, которое я получаю во время компиляции:
Это строка кода, вызывающая ошибку:
Остальной код можно найти ниже:
1 ответ
У вас здесь несколько ошибок. Я их исправил, программа запускается и выдаёт результат:
Имя: Эл
Адрес: 222BurdSt
. Телефонный номер: 2102223321
Идентификатор клиента: 46821
Потрачено: 2000
В списке рассылки: верно
Скидка: 10.0
Удалите конструктор PreferredCustomer из основного метода. Это не может быть частью метод, он является частью класса. Затем конструктор PreferredCustomer уже присутствует в классе PreferredCustomer.
Надеюсь, классы вашего клиента и PreferredCustomer находятся в отдельных файлах? Если нет, поместите их в отдельные файлы с именами customer.java и PreferredCustomer.java. В конструкторе класса PreferredCustomer удалите PreferredCustomer preferredCustomer из аргументов. Это излишне: зачем передавать одного клиента другому? Есть ли у клиентов какие-либо отношения друг с другом? Теперь количество аргументов будет совпадать при вызове конструктора (и не использовать строки «2000», «1000», где должны быть целые числа):
Далее в конструкторе PreferredCustomer используйте this вместо preferredCustomer здесь: this.discount = Discount; и выведите Discount в верхнем регистре, как в сигнатуре конструктора.
В результате код конструктора должен быть:
Основной метод в классе a6main:
И позаботьтесь об именах, как указывали другие люди.
Источник
Как избавиться от синтаксической ошибки на токене «public» в основном классе?
Я получаю синтаксическую ошибку в своем основном классе, когда вызываю конструктор из другого класса, который мне нужен для запуска основной программы. Эта программа ориентирована на наследование и соответствующий вызов конструкторов и аргументов. Это сообщение об ошибке, которое я получаю во время компиляции:
Это строка кода, вызывающая ошибку:
Остальной код можно найти ниже:
Весь ваш код в одном файле?
@azurefrog Да, они в одной папке
Ну, он не знает, как разбирать public PreferredCustomer() <> , потому что это был бы конструктор в классе PreferredCustomer . Вместо этого он случайным образом помещается в метод main() вашей программы в класс a6main . Просто удалите три строки, они ничего не делают. Возможно, это была ошибка копирования и вставки?
@ PetrJaneček Хорошо, я сделал это, теперь конструктор PreferredCustomer в main не определен . PreferredCustomer c = new PreferredCustomer («Al», «222BurdSt», «2102223321», «46821», «2000», true, «1000») ;
@AlwinBaybayan Привет, ваш конструктор PreferredCustomer принимает 9 аргументов. Вы вызываете этот конструктор с помощью new PreferredCustomer («Al», «222BurdSt», «2102223321», «46821», «2000», true, «1000»); Следовательно, либо вы исправляете свой общедоступный конструктор PreferredCustomer (xxxxx), чтобы он принимал только 7 аргументов, либо вы используете этот конструктор и передаете ему 9 значений . Также я вижу что-то странное в вашем общедоступном конструкторе PreferredCustomer () . Почему? вы проходите мимо, PreferredCustomer preferredCustomer) это к нему? 🙂
У вас здесь несколько ошибок. Я их исправил, программа запускается и выдаёт результат:
Name: Al
Address: 222BurdSt
Telephone number: 2102223321
Customer ID: 46821
Amount spent: 2000
On mailing list: true
Discount: 10.0
Удалите конструктор PreferredCustomer из основного метода. Это не может быть частью метод, он является частью класса. Затем конструктором PreferredCustomer является уже присутствует в классе PreferredCustomer.
Надеюсь, классы вашего клиента и PreferredCustomer находятся в отдельных файлах? Если нет, поместите их в отдельные файлы с именами customer.java и PreferredCustomer.java. В конструкторе класса PreferredCustomer удалите PreferredCustomer preferredCustomer из аргументов. Это излишне: зачем передавать одного клиента другому? Есть ли у клиентов какие-либо отношения друг с другом? Теперь количество аргументов будет совпадать при вызове конструктора (и не использовать строки «2000», «1000», где должны быть целые числа):
Далее в конструкторе PreferredCustomer используйте this вместо preferredCustomer здесь: this.discount = Discount; и выведите Discount в верхнем регистре, как в сигнатуре конструктора.
В результате код конструктора должен быть:
Основной метод в классе a6main:
И позаботьтесь об именах, как указывали другие люди.
Источник