Syntax error on token invalid assignmentoperator

for (int iI = 4; iI > 0; iI--) faAmount[iI] - faAmount[iI - 1]; This is the code it's in. How can I fix this?
for (int iI = 4; iI > 0; iI--)
  faAmount[iI] - faAmount[iI - 1];

This is the code it’s in. How can I fix this?

MByD's user avatar

MByD

135k26 gold badges266 silver badges275 bronze badges

asked May 6, 2012 at 1:49

Riemke Shabadoo's user avatar

1

Maybe you forgot the equal sign

for (int iI = 4; iI > 0; iI--) 
    faAmount[iI] -= faAmount[iI - 1];

Or to assign the difference in a variable

double x = 0; //or another value
for (int iI = 4; iI > 0; iI--) 
    x = faAmount[iI] - faAmount[iI - 1];

answered May 6, 2012 at 1:51

Luiggi Mendoza's user avatar

Luiggi MendozaLuiggi Mendoza

84.5k16 gold badges153 silver badges326 bronze badges

faAmount[iI] - faAmount[iI - 1] is n expression that have a result, but you don’t assign it to anything, this is invalid in Java.

answered May 6, 2012 at 1:52

MByD's user avatar

MByDMByD

135k26 gold badges266 silver badges275 bronze badges

The technical explanation is that faAmount[iI] - faAmount[iI - 1] is an expression but isn’t a statement. The JLS notes that

Unlike C and C++, the Java programming language allows only certain forms of expressions to be used as expression statements.

An additive expression is not one of those expressions that are also statements.

answered May 6, 2012 at 2:45

trutheality's user avatar

truthealitytrutheality

22.8k6 gold badges52 silver badges68 bronze badges

0

Содержание

  1. Ошибка «Недопустимое присвоение» от оператора ==
  2. 4 ответы
  3. Syntax error on token «==», invalid Assignment Operator
  4. Best Answer
  5. Answers
  6. RaspberryPi on SAP HCP – IoT blog series part 2: Receiving the sensor values in the cloud
  7. The Business Scenario: Rui’s Fish Import/Export Inc.
  8. The applications we’ll need
  9. Java app on the Raspberry Pi
  10. Java app on SAP HANA Cloud Platform account
  11. SAPUI5 app on SAP HANA Cloud Platform
  12. Get a free developer account for SAP HANA Cloud Platform
  13. Setup your development environment
  14. Deploy the Java app on your SAP HANA Cloud Platform account
  15. Getting the libs
  16. Setup project facets
  17. Add the source code
  18. The two persistence classes
  19. Code for Measurement.java file
  20. Code for Sensor.java file
  21. The SensorsServlet
  22. The DataHelper class
  23. Adapt the web.xml
  24. The resulting project
  25. Deploy the app
  26. Test the app
  27. Adding a sensor
  28. Adding a sensor value (measurement)
  29. Summary
  30. Assigned Tags

Ошибка «Недопустимое присвоение» от оператора ==

Я пытался написать простой метод:

И получил странную ошибку на == null часть:

Синтаксическая ошибка токена ==. Недействительный оператор присваивания.

Может, моя Java заржавела после сезона в PLSQL. Итак, я попробовал более простой пример:

Как это может быть?

Я использую jdk160_05.

Чтобы уточнить: я не пытаюсь ничего назначить, просто сделайте && операция между двумя логическими значениями. Я не хочу этого делать:

Да ладно ! Голосующий не хочет комментировать? — Tom

Я не голосовал против вас, но полагаю, они думают, что это такой глупый и очевидный вопрос, что похоже, что вы троллите. — Pyrolistical

Раньше вопроса было недостаточно, и на основании этого можно было дать ответ — gmhk

ВЕСЬ Ваш validate Метод не должен иметь никаких проблем, если PropertyA и PropertyB являются объектами, а не примитивными типами данных. — Pyrolistical

@Tom Я бы попробовал чистую сборку. У вас могут быть фантомные ошибки — Pyrolistical

4 ответы

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

должен выдать примерно такую ​​ошибку:

Ваша первая программа должна правильно компилироваться. Возможно, в тексте есть какой-то невидимый символ Юникода, который сбивает компилятор с толку. Попробуйте удалить всю функцию и ввести ее снова.

ответ дан 29 апр.

Спасибо, что немного обдумали это и не дали you cant assign дерьмовый ответ. — Том

? так вы исправили свою проблему или нет? — Пиролитический

@ Пиротехнические. Это помогло больше, чем все другие ответы. — Том

Я думаю, что на вопрос Тома более полно отвечает мой ответ, но ваш, по крайней мере, также указывает в правильном направлении. Проблема в том, что i==null не является утверждением, но некоторые компиляторы Java предоставляют дрянную диагностику для случая «не утверждения». — Даниэль Мартин

@Tom Итак, если это помогло, в чем была проблема? — звездно-голубой

== не является оператором присваивания, это логический оператор равенства, см .:

Если вы хотите установить i в значение null, используйте простой оператор присваивания =:

Если вы хотите проверить, что i имеет значение null, вам необходимо использовать оператор ==

ответ дан 29 апр.

Не могли бы вы тогда объяснить, что вы пытаетесь сделать . ваш вопрос немного сбивает с толку . — Джон

Так что я не могу сделать что-то вроде return i==null ? Сложно поверить. — Том

Да, вы можете написать «return i == null;» Но вы представили нам на рассмотрение не это. — Леонблой

return i==null буду работать. Ваш код выше только i==null . i==null сам по себе ничего не значит. — Райанпрайого

@ryanprayogo. Тем не менее, ошибка компилятора? Нужно просто скомпилировать в нерабочую или что-то в этом роде. — Том

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

Итак, у Java есть эта идея, которая разделяется некоторыми другими языками, поскольку только потому, что что-то является действительным выражение не означает, что эта вещь сама по себе является действительной заявление.

Например, этот код будет жаловаться аналогично:

И все же, очевидно, я могу использовать i+3 (распаковывайте!) в другом месте, чтобы означать » 7 «:

Это немного сбивает с толку, потому что в отличие от некоторых языков, которые имеют это различие между выражениями и операторами, java позволяет использовать любой вызов метода — независимо от того, возвращает он значение или нет — в качестве оператора. Однако большинство операторов Java сами по себе не формируют действительный оператор.

Источник

Syntax error on token «==», invalid Assignment Operator

Hello, I am new to processing. And I am really stuck I’m currently try to make a object move left to right or right to left randomly.

however the line (check == true) has a error on it. Any idea how i can fix this?

Best Answer

Answers

must be
check = false;

Welcome to processing! It’s great!

the double == is for comparison (as in if)

the single = is for assignment (give the variable on the left the result of what’s on the right)

you mostly have that right anyway.

Hmm, then it says cannot convert float to int.. for (int z = random(1))

you might want to use setup() and draw()

pls read the section «hello mouse» here:

Hmm, then it says cannot convert float to int.. for (int z = random(1))

int z = int (random(1));

Oh, thank you i figure it out!

How to post code

when you post your code:

in the editor hit ctrl-t to auto format

paste it in the browser

leave 2 empty lines before it

mark the code (without the 2 empty lines)

press C in the small command bar.

For pure boolean comparisons like:
if (check == true) <> and if (check == false) <>

A more elegant (and possibly better performance) coding is:
if (check) <> and if (!check) <>

This will always be 0 (so check will always be false). Run the following code:

The reason is that int() always rounds down to an integer (it removes the part that comes after the decimal point entirely). The solution is to take a random number between 0 and 2:

You don’t need the second if statement to check if z is equal to 0, because check is false by default so you’re not changing anything. Also in the improbable case z would be equal to 2 one day (not sure if this is even possible), it will be taken care of.

Источник

RaspberryPi on SAP HCP – IoT blog series part 2: Receiving the sensor values in the cloud

In the first blog post of this Iot blog post series we’ve prepared the Raspberry Pi for the upcoming blog posts.

In this blog post we’ll create a Java app on your free developer account on the SAP HANA Cloud Platform that will receive the sensor values from the Raspberry Pi.

Once this is up and running, the Java app on the Raspberry Pi will be “a piece of cake” 🙂

Please be aware that this blog post will not provide you with code that you should use productively. It actually is focusing on getting an app up-and-running for demo purposes.

So take this whole blog post series and its sample code AS IS and with the purpose it was build: to inspire you to think about other IoT (Internet of Things) scenarios you could run on the SAP HANA Cloud Platform and NOT as a best practice for productive environments.

So let’s get started.

Table of Contents

The Business Scenario: Rui’s Fish Import/Export Inc.

In our scenario we’ll assume we are in the Fish business and transport fish from one location to the other. As the fish we are transporting is very valuable we want to be able to track the temperature inside the fish boxes remotely.

For that purpose we have installed inside our truck a Raspberry Pi that can send data to the internet. In addition to that we have connected 4 temperature sensors to the RaspberryPi that we’ll use to determine the temperature inside the fish boxes. Those temperature values will be sent every minute to your free developer account on the SAP HANA Cloud Platform.

The applications we’ll need

Our solution will have in its center an SAP HANA Cloud Platform account. We’ll use an account under the free developer license.

The software solution well build will have three building blocks.

Java app on the Raspberry Pi

Firstly we’ll provide our Raspberry Pi with a Java app. That app will send an http request to a Java app on the SAP HANA Cloud Platform and send sensor data to it.

Java app on SAP HANA Cloud Platform account

Secondly we’ll have a Java app on your account on the SAP HANA Cloud Platform that will be the receiving the data from your Raspberry Pi. That app will also persist the data on the HANA instance of your account.

The Java app will also be able to create a JSON output with the sensor data so it can be consumed by the SAPUI5 application we have.

SAPUI5 app on SAP HANA Cloud Platform

The SAPUI5 app will provide us with a dashboard showing the current temperature of the fish boxes in the truck. That application will consume the JSON output from the Java app on the SAP HANA Cloud Platform account.

Get a free developer account for SAP HANA Cloud Platform

As a developer you can get a free developer account under a developer license. You register on https://hanatrial.ondemand.com and after activating your account via an email you get access to the cockpit of your developer account (https://account.hanatrial.ondemand.com/cockpit).

Setup your development environment

You’ll need to install Eclipse IDE for Java EE Developers as well as the SAP HANA Cloud Platform Tools and the SAP HANA Tools Eclipse plugins.

In a last step you also need to download the Java Web SAP HANA Cloud Platform SDK and unzip it on your drive. I’ve used for this blog post the SDK version 1.65.10.

To prepare your project you should also already add a new server under the Servers view for deployment on your localhost.

All of these steps are drilled-down in detail on a tutorial at the hcp.sap.com website. Just follow the steps there and you are all set for the next steps.

Deploy the Java app on your SAP HANA Cloud Platform account

The Java app on your account will be a Dynamic Web Project. So go ahead and create such a project in your Eclipse.

To do that switch to your Java EE perspective (Window > Open Perspective > Other > Java EE) and create such a project (File > New > Dynamic Web Project). Ensure your screen looks like the screenshot below.

Meaning you have selected the correct Target runtime (Java Web) as well as the right Dynamic web module version (2.5) and the right Configuration (Default Configuration for Java Web).

Getting the libs

Now you need to get a couple of libraries first to use the app. Three of them can be found in the Java Web SDK of the SAP HANA Cloud Platform (1.xx.yy). They are called eclipselink-xxx.jar, javax.persistence-yyy and com.sap.security.core.server.csi_1.0.1.jar. You can find all three files in one of the samples in the SDK folder under samples > persistence-with-jpa > WebContent > WEB-INF > lib. In the SDK version I’ve used (1.65.10) the files are called eclipselink-2.5.1.jar, javax.persistence-2.1.0.jar and com.sap.security.core.server.csi_1.0.1.jar. Copy all three files into the lib folder of your Eclipse project (WebContent > WEB-INF > lib).

The other library you need is the GSON library from Google, which helps us generate JSON output quite elegantly. You can get it here. You also need to copy that jar file into the lib folder of your Eclipse project (WebContent > WEB-INF > lib).

Setup project facets

We’ll use JPA in our project hence we need to activate the corresponding project facet in our project. Simply right-click on your project in the Eclipse project explorer and select Build path > Configure Build Path. After that click on the Project Facets entry on the left side of the window and activate on the right the JPA project facet in version 2.0.

Once you click on it you’ll also notice at the bottom of the window a link called “Further configuration available”. Click on that link and configure the facet as shown in the screenshot below.

Add the source code

We’ll need in total four Java classes. One is the servlet, the other one a helper class for the persistence and two other classes containing the data model of our app.

The two persistence classes

Click on the folder of your project that is called Java Resources, right-click on it and select New > Class. In the Package field enter the value org.persistence and in the filed Name you need to enter Measurement. Once entered, click on Finish.

Now do the same for the class Sensor. In the Package field enter also the value org.persistence and in the filed Name you need to enter Sensor. Once entered, click on Finish.

Substitute the generated code with the following code.

Code for Measurement.java file

import static javax.persistence.GenerationType.AUTO;

@NamedQuery(name = “AllMeasurements”, query = “select m from Measurement m”),

@NamedQuery(name = “LastSensorReading”, query = “select m from Measurement m where m.sensorId = :paramSensorId and m.storedAt = (SELECT MAX(r.storedAt) from Measurement r where r.sensorId = :paramSensorId)”),

@NamedQuery(name = “LastReadingsFromSensor”, query = “select p from Measurement p where p.sensorId = :paramSensorId order by p.storedAt DESC”) >)

public class Measurement implements Serializable <

private static final long serialVersionUID = 1L;

private Long id;

private String unit;

private Timestamp storedAt;

private Double value;

private long sensorId;

public Long getId()

public void setId(Long id)

public String getUnit()

public void setUnit(String unit)

public Timestamp getStoredAt()

public void setStoredAt(Timestamp dateStored)

public Double getValue()

public void setValue(Double sensorValue)

public static long getSerialversionuid()

public long getSensorId()

public void setSensorId(long param)

Code for Sensor.java file

import static javax.persistence.GenerationType.AUTO;

public class Sensor implements Serializable <

private static final long serialVersionUID = 1L;

private long id;

private String device;

private String type;

private String description;

private Measurement lastMeasurement;

private Collection measurements;

public Measurement getLastMeasurement()

public void setLastMeasurement(Measurement lastMeasurement)

public long getId()

public void setId(long id)

public String getDevice()

public void setDevice(String param)

public String getType()

public void setType(String param)

public String getDescription()

public void setDescription(String param)

public Collection getMeasurement()

public void setMeasurement(Collection param)

Finally you need to update the persistence.xml file so that you add a few new lines to register the two persistence classes to it.

Open the persistence.xml file (Java Resources > src > META-INF) by right-clicking on the persistence.xml file and click on Open With > Text Editor.

Between the persistence-unit tag you need to have 6 additional lines added which are marked bold below.

Be aware to only add the 6 new lines, because the file contains the name of your project in the persistence-unit under the name property.

So your persistence.xml file looks like this.

org.persistence.Measurement

org.persistence.Sensor

The SensorsServlet is the servlet that will receive the data and also take care to create corresponding JSON output.

Create a servlet called SensorsServlet. To do that click on the folder of your project that is called Java Resources, right-click on it and select New > Servlet. As Java package enter the value com.sap.iot.sensors and as Class name you enter SensorsServlet. Once entered click on Finish.

Now just replace the code you have there with the code for SensorsServlet that I’ve provided as an additional file to this blog. Just unzip the file and copy-and-paste it.

Please be sure to adapt the init() method inside the SensorsServlet so that

emf = Persistence.createEntityManagerFactory(“iotscenario“, properties);

has the same name like your project. It needs to be the same like defined in the persistence-unit entry of your persistence.xml file (under

The DataHelper class

This class will help us with some methods to persist data.

Create a classe called DataHelper. To do that click on the folder of your project that is called Java Resources, right-click on it and select New > Class. As Java package enter the value com.sap.iot.sensors and as Class name you enter DataHelper. Once entered click on Finish.

Now just replace the code you have there with the code for DataHelper.java (see at the bottom of this post).

Adapt the web.xml

At the end we’ll need to modify the web.xml file for the servlet mapping of the Servlet. Instead of

we need to change the url-pattern and add a new resource into the web.xml for the jdbc connection so that the part of the servlet-mapping looks like this

jdbc/DefaultDB

javax.sql.DataSource

The resulting project

At the end your project structure should look like this:

Deploy the app

Now deploy the app to your free developer account. Just follow the instructions in the tutorial HCP and Java – Hello World on the hcp.sap.com website if you don’t know how to do that. Check the step called “Deploy, Run and Test the Application in the Cloud” in that tutorial and adapt the instructions there to your project here.

Test the app

If you did everything right you should now be able to add a sensor to the database. Let’s test this.

When calling your app for the first time you’ll get an empty JSON output with an opening and closing curly bracket.

Adding a sensor

To add a sensor to your database you should call the servlet this way:

https:// .hanatrial.ondemand.com/ /?action=addsensor&type=temperature&device=Truck 1- RaspPi&description=RaspberryPi CPU

If your account is called p1234567890trial, the project is called iotscenario and you defined the name fishimport as the name of your app when you’ve deployed it to your account the link looks like this:

Just enter the link and press return. After that call your app again (in this example the link to the app is https://fishimportp1234567890trial.hanatrial.ondemand.com/iotscenario), and instead of getting empty curly brackets you should see something similar like this:

You can add as many sensors as you want. Most importantly each of them as a unique id. That id is used to assign measurements to it. That’s what we’ll do in the next step.

Adding a sensor value (measurement)

Now that we have a sensor added to the database we can also store the sensor values related to it.

To add a sensor value (or measurement how the object is called in the database) you need to call the servlet with different parameters. Taking the example from above where we’ve created a sensor with the id 1, the link to create a corresponding measurement looks like this:

Again type-in the link and execute it. Afterwards call the servlet again without any parameters and you’ll get an output similar to this one:

“id”:1,”device”:”Truck 1 – RaspPi”,”type”:”temperature”,”description”:”RaspberryPi CPU”,

The output provides you now with the last measured sensor value (lastMeasurement) as well as a list of all stored measurements (measurements). Although it should provide you with ALL measurements you have assigned to the sensor there is a limit that I’ve added for performance reasons.

If you check the code of the servlet there is a variable inside SensorsServlet called MAX_NUMBER_SENSOR_READINGS. In the code I’ve provided this is set to 10. Of course you can modify this number and adapt it to your needs.

Summary

We are now set to send sensor values to our app in the cloud which also provides a JSON output of that data that we can consume in an UI.

In the next blog post we’ll create the sending part on the RaspberryPi so that it can send it’s temperature to our app in the cloud.

Looking forward for your feedback.

Assigned Tags

Hi all, I’ve just added the code for the SensorsServlet and DataHelper as additional files to this blog post. Makes it easier for you to copy-and-paste the code.

Where are the files mentioned in this blog post? (zip?)
The SensorsServlet and the DataHelper or copy and paste the code.

Please make it available again. Thanks!

is it possible for you to share the code from this file?

The file is no longer available in this blog 🙁

restored DataHelper.java — for the rest we have to wait for Rui.
thanks!

Please provide the Code for Sensorservlet

Can you please provide the SensorServlet and DataHelper files? They are no longer available on the links

Thanks in advance

Damn it Rui, you may just have me back programming Java again 😉

Great blog series!!

Thanks Hendrik! Have fun.

Hi Rui & Hendrik,

I think with my «SAP HANA Cloud Trial Authentication Proxy for HANA XS Services» (https://github.com/gregorwolf/hanatrial-auth-proxy) this example should also be possible without any Java coding. Sounds like a next home project :-).

Hi Gregor, you are absolutely right.

There is no need for a Java app, but you can also create a HANA-native app for this purpose with less effort.

Haven’t had a chance looking into your «SAP HANA Cloud Trial Authentication Proxy for HANA XS Services».

In case you try out with your project please share. Thanks a lot!

Cool idea! If you could give me an extra long weekend next, I’d be up for the challenge 😉

(and now I’m even more convinced that we’ll be seeing some HCP-XS-Auth-Magic at sitfra)

Cheers & Have fun Gregor!

That’s a serious amount of Java. And Java is not really my thing

But it all looks pretty comprehansible so I’ll just try and learn 🙂

A nice one for the weekend

I’m getting an issue with the project, there is warning that prevents the deployment of the application in HCP, here is the warning:

Description Resource Path Location Type No connection specified for project. No database-specific validation will be performed

It’s related to a missing connection in the Setup project facets where an entry of the connection is missing.

Do you have any input on this?

Can you share a screenshot from your project facets and where you see the missing connection?

Please use EclipseLink 2.2.x as described in the script and not EclipseLink 2.6.x

Hope this helps.

I have a similar issue: JPA Problem: No connection specified for project. No database-specific validation will be performed. I am using EclipseLink 2.2.x

Just fixed a bug in the SensorsServlet source file in the encodeText method.

Would it be possible to send a zipped copy of the project? I have been following the project with interest but am not a Java practitioner and I am getting a 404 error when I run the code locally and on HANA.

Would love to see that as a WebIDE based Javascript only app. 😉

that of my talk that I’ve submitted for the sitFRA. I’ve replicated Rui’s project in pure HANA, node.js, Node-Red and SAP Web IDE.

Nice blog series Rui,

Hi Basar, was hoping that others will jump-in and do that :-).

I haven’t done much with nodeJS, but you should be able to use the same principles also on nodeJS.

Could I make a calculation view on those tables that were generated from the persistence units? I cannot even find them on the trial cloud account. I have loads of temperature readings and I would like to sum them (lets say by day) in a claculation view. I would call that calculation view in the app.

Great post and thanks,

Hi David, just connect to your free developer account using the SAP HANA Development perspective and follow the steps that I also show in the openSAP course «Introduction to SAP HANA Cloud Platform» in week 2 unit 2:

Should work out-of-the-box.

Hope this helps.

Great blog.
Thanks for sharing.

Thank you for your blog and online courses @ open.sap.com.

I have a question. Once sensors data created @

Is it possible to reset database to initial value <>?

Hi Andrey, yes. It is possible by editing a property in the persistence.xml file. Just set the DDL generation type from «Create Tables» to «Drop and Create Tables» and deploy your application again to your account. After that the tables of the app are all deleted and created again.

If you want to keep your data after deploying the app, you need to switch the property back to «Create Tables».

Hope this helps.

Thank you for your reply.

I was able to reset my table

Excellent blog. I was trying to write procedures and create views on the sensor readings dumped to the cloud. However, I get the following error (Insufficient Privileges Execute on Repository_Rest) when I open the content section in SAP Hana Administration console on eclipse. It seems I don’t have the required package privileges. Could you please suggest a solution to this issue.

Thanks and Regards

it is a shared HANA instance on trial.You are not allowed to see the Contents. You may try to create a HANA XS Trial instance for your HCP account on trial and then re-bind the ‘iotscenario’ java app to work with the created HANA XS instance. With that you will have your own package under Content directory, create XS apps and also use SAP HANA Web Based Development workbench for development.

P.S. After re-bind the data source for your java app, you will have to re-start an app and send some data first.

Update. Necessary steps on how to create a XS Trial instance and do the re-binding of the data source can be found in blog post #3 by the following link Using the SAP HCP IoT Services

Thank you so much Anton.

That really helps a lot. I created a HANA XS trial instance and changed the binding. I am able to see the content section and I have the required access privileges I need to create procedures and views.

Hi Rui and Aaron,

Thank you for your support.

I was able to connect » DS18B20″ sensor on raspberry pi over the node-red.

Sending home room temperature over Internet of Things Services (BETA)

using HTTP API data services POST as per instructions provided

Screen below shows exercise with HANA XS application. As per Aaron pdf «Connecting a UI5 GUI using WebIDE»

Next idea is build fiori application to get access to the data from temperature sensor.

Great post and I tried going through the steps. i do get errors in the eclipse environment. the classes dont seem to be found. I have included a picture.

I did probably download newer versions of the jre and eclipse environment, could that result in these errors.

Regards, Niels.

Figured it out. In Eclips the org.persistance package was not recognised correctly. Fixed now, works like a dream.

I’m getting the following error. Any thoughts?

Hi Eric, do you use the same setup: HCP Runtime and JPA? What is the persistence version specified in your persistence.xml?

It seems to be 2.1

xml version=»1.0″ encoding=»UTF-8″?>

My suspicion is that my web.xml config is not right. See below:

xml version=»1.0″ encoding=»UTF-8″?>

ref -name> jdbc /DefaultDB ref -name>

Any help gratefully accepted.

FYI, I’m very much a newbie to Eclipse, SAP’s environment and XML config files. Used to be a C coder.

Here are my Java resource files

Change it to 2.0 and redeploy your web app.

you need to choose a database in the Java applications default settings. Make sure you have a entry in the Data Source Bindings:

Awesome tutorial Rui!

Just one comment to maybe help others with the same issue.

After deploying the app I got message:

HTTP Status 500 — while trying to invoke the method java.util.List.size() of a null object loaded from local variable ‘sensors’

It seems the named queries were not registered successfully. To fix this I had to add the persistency classes to the persistency.xml:

xml version = «1.0» encoding = «UTF-8» ?>

persistence-unit name = «iotscenario» >

provider > org.eclipse.persistence.jpa.PersistenceProvider provider >

class > org.persistence.Measurement class >

class > org.persistence.Sensor class >

property name = «eclipselink.ddl-generation» value = «create-tables»/>

i am not getting from where i need to add jar files to the lib directory.

my project structure is like this.

as Rui explained you need to take those jars from «persistence-with-jpa» sample available in SDK (current version is neo-java-web-sdk-1.105.21) on SAP Development Tools

I got servlet deployed on HCP. I am able to run it and see <>. When I am trying to add sensor, it is throwing an exception. Could you please help let me know what could be the issue here.

Where are the files mentioned in this blog post? (zip?)

Please make it available again. Thanks!

maybe someone has the files or the code (SensorsServlet, DataHelper, Temperatur.java) and could send it to me?

Thanks in advance.
Daniel

If someone replies your post, can you please forward me the files?

THanks in advance

restored DataHelper.java — check it out in the post. thanks!

Hi all —
we’re aware that the required class/code files referenced in this blog have been lost during the SAP Community migration. Unfortunately Rui is out of the office at the moment but is aware of the issue and plans to get to it as soon as possible! Stay tuned and apologies for the inconvenience!
-m

Hi all — we’ve restored DataHelper.java. If there are still other missing files we’ll need to wait for Rui to return. Hopefully this helps get further!
thanks

Hi Moya and Rui,

Would be great if you could provide the SensorServlet file/code.

Hi all together,

Are there any updates on the missing SensorsServlet file? I’d like to use it for my IoT project. When does Rui Nogueira upload it?

Do you know when you will load the SensorServlet file?

Hey everybody, due to a great community member (thanks Olivia Carline!) I was able to add the missing Java servlet SensorsServlet.

When I copied the measurement.java I cam across some syntax checks I couldn’t resolve myself.

I came as far as copying the measurement.java

Any idea? Thanks in advance!

Maybe eclipse environment or syntax have changed meanwhile.

«measurement cannot be resolved to a type»

Detailed Java Problems:

Duplicate annotation of non-repeatable type @NamedQuery. Only annotation types marked @Repeatable can be used multiple times at one target.
Duplicate annotation of non-repeatable type @NamedQuery. Only annotation types marked @Repeatable can be used multiple times at one target.
Syntax error on token «:», @ expected
Syntax error on token «:», @ expected
Syntax error on token «:», delete this token
Syntax error on token «by», invalid AssignmentOperator
Syntax error on token «Invalid Character», @ expected
Syntax error on token «Invalid Character», @ expected
Syntax error on token «Invalid Character», @ expected
Syntax error on token «Invalid Character», @ expected
Syntax error on token «Invalid Character», delete this token
Syntax error on token «Invalid Character», delete this token
Syntax error on token «Invalid Character», delete this token
Syntax error on token «m», delete this token
Syntax error on token «MAX», invalid AssignmentOperator
Syntax error on token «where», ( expected
Syntax error on token «where», ) expected
Syntax error on token(s), misplaced construct(s)
Syntax error on token(s), misplaced construct(s)
Syntax error on token(s), misplaced construct(s)
Syntax error on token(s), misplaced construct(s)
Syntax error on token(s), misplaced construct(s)
Syntax error on token(s), misplaced construct(s)
Syntax error on token(s), misplaced construct(s)
Syntax error on token(s), misplaced construct(s)
Syntax error on token(s), misplaced construct(s)
Syntax error on token(s), misplaced construct(s)
Syntax error on token(s), misplaced construct(s)
Syntax error on token(s), misplaced construct(s)
Syntax error on tokens, ( expected instead
Syntax error on tokens, MemberValuePairs expected instead
Syntax error on tokens, MemberValuePairs expected instead
Syntax error on tokens, MemberValuePairs expected instead
Syntax error on tokens, MemberValuePairs expected instead
Syntax error, insert «)» to complete MemberValue

Источник

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

Понравилась статья? Поделить с друзьями:
  • Syntax error on token expected syntax error on token expected after this token
  • Syntax error on token expected after this token java 1610612967
  • Syntax error on token else delete this token
  • Syntax error on token close identifier expected after this token
  • Syntax error on token class char expected