Syntax error on token expected after this token java 1610612967

In this post, I will be sharing how to fix syntax error on token ",", { expected after this token error in Java. It is a compile-time error. As the

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:

[Solved] Syntax error on token ",", { expected after this token

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.

Member Avatar

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

Member Avatar

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.
      }

Member Avatar


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.

Member Avatar

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. :)

Member Avatar

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.

Я получаю синтаксическую ошибку в своем основном классе, когда вызываю конструктор из другого класса, который мне нужен для запуска основной программы. Эта программа ориентирована на наследование и соответствующий вызов конструкторов и аргументов. Это сообщение об ошибке, которое я получаю во время компиляции:

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

Anton8800

14 / 2 / 0

Регистрация: 29.09.2018

Сообщений: 246

1

12.12.2018, 00:12. Показов 5410. Ответов 12

Метки нет (Все метки)


Java
1
2
3
4
5
6
7
public class j2 {
    public static void main(String[] args) {
        int a=1;
        int b=2;
        a>3&&b>3 ? a+b:a;
    }
}

Exception in thread «main» java.lang.Error: Unresolved compilation problems:
Syntax error on token «>», invalid AssignmentOperator
The operator && is undefined for the argument type(s) int, boolean

at j2.main(j2.java:6)
Вопрос, откуда проблемы компиляции? Что я сделал не так?

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



109 / 89 / 25

Регистрация: 02.06.2018

Сообщений: 259

12.12.2018, 00:59

2

Потому что вы просто в «пустоту» пытаетесь вывести результат.
Напишите это в System.out.println(), например

Добавлено через 8 минут
Да, вам будет еще подсказка, что проверка вообще-то в данном случае в принципе не нужна, т.к. результат и так false, потому что вы явно задали значения a = 1 и b = 2



0



Эксперт Java

3636 / 2968 / 918

Регистрация: 05.07.2013

Сообщений: 14,220

12.12.2018, 08:59

3

в армию тебе надо, в армии хорошо, думать не требуется



0



Anton8800

14 / 2 / 0

Регистрация: 29.09.2018

Сообщений: 246

12.12.2018, 19:20

 [ТС]

4

Цитата
Сообщение от NiceJacket
Посмотреть сообщение

Потому что вы просто в «пустоту» пытаетесь вывести результат.
Напишите это в System.out.println(), например
Добавлено через 8 минут
Да, вам будет еще подсказка, что проверка вообще-то в данном случае в принципе не нужна, т.к. результат и так false, потому что вы явно задали значения a = 1 и b = 2

Java
1
2
3
4
5
Потому что вы просто в "пустоту" пытаетесь вывести результат.
Напишите это в System.out.println(), например
 
Добавлено через 8 минут
Да, вам будет еще подсказка, что проверка вообще-то в данном случае в принципе не нужна, т.к. результат и так false, потому что вы явно задали значения a = 1 и b = 2

Так тоже не работает.Но работает так

Java
1
2
3
4
5
6
7
8
9
10
public class j2 {
    public static void main(String[] args) {
        int a=1;
        int b=2;
        int x;
        x = a > 1&&b <1 ? a-1 : a+1;
        System.out.print(x);
        
    }
}

Почему?



0



Нарушитель

Эксперт PythonЭксперт Java

14042 / 8230 / 2485

Регистрация: 21.10.2017

Сообщений: 19,708

12.12.2018, 19:27

5

Цитата
Сообщение от Anton8800
Посмотреть сообщение

Почему?

Прежде чем пытаться лепить тернарный оператор, разберись как следует с if..else



0



14 / 2 / 0

Регистрация: 29.09.2018

Сообщений: 246

12.12.2018, 19:38

 [ТС]

6

Цитата
Сообщение от iSmokeJC
Посмотреть сообщение

Прежде чем пытаться лепить тернарный оператор, разберись как следует с if..else

Почему? И что конкретно подучить с if else там же вроде все просто. Или есть подводные камни?



0



Нарушитель

Эксперт PythonЭксперт Java

14042 / 8230 / 2485

Регистрация: 21.10.2017

Сообщений: 19,708

12.12.2018, 19:52

7

Лучший ответ Сообщение было отмечено Aviz__ как решение

Решение

Anton8800, что такое тернарный оператор?

Добавлено через 7 минут
Из той же самой википедии:

Безотносительно к определённому языку программирования тернарную операцию можно определить так:

логическое выражение ? выражение 1 : выражение 2
Алгоритм работы операции следующий:

1. Вычисляется логическое выражение.
2. Если логическое выражение истинно, то вычисляется значение выражения выражение 1, в противном случае — значение выражения выражение 2.
3. Вычисленное значение возвращается.

Обрати внимание на третий пункт.

Цитата
Сообщение от Anton8800
Посмотреть сообщение

a>3&&b>3 ? a+b:a;

Вот куда оно у тебя здесь возвращается?



1



14 / 2 / 0

Регистрация: 29.09.2018

Сообщений: 246

12.12.2018, 21:35

 [ТС]

8

Цитата
Сообщение от iSmokeJC
Посмотреть сообщение

Прежде чем пытаться лепить тернарный оператор, разберись как следует с if..else

Почему? И что конкретно подучить с if else там же вроде все просто. Или есть подводные камни?

Цитата
Сообщение от iSmokeJC
Посмотреть сообщение

Вот куда оно у тебя здесь возвращается?

Понял принял)



0



NiceJacket

109 / 89 / 25

Регистрация: 02.06.2018

Сообщений: 259

12.12.2018, 21:50

9

Цитата
Сообщение от Anton8800
Посмотреть сообщение

Так тоже не работает.
Почему?

честно говоря, для меня загадка, КАК именно не работает, основываясь на моём комменте?

Не по теме:

Не думал, что мой коммент не будет исчерпывающим

Добавлено через 8 минут

Цитата
Сообщение от Anton8800
Посмотреть сообщение

Почему? И что конкретно подучить с if else там же вроде все просто. Или есть подводные камни?

Если переписать ваш тернарный оператор на if else именно так, как написано у вас, то это будет выглядеть следующим образом:

Java
1
2
3
4
if (a>3 && b>3) 
    a+b;
else 
    a;

Что totally некорректно. Суть ясна?



1



14 / 2 / 0

Регистрация: 29.09.2018

Сообщений: 246

12.12.2018, 22:00

 [ТС]

10

Цитата
Сообщение от NiceJacket
Посмотреть сообщение

Суть ясна?

Да, спасибо)



0



109 / 89 / 25

Регистрация: 02.06.2018

Сообщений: 259

12.12.2018, 22:01

11

Цитата
Сообщение от Anton8800
Посмотреть сообщение

Да, спасибо)

Так вы поделитесь, вот вы прочитали, сделали, не получилось. Как именно вы сделали?
Заинтриговало же )



0



Anton8800

14 / 2 / 0

Регистрация: 29.09.2018

Сообщений: 246

12.12.2018, 22:16

 [ТС]

12

Цитата
Сообщение от NiceJacket
Посмотреть сообщение

Суть ясна?

Да, спасибо)

Цитата
Сообщение от NiceJacket
Посмотреть сообщение

Так вы поделитесь, вот вы прочитали, сделали, не получилось. Как именно вы сделали?
Заинтриговало же )

Сделал по дебильному

Java
1
2
3
4
int a=1;
        int b=2;
        int x;
        a>3&&b>3 ? System.out.print(a+b):System.out.print(a);

Просто не понимал, что вычисленное значение возвращается



0



NiceJacket

109 / 89 / 25

Регистрация: 02.06.2018

Сообщений: 259

12.12.2018, 22:19

13

Цитата
Сообщение от Anton8800
Посмотреть сообщение

Да, спасибо)
Сделал по дебильному

Java
1
2
3
4
int a=1;
        int b=2;
        int x;
        a>3&&b>3 ? System.out.print(a+b):System.out.print(a);

Просто не понимал, что вычисленное значение возвращается

понятно, конечно же, имелось в виду всю операцию поместить в System.out.println()



1



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

12.12.2018, 22:19

Помогаю со студенческими работами здесь

Ошибка «Fatal: Syntax error, «BEGIN» expected but «END» found»
Ввожу
unit Unit1;

{$mode objfpc}{$H+}

interface

uses
Classes, SysUtils, FileUtil,…

Ошибка «Fatal: Syntax error, «;» expected but «.» found»
звучит задание: создай программу, в которой можно преподнести введенное пользователем число к…

Unit1.pas(51,0) Fatal: Syntax error, «BEGIN» expected but «end of file» found
Вобщем, мне говорят что у меня ошибка в несуществующей строке.
Пишет мне вот это; unit1.pas(51,0)…

Ошибка: project1.lpr(1,1) Fatal: Syntax error, «BEGIN» expected but «end of file» found
project1.lpr(1,1) Fatal: Syntax error, &quot;BEGIN&quot; expected but &quot;end of file&quot; found
выдает эту ошибку…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

13

Синтаксическая ошибка в токене «int», VariableDeclarationId ожидается после этой ошибки токена R.java

Это ошибка, которая генерирует снова и снова. Я почистил свой проект.

 public static final class id {
        public static final int  =0x7f07005b;
        public static final int button1=0x7f070004;
        public static final int button2=0x7f070005;
        public static final int frameLayout1hardMatchup=0x7f070009;

В String.xml нет ошибки, вот мой String.xml.

<string name="hello">Hello World, MemoryCardsActivity!</string>
<string name="app_name">Princess  Memory Cards</string>
<string name="text_name">Congrates</string>
 <string name="text_help">Turn over pairs of matching cards, tap to flip two cards, as the match happens, they get removed from the screen.Try to get all cards match in minimum moves and proceed to next level</string>

А также нет никаких ошибок типа @+id. Что еще может быть причиной этого. Будем очень признательны за любой положительный ответ.. :(

2 ответы

Вам не хватает имени переменной

public static final int  = 0x7f07005b;

вместо

public static final int variableName = 0x7f07005b;

Создан 26 июля ’13, 13:07

Я произвел аналогичную ошибку, изменив один из моих XML-файлов макета. я изменил

android:id="@+id/image_frame"

в

android:id="@+id/ " 

Ошибка, которую я вижу с этим изменением,

public static final int  =0x7f080010; 
// Syntax error on token "int", VariableDeclaratorId expected after this token

Кажется, это то, что описывал @codeMagic.

Создан 28 июля ’13, 01:07

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками

android
android-xml
r.java-file

or задайте свой вопрос.

Понравилась статья? Поделить с друзьями:
  • Syntax error on token close identifier expected after this token
  • Syntax error on token class char expected
  • Syntax error non utf 8 code starting with
  • Syntax error non ascii character xd0 in file
  • Syntax error non ascii character python