Syntax error insert variabledeclarators to complete localvariabledeclaration

public class Water { private Graphic graphic; private float speed; private float distanceTraveled; public Water(float x, float y, float direction) { speed = 0.7f; ...
public class Water {
    private Graphic graphic;
    private float speed;
    private float distanceTraveled;

    public Water(float x, float y, float direction) 
    {
        speed = 0.7f;

        graphic = new Graphic();
        graphic.setType("WATER");   

        graphic.setX(x);
        graphic.setY(y);

        direction = graphic.getDirection(); //direction from Hero as water is fired
    }
    public Water update(int time) 
    {
        graphic.draw();
        return Water.this;
        distanceTraveled; // this is where the error occured...
    }
}

When I tried to call distanceTraveled, I am getting the error as:

Syntax error, insert «VariableDeclarators» to complete LocalVariableDeclaration

Miki's user avatar

Miki

40.4k13 gold badges121 silver badges202 bronze badges

asked Mar 16, 2016 at 16:18

Mike's user avatar

4

To make the Syntax error disappear and to assign a value to distanceTraveledmodify the method public Water update(int time) as follows:

public Water update(int time) {
    graphic.draw();
    distanceTraveled = 1; // assign a value before returning
    return Water.this;
}

Maybe you should read a bit about Java and doing some tutorials, because this is very basic stuff (at least if I’m not getting you wrong).

answered Mar 16, 2016 at 16:37

mnille's user avatar

mnillemnille

1,3304 gold badges16 silver badges20 bronze badges

2

You have to either print distanceTraveled or do any operation like increment. Don’t write only variable.

marc_s's user avatar

marc_s

722k173 gold badges1320 silver badges1443 bronze badges

answered Jun 4, 2022 at 7:55

rohit mendre's user avatar

1

CORRECT: <%! …code… %> (JSP DECLARATION)

WRONG : <% …code… %> (JSP SCRIPLET)

WRONG : <%= …code… %> (JSP EXPRESSION)

Example:

<!-- ------------------------------------- -->
<html><body><h1> 
    <%!
    public static String fn(){

        return( "[CORRECT:USE ! MARK]");
    }; 
    %>

    <%= fn() %>
</h1></body></html>
<!-- ------------------------------------- -->

Using «<%» or «<%=» instead of «<%!» will get error:

org.apache.jasper.JasperException: Unable to compile class for JSP:

An error occurred at line: [3] in the jsp file: [/index.jsp] Syntax
error, insert «VariableDeclarators» to complete
LocalVariableDeclaration

answered Jul 9, 2018 at 0:44

KANJICODER's user avatar

KANJICODERKANJICODER

3,47729 silver badges16 bronze badges


posted 4 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

My code is above(not all of it) but I am getting a » Syntax error, insert «VariableDeclarators» to complete LocalVariableDeclaration» error for PhoneList[];

Any help would be appreciated!

I am really slow when it comes to Java and I’m just trying to finish up some homework.  Not looking for someone to write my code, just some guidance.  Thanks!


posted 4 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

This isn’t correct. It looks like you are declaring an array of type «PhoneList» but you haven’t specified a variable name. Given the code above it I’m guessing what you wanted was:

Which is an array of type «Phone» with a variable name of «list».

Please note  that while the Java compiler accepts the following syntax for historical reasons

The Java convention is to move the square brackets up against the type, as in:

Sarah Butler

Greenhorn

Posts: 3


posted 4 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

I see that error, so how do I fix these?  I get a new error now…I’m a mathematics major ugh!!

Sarah Butler

Greenhorn

Posts: 3


posted 4 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

I forgot to tell you my error…it’s on line 12,24 and 32.  

Carey Brown

Saloon Keeper

Posts: 9865

Eclipse IDE
Firefox Browser
MySQL Database
VI Editor
Java
Windows


posted 4 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Creates a new array of Phone of the specified size.

Carey Brown

Saloon Keeper

Posts: 9865

Eclipse IDE
Firefox Browser
MySQL Database
VI Editor
Java
Windows


posted 4 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Constructs a single instance of a Phone object with the specified parameters. Assigns the object reference to the i’th reference as found in the array named ‘list’.

Marshal

Posts: 77299


posted 4 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Welcome to the Ranch

Sarah Butler wrote:. . . . . .

That isn’t a syntax error, but only ever use n or r if somebody says they want the LF or CR characters. If you are using prinf, use %n instead. There is more about printf in the Java™ Tutorials, and if I have given you the right formatting link (there are two), it will tell you to avoid n and r.

Rancher

Posts: 515

Notepad
Java


posted 4 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Here are some fixes required in the code as you have posted. All of these are within the

getInput()

method:

(1)

//get input

list=new Phone list[get.nextInt()]; //define phone array size

CHANGED TO:

list=new Phone [get.nextInt()];

This is a syntax error during compilation. Defining an array, an example:

(2)

get.nextLine();

This code is to be removed, it is not required.

(3)

list[i]=new Phone list(name,area,exchange,number);

CHANGED TO:

list[i]=new Phone (name,area,exchange,number);

The reason is same as that of the one in the point (1).

(4)

list[i]=new Phone list(name,area,exchange,number,extension);

CHANGED TO:

list[i]=new BusinessPhone (name,area,exchange,number,extension);

The reason is same as that of the one in the point (1).

The second reason is that you are looking for the

extension

to be printed from a

BusinessPhone

.

(5)

The variable

type

wasn’t defined. And, this is a syntax error during compilation

NOTE: The above changes are valid with the assumption that the «input.txt» file has data in the following format. And, it runs fine to give the expected output.

3

person name 800 209 9024

person name 800 209 9025

business name 800 209 9098 12

Hope this is helpful to you.

SCJP 5, OCPJP 7, 8, SCJD 5, SCWCD 4, SCBCD 5, SCJWS 4, IBM OOAD 833 & 834, MongoDB Developer

2 ответа

Чтобы исчезнуть ошибка синтаксиса и присвоить значение distanceTraveled измените метод public Water update(int time) следующим образом:

public Water update(int time) {
    graphic.draw();
    distanceTraveled = 1; // assign a value before returning
    return Water.this;
}

Может быть, вам стоит немного почитать о Java и делать некоторые уроки, потому что это очень простой материал (по крайней мере, если я не ошибаюсь).

mnille
16 март 2016, в 15:24

Поделиться

CORRECT: <%! … код…%> (JSP DECLARATION)

WRONG: <%… code…%> (JSP SCRIPLET)

WRONG: <% =… code…%> (JSP EXPRESSION)

Пример:

<!-- ------------------------------------- -->
<html><body><h1> 
    <%!
    public static String fn(){

        return( "[CORRECT:USE ! MARK]");
    }; 
    %>

    <%= fn() %>
</h1></body></html>
<!-- ------------------------------------- -->

Используя «<%» или «<% =» вместо «<%!» получится ошибка:

org.apache.jasper.JasperException: невозможно компилировать класс для JSP:

Произошла ошибка в строке: [3] в файле jsp: [/index.jsp] Ошибка синтаксиса, вставьте «VariableDeclarators» для завершения LocalVariableDeclaration

J.M.I. MADISON
08 июль 2018, в 21:52

Поделиться

Ещё вопросы

  • 0SQL-запрос в цикле накапливает каждый цикл
  • 0Проблема с добавлением двух полиномов, построенных как связанный список c ++
  • 0HTML / CSS проблема с элементами, движущимися при разных разрешениях экрана
  • 1Время, прошедшее с момента отключения питания от сети
  • 0c ++ как объявить функцию, возвращающую вектор объектов
  • 1Проверка содержимого EditText, как только пользователь вводит данные
  • 0Функция маршрутизации и перенаправления ZF2 в контроллере
  • 0Использовать массивы на нескольких страницах php?
  • 0угловое повторение скрывает стиль div
  • 1Что означает параметр `int` в` map` Python 3?
  • 1Расположение провайдеров в Android?
  • 1встроенная реализация UDP для Android
  • 0WriteFIle зависает
  • 1Я не могу изменить цвет угла ScrollPane в JavaFX
  • 0положить несколько значений в json_encode
  • 0Как передать переменную в контроллер из директивы, которая находится за пределами контроллера?
  • 0Я получаю «неопределенный тип» в моей реализации cvSnakeImage ()
  • 0Угловая директива множественных входов одной модели
  • 0Невозможно скрыть вложенный список, который находится внутри div
  • 1MVC 5 Не удается неявно преобразовать тип ‘System.Linq.IQueryable в bool?
  • 1Пользовательский Сериализатор Джексона для определенного типа в определенном классе
  • 1Как найти имя выходного узла данного файла .ckpt.meta в тензорном потоке
  • 0Yii renderPartial с помощью внешнего JavaScript
  • 0Получение Uncaught TypeError: Невозможно прочитать свойство ‘push’ из неопределенного
  • 1Сбой HTTPS при использовании модуля «запросы» в Google App Engine
  • 0Angular UI Router не загружает шаблоны или контроллеры при изменении URL
  • 1pyinstaller не загружает никаких зависимостей
  • 1Получить изображения из медиа библиотеки
  • 0Пытаясь получить 4 колонны с кладкой, что не так?
  • 1Как добавить картинку в html-страницу в приложении Spring
  • 1Каков наилучший способ отобразить данные таблицы соединений в сущности Java?
  • 0Поместите изображение в определенную позицию большего изображения
  • 0AngularJS и SparkJava. Никогда не входите в метод .success () и не видите ответ сервера
  • 0скрыть элементы в iframe от родителя, если у iframe нет идентификатора
  • 1Вытащить сообщение из обработчика Android
  • 1Использование модуля opencv stitcher для сшивания размытых изображений
  • 1Как выполнить логическую операцию и логическое индексирование с помощью VIPS в Python?
  • 0php loop математические вопросы
  • 1Настройки магазина приложений Android
  • 1RSA-шифрование с использованием блоков
  • 1Как вычесть числа из строк, чтобы получить разницу во времени
  • 0Как получить значение отформатированного значения ячейки строки в jqgrid
  • 0Cakephp генерирует строчные URL с именами контроллеров в верхнем регистре
  • 1Использование linq для поиска дубликатов в списке <Vector2>
  • 0C ++ стандартная альтернатива itoa () для преобразования int в base 10 char *
  • 0Получение номера ручки открытой на поток
  • 0Массивы не публикуются в php
  • 0Как связать страницу между входом, регистрацией и профилем в php
  • 0c ++ возвращает одно значение из связанного списка
  • 1Есть ли контактный номер или адрес электронной почты для выбора / выбора конкретного контакта?

To make the Syntax error disappear and to assign a value to distanceTraveledmodify the method public Water update(int time) as follows:

public Water update(int time) {
    graphic.draw();
    distanceTraveled = 1; // assign a value before returning
    return Water.this;
}

Maybe you should read a bit about Java and doing some tutorials, because this is very basic stuff (at least if I’m not getting you wrong).

Comments

  • public class Water {
        private Graphic graphic;
        private float speed;
        private float distanceTraveled;
    
        public Water(float x, float y, float direction) 
        {
            speed = 0.7f;
    
            graphic = new Graphic();
            graphic.setType("WATER");   
    
            graphic.setX(x);
            graphic.setY(y);
    
            direction = graphic.getDirection(); //direction from Hero as water is fired
        }
        public Water update(int time) 
        {
            graphic.draw();
            return Water.this;
            distanceTraveled; // this is where the error occured...
        }
    }
    

    When I tried to call distanceTraveled, I am getting the error as:

    Syntax error, insert «VariableDeclarators» to complete LocalVariableDeclaration

  • same issue but different scenario, can anyone please help :- public class InterfaceInsideClass { public static void main(String[] args) { ClassO.inner.i; // Error occurs here } } class ClassO { interface inner { int i=10; } }

  • @bharatbhushan: I think here you have multiply issues. First you have an interface which you cannot use for an assignment directly. You should have a class which implements the interface. Member variables in interfaces are final, so even you could use an interface for an assignment you were not allowed to change the value of i.

Recents

  • #2

Ты не присваиваешь значение, а просто его вызвал /Зачем?/

  • #3

MJaroslav написал(а):

Ты не присваиваешь значение, а просто его вызвал /Зачем?/

int quan = itemStack.stackSize; Вот так правильно?)

Eifel


  • #5

Ок, а как вычесть один предмет? Т.е. (пкм+шифт) = — 1 предмет, что в руках.

  • #6

Enotus написал(а):

MJaroslav написал(а):

Ты не присваиваешь значение, а просто его вызвал /Зачем?/

int quan = itemStack.stackSize; Вот так правильно?)

Вопрос в том, зачем тебе это значение, если ты его не используешь?

  • #7

MJaroslav написал(а):

Вопрос в том, зачем тебе это значение, если ты его не используешь?

Да, у меня такой же вопрос))
Я правильно понимаю, минусануть один предмет можно с помощью itemStack.stackSize?

  • #8

Enotus написал(а):

MJaroslav написал(а):

Вопрос в том, зачем тебе это значение, если ты его не используешь?

Да, у меня такой же вопрос))
Я правильно понимаю, минусануть один предмет можно с помощью itemStack.stackSize?

Да, но есть другой и большее правильный способ, посмотри код ItemStack’а, навскидку скажу, что в названии метода есть consume.

/И да, не забудь setMaxDamage(количество прочности), если у тебя это инструмент (по логике)/

  • #9

MJaroslav написал(а):

Enotus написал(а):

MJaroslav написал(а):

Вопрос в том, зачем тебе это значение, если ты его не используешь?

Да, у меня такой же вопрос))
Я правильно понимаю, минусануть один предмет можно с помощью itemStack.stackSize?

Да, но есть другой и большее правильный способ, посмотри код ItemStack’а, навскидку скажу, что в названии метода есть consume.

/И да, не забудь setMaxDamage(количество прочности), если у тебя это инструмент (по логике)/

Окей, с инструментом учту… Но у меня не инструмент. А вот consume и в помине нет.

Eifel


  • #10

if(player.isSneaking()) itemStack.stackSize—;

  • #11

Thunder написал(а):

if(player.isSneaking()) itemStack.stackSize—;

Вы явно сговорились))) До этого у меня этот метод не работал. Присвоить как-либо значение itemStack.stackSizе’у было нельзя. сейчас все работает. Благодарю!

  • #12

Вот, нашел ItemStack.damageItem(int, EntityLivingBase);

  • #13

Ааааааа… Создавайте нормальные названия тем, ну пожалуйста((

  • #14

RonyC написал(а):

Ааааааа… Создавайте нормальные названия тем, ну пожалуйста((

Два вопроса:
1) Почему это название ненормальное?
2) Что есть нормально название? (Ok. Google! Как научиться создавать нормальные названия?)

  • #15

1) Оно не говорит конкретно о проблеме, вместо этого соответствует практически всем возможным проблемам
2) Нужно называть темы так, чтобы было понятно: че там конкретно внутри?

  • #16

hohserg написал(а):

1) Оно не говорить конкретно о проблеме, вместо этого соответствует практически всем возможным проблемам
2) Нужно называть темы так, чтобы было понятно: че там конкретно внутри?

Окей, понял)

  • #17

И вдруг твою тему искать будут по схожей проблеме, поэтому надо давать четкие названия

Понравилась статья? Поделить с друзьями:
  • Syntax error unexpected symbol expecting register
  • Syntax error unexpected string at end of statement
  • Syntax error unexpected parseop zero
  • Syntax error unexpected main expecting
  • Syntax error unexpected integer number