Syntax error on token println identifier expected after this token

I am getting Java Syntax error on token "callMe", Identifier expected after this token on below line of my program: c1.callMe(); class Class2 { Class1 c1 = new Class1(); c1.callMe()...

I am getting Java

Syntax error on token «callMe», Identifier expected after this token

on below line of my program:

c1.callMe();
class Class2 {
    Class1 c1 = new Class1();
    c1.callMe();
}

public class Class1 {
    public void callMe() {
        System.out.println("I am called!!");
    }
}

Dharman's user avatar

Dharman

29.3k21 gold badges80 silver badges131 bronze badges

asked Feb 25, 2015 at 14:01

Nitin's user avatar

0

Class1 c1 = new Class1();
c1.callMe();

Must be moved to a method, it can’t be at the class definition level, else it makes no sense (when would your code be executed??):

public class Class2 {
    public void doSomething() {
        Class1 c1 = new Class1();
        c1.callMe();
    }
}

answered Feb 25, 2015 at 14:07

jpo38's user avatar

jpo38jpo38

20.5k10 gold badges68 silver badges143 bronze badges

Here is how you write classes correctly in Java :)

class Class2 {
    Class1 c1 = new Class1();
    public void callMe(){
        c1.callMe();
     }
}
public class Class1 {
    public void callMe() {
        System.out.println("I am called!!");
    }
}

answered Feb 25, 2015 at 14:11

riflehawk's user avatar

Add Main method and re-arrange your code:

public class Class2 {
    public static void main(String[] args) {
        Class1 c1 = new Class1();
        c1.callMe();
    }
}
class Class1 {
    void callMe(){
    System.out.println("I am called!!");
   }
}

answered Oct 30, 2017 at 10:23

sabith.ak's user avatar

sabith.aksabith.ak

2204 silver badges11 bronze badges

Содержание

  1. — Syntax error on token «.», @ expected after this token
  2. 4 Answers 4
  3. Linked
  4. Related
  5. Hot Network Questions
  6. Subscribe to RSS
  7. Syntax error on token, Identifier expected
  8. Java Syntax error on token «>»,< expected after this token [closed]
  9. 5 Answers 5
  10. Related
  11. Hot Network Questions
  12. Как избавиться от синтаксической ошибки на токене «public» в основном классе?
  13. 1 ответ

— Syntax error on token «.», @ expected after this token

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:

These are the errors I receive on the same line as I have my

4 Answers 4

You can’t just have statements floating in the middle of classes in Java. You either need to put them in methods:

Or in static blocks:

You can’t have statements outside of initializer blocks or methods.

Try something like this:

You have a method call outside of a method which is not possible.

Correct code Looks like:

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.

Execute the above, the code will work now.

Linked

Hot Network Questions

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.1.14.43159

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Syntax error on token, Identifier expected

  • I’m new to Java/JSP so bare with me.

    I’m converting ASP code to Java, but I’m getting a syntax error (line 50 in the code), I’m not sure if I have declared the variable or string in the correct place.

    any suggestions would be great that you

  • All things are lawful, but not all things are profitable.

  • On line 46 you set objError = : But objError isn’t declared anywhere. (that I could see anyway. doesn’t necessarily mean it’s not there).

    Another issue I see is that you seem to declared the majority of your variables, methods and classes as final. For example, on line 45 you declare a ‘final String strNoCurrencyMessage = «»;’ What this does is declare an empty string that you cannot ever change. According to the JavaDocs you can only assign a value to a final variable once. Similar rules apply to methods and classes. Final methods can not be extended. All sorts of fun stuff.

    And while it’s not a big thing to me, but the Hungarian notation usage is a no-no.

    There are worse crimes than burning books. One of them is not reading them. Ray Bradbury

  • What is a no-no for me is doing all this in a JSP.

    I know you’re translating an ASP, but moving from one language/framework to another is not simply a case of changing a bit of syntax.
    A Java web app is supposed to have its processing side of things done via a Servlet, with a JSP as a tool for laying out the response.

  • @Dave, yeah I have set everything up in eclipse. I’ve created the servlet (I think) I have a folder called WebContent where my JSP files are. Then I have java resources where my DB connection is (have tested and can pull data from the DB). I have the connection in the JSP file as well, since a lot of examples I’ve seen have the Java/jsp code above the

    Am I wrong in doing it this way?

    @Robert, yeah that’s the only place I have the objError declared, Should I declare at the top where I’m declaring the other variables? I made everything «final» because I know that it should change in color, when I had it as just a «string» it was just plain text. Did this to see if I could get past errors and keep debugging.

    Источник

    Java Syntax error on token «>»,< expected after this token [closed]

    I am unsure about what is causing a Java syntax error on one of my methods. I have provided a comment on the place that has the error.

    5 Answers 5

    You should indent your code properly, it would help you find this type of errors. This code is not inside a method, which is not allowed in Java:

    You have a misplaced try catch that is out of any method. I am not sure what you meant there. Right after the getDateTime method.

    The code after the getDateTime() method should be inside a method block.currently its not inside any method. place it in appropriate method block.

    That > ends your getDateTime method, after which you have a stranded bunch of code (below) which needs to be encapsulated in a block somehow.

    What is this?? I beleive, that code that begins after your comment is out of any function. This is not possible. You should place it in any function.

    Also, you can use SimpleDateFormat to convert your date to String in specified format, e.g.:

    Hot Network Questions

    Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.1.14.43159

    By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

    Источник

    Как избавиться от синтаксической ошибки на токене «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:

    И позаботьтесь об именах, как указывали другие люди.

    Источник

    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.

    — Синтаксическая ошибка на токене «.», @ Ожидается после этого токена

    Мой Eclipse работал отлично пару дней назад до обновления Windows. Теперь я получаю сообщения об ошибках всякий раз, когда я пытаюсь сделать что-либо в Eclipse. Просто простая программа, так как это отображает кучу сообщений об ошибках:

    package lab6;
    
    public class Hellomsg {
        System.out.println("Hello.");
    
    }
    

    Это ошибки, которые я получаю в той же строке, что и у меня.

    "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"
    

    12 окт. 2016, в 15:52

    Поделиться

    Источник

    Вы не можете просто иметь инструкции, плавающие в середине классов на Java. Вам либо нужно поместить их в методы:

    package lab6;
    
    public class Hellomsg {
        public void myMethod() {
             System.out.println("Hello.");
        }
    }
    

    Или в static блоках:

    package lab6;
    
    public class Hellomsg {
        static {
             System.out.println("Hello.");
        }
    }
    

    Mureinik
    12 окт. 2016, в 11:26

    Поделиться

    У вас есть вызов метода за пределами метода, который невозможен.

    Правильный код Похож:

    public class Hellomsg {
      public static void main(String[] args) { 
        System.out.println("Hello.");
        }
    }
    

    Jens
    12 окт. 2016, в 11:28

    Поделиться

    У вас не может быть операторов вне блоков или методов инициализатора.

    Попробуйте что-то вроде этого:

    public class Hellomsg {
        {
            System.out.println("Hello.");
        }
    }
    

    или это

    public class Hellomsg {
        public void printMessage(){
            System.out.println("Hello.");
        }
    }
    

    Adam Arold
    12 окт. 2016, в 11:16

    Поделиться

    Ещё вопросы

    • 0SUM строк файла для итога и сделать запрос с итогом. PHP MSSQL
    • 1Следующая и предыдущая кнопки в массиве циклически перебирают массив слишком много раз при каждом нажатии (более одного раза)
    • 0получить максимальное значение из 1 таблицы на основе 3 таблиц
    • 0Примечание: ошибка преобразования массива в строку при преобразовании массива из php в javascript
    • 1Как нарисовать ограничивающую рамку на лучших матчах?
    • 0Угловые обещания в цикле карты
    • 0C ++ «врезается» в виртуальные функции базовых классов
    • 0AngularJS загружает json из файла в services.js
    • 0Ошибка зависимостей однорангового NPM
    • 0Не могу открыть сжатый файл
    • 1Более обратный формат даты возврата
    • 1PongWebSocketFrame не поддерживается Internet Explorer
    • 0STL установить найти производительность
    • 1Одновременное завершение дочерних процессов и выполнение обещаний
    • 1Нахождение термина в списке
    • 1Как получить вывод из класса после ввода всех значений
    • 1Как взять значение двух полей EditText и выполнить простую математику
    • 1Установите что-то на странице Freemarker с помощью AOP в SpringMVC
    • 1Изменить этот учебник для доступа к изображениям с SD-карты?
    • 1Проверка БД на пустые записи
    • 1Динамически добавлять фильтр сервлетов в приложение Grails
    • 0блокировка матрицы дает ошибку сегментации
    • 1Получать уведомления в ASP.net, если таблица из SQL была обновлена / изменена
    • 0Расширение Magento Checkout — перейти к следующему шагу в Checkout
    • 0Как изменить слайдер Duorable для использования обложки CSS3 background-size
    • 1нельзя использовать Tablelayout в виджете?
    • 0показ одной опции в один div после двух выбранных выпадающих
    • 0Использование мобильных служб Azure в приложении C ++
    • 0Конвертируйте встроенные теги изображений, например [image: 123: title: size], в теги HTML img
    • 1java.lang.NumberFormatException для входной строки «»
    • 0Запустить курсор через вектор, проверяя его границы
    • 1Получить разницу между списком в кадре данных Pandas и внешним списком
    • 0jQuery динамически вставляет новое поле ввода в keyup
    • 0Передача списка в качестве типа возврата c ++
    • 1df.where, основанный на разнице двух других DataFrames
    • 0Как изменить класс кнопки при смене слайда?
    • 0Преобразование поля даты и времени ничего не возвращает в запросе php / mssql
    • 1Растянуть списки, чтобы соответствовать размерам друг друга
    • 1Как добавить значения в новый столбец в панде dataframe?
    • 1Android — определение элементов любого макета на новом экране (действие)
    • 1Форматирование даты и времени панд в Bokeh HoverTool
    • 0PHP — ISS и неверные заголовки аутентификации
    • 1Проверьте соседнюю точку в 2d массиве с граничными условиями
    • 1Член PropertyChanged для INotifyPropertyChanged всегда равен нулю
    • 0Подходящий способ написать математическую формулу
    • 1ASP.NET Identity — проверка уникального адреса электронной почты пользователя в IdentityUser
    • 1Модуль ES2015 импортирует загрязняющее глобальное пространство имен
    • 0Javascript перенаправить на конкретный путь в URL
    • 0Конструкторы C ++, константы, наследование и предотвращение повторения
    • 0Уведомлять при завершении вызова JQuery Ajax

    Сообщество Overcoder

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

    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

    Понравилась статья? Поделить с друзьями:
  • Syntax error on token package import expected
  • Syntax error on token module interface expected
  • Syntax error on token invalid assignmentoperator
  • Syntax error on token expected syntax error on token expected after this token
  • Syntax error on token expected after this token java 1610612967