I am trying to create a nested class in order to use the AsyncTask, however eclipse gives me an error on the class SendData saying «Syntax error on token «class», invalid type» why is it giving me that error?
package com.example.myfirstapp;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.os.Bundle;
import android.app.Activity;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;
import android.content.Intent;
import android.widget.TextView;
public class DisplayMessageActivity extends Activity {
String url = "http://www.mySIte.com/phpFIle";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
setContentView(textView);
new SendData().execute();
}
private class SendData() extends AsyncTask<Void, Void, Void>{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try{
List<NameValuePair> nameValues = new ArrayList<NameValuePair>(1);
nameValues.add(new BasicNameValuePair("id", "12345"));
httppost.setEntity(new UrlEncodedFormEntity(nameValues));
System.out.println("Before response");
HttpResponse response = httpclient.execute(httppost);
System.out.println("After response");
}catch(ClientProtocolException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
asked Dec 26, 2012 at 21:33
1
sendData() is a method syntax, not a class
private class SendData() extends AsyncTask<Void, Void, Void>{
should be
private class SendData extends AsyncTask<Void, Void, Void>{
answered Dec 26, 2012 at 21:34
PermGenErrorPermGenError
45.7k8 gold badges86 silver badges106 bronze badges
private class SendData()
You have both method
and class
syntax here. Not sure which one you want.
If you want to define a class then remove ()
answered Dec 26, 2012 at 21:34
kosakosa
65.6k13 gold badges126 silver badges167 bronze badges
Я получаю синтаксическую ошибку в своем основном классе, когда вызываю конструктор из другого класса, который мне нужен для запуска основной программы. Эта программа ориентирована на наследование и соответствующий вызов конструкторов и аргументов. Это сообщение об ошибке, которое я получаю во время компиляции:
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
In this post, I will be sharing how to fix the syntax error on token «,», { expected after this token error in Java. It is a compile-time error. As the name suggests, this error is syntax-based and mostly faced by Java beginners.
Read Also: [Fixed] Unclosed String Literal Error
As always, first, we will produce the syntax error on token «,», { expected after this token error before moving on to the solution. Let’s dive deep into the topic:
Note: This compiler error can be produced only in the Eclipse IDE.
[Fixed] Syntax error on token «,», { expected after this token
1. Producing the error
We can easily produce this error in the Eclipse IDE by writing code or executable statements outside the method as shown below:
import java.util.*; public class SyntaxError { String str = "Alive is Awesome"; Random rand = new Random(); for (int i = 0; i < 3; i++) { System.out.println(str); } }
Output:
2. Explanation:
The cause of this error is due to the code or executable statements not present inside the method. You can not directly write the code in a class in Java. Only variables declaration/initialization are allowed outside the method.
3. Solution:
The above compilation error can be resolved by moving the code inside a method. In simple words, you can’t call a class you have to call a method that is declared inside a class. We can easily avoid this error by using one of the solutions given below:
Solution 1: Using public static void main() method
We have moved the code inside the public static void main() method as shown below in the code:
import java.util.*; public class SyntaxError { public static void main(String args[]) { String str = "Alive is Awesome"; Random rand = new Random(); for (int i = 0; i < 3; i++){ System.out.println(str); } } }
Solution 2: Using any method
We can move the executable code inside any method, for example, the printString() method as shown below in the code:
import java.util.*; public class SyntaxError { public static void printString() { String str = "Alive is Awesome"; Random rand = new Random(); for (int i = 0; i < 3; i++){ System.out.println(str); } } public static void main(String args[]) { printString(); } }
Solution 3: Using block
Any executable code inside {} without any method name is called a block. We can move the executable code inside the block also as shown below:
import java.util.*; public class SyntaxError { // Using block { String str = "Alive is Awesome"; Random rand = new Random(); for (int i = 0; i < 3; i++){ System.out.println(str); } } public static void main(String args[]) { new SyntaxError(); } }
That’s all for today. Please mention in the comments in case you have any questions related to the syntax error on token «,», { expected after this token error in Java.
Anton8800 14 / 2 / 0 Регистрация: 29.09.2018 Сообщений: 246 |
||||
1 |
||||
12.12.2018, 00:12. Показов 5410. Ответов 12 Метки нет (Все метки)
Exception in thread «main» java.lang.Error: Unresolved compilation problems: at j2.main(j2.java:6)
__________________
0 |
109 / 89 / 25 Регистрация: 02.06.2018 Сообщений: 259 |
|
12.12.2018, 00:59 |
2 |
Потому что вы просто в «пустоту» пытаетесь вывести результат. Добавлено через 8 минут
0 |
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 |
|||||||
Потому что вы просто в «пустоту» пытаетесь вывести результат.
Так тоже не работает.Но работает так
Почему?
0 |
Нарушитель 14042 / 8230 / 2485 Регистрация: 21.10.2017 Сообщений: 19,708 |
|
12.12.2018, 19:27 |
5 |
Почему? Прежде чем пытаться лепить тернарный оператор, разберись как следует с if..else
0 |
14 / 2 / 0 Регистрация: 29.09.2018 Сообщений: 246 |
|
12.12.2018, 19:38 [ТС] |
6 |
Прежде чем пытаться лепить тернарный оператор, разберись как следует с if..else Почему? И что конкретно подучить с if else там же вроде все просто. Или есть подводные камни?
0 |
Нарушитель 14042 / 8230 / 2485 Регистрация: 21.10.2017 Сообщений: 19,708 |
|
12.12.2018, 19:52 |
7 |
РешениеAnton8800, что такое тернарный оператор? Добавлено через 7 минут Безотносительно к определённому языку программирования тернарную операцию можно определить так: логическое выражение ? выражение 1 : выражение 2 1. Вычисляется логическое выражение. Обрати внимание на третий пункт.
a>3&&b>3 ? a+b:a; Вот куда оно у тебя здесь возвращается?
1 |
14 / 2 / 0 Регистрация: 29.09.2018 Сообщений: 246 |
|
12.12.2018, 21:35 [ТС] |
8 |
Прежде чем пытаться лепить тернарный оператор, разберись как следует с if..else Почему? И что конкретно подучить с if else там же вроде все просто. Или есть подводные камни?
Вот куда оно у тебя здесь возвращается? Понял принял)
0 |
NiceJacket 109 / 89 / 25 Регистрация: 02.06.2018 Сообщений: 259 |
||||
12.12.2018, 21:50 |
9 |
|||
Так тоже не работает. честно говоря, для меня загадка, КАК именно не работает, основываясь на моём комменте? Не по теме: Не думал, что мой коммент не будет исчерпывающим Добавлено через 8 минут
Почему? И что конкретно подучить с if else там же вроде все просто. Или есть подводные камни? Если переписать ваш тернарный оператор на if else именно так, как написано у вас, то это будет выглядеть следующим образом:
Что totally некорректно. Суть ясна?
1 |
14 / 2 / 0 Регистрация: 29.09.2018 Сообщений: 246 |
|
12.12.2018, 22:00 [ТС] |
10 |
Суть ясна? Да, спасибо)
0 |
109 / 89 / 25 Регистрация: 02.06.2018 Сообщений: 259 |
|
12.12.2018, 22:01 |
11 |
Да, спасибо) Так вы поделитесь, вот вы прочитали, сделали, не получилось. Как именно вы сделали?
0 |
Anton8800 14 / 2 / 0 Регистрация: 29.09.2018 Сообщений: 246 |
||||
12.12.2018, 22:16 [ТС] |
12 |
|||
Суть ясна? Да, спасибо)
Так вы поделитесь, вот вы прочитали, сделали, не получилось. Как именно вы сделали? Сделал по дебильному
Просто не понимал, что вычисленное значение возвращается
0 |
NiceJacket 109 / 89 / 25 Регистрация: 02.06.2018 Сообщений: 259 |
||||
12.12.2018, 22:19 |
13 |
|||
Да, спасибо)
Просто не понимал, что вычисленное значение возвращается понятно, конечно же, имелось в виду всю операцию поместить в 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» {$mode objfpc}{$H+} interface uses
Ошибка: project1.lpr(1,1) Fatal: Syntax error, «BEGIN» expected but «end of file» found Искать еще темы с ответами Или воспользуйтесь поиском по форуму: 13 |
У вас здесь несколько ошибок. Я их исправил, программа запускается и выдаёт результат:
Name: Al
Address: 222BurdSt
Telephone number: 2102223321
Customer ID: 46821
Amount spent: 2000
On mailing list: true
Discount: 10.0
Удалите конструктор PreferredCustomer из основного метода. Это не может быть частью
метод, он является частью класса. Затем конструктором PreferredCustomer является уже присутствует в классе PreferredCustomer.
Надеюсь, классы вашего клиента и PreferredCustomer находятся в отдельных файлах? Если нет, поместите их в отдельные файлы с именами customer.java и PreferredCustomer.java. В конструкторе класса PreferredCustomer удалите PreferredCustomer preferredCustomer из аргументов. Это излишне: зачем передавать одного клиента другому? Есть ли у клиентов какие-либо отношения друг с другом? Теперь количество аргументов будет совпадать при вызове конструктора (и не использовать строки «2000», «1000», где должны быть целые числа):
PreferredCustomer 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());
}
И позаботьтесь об именах, как указывали другие люди.
posted 8 years ago
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
Hello,
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
posted 8 years ago
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
seems to be declared as just an
Object
.
Errors
is not a property of
Object
.
All things are lawful, but not all things are profitable.
posted 8 years ago
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
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.
Regards,
Robert
There are worse crimes than burning books. One of them is not reading them. Ray Bradbury
posted 8 years ago
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
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.
casey Gould
Greenhorn
Posts: 17
posted 8 years ago
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
@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 <Doc type>
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.
Robert D. Smith
Ranch Hand
Posts: 235
posted 8 years ago
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
That’s the problem — objError is not declared. You are assigning an empty string to something that is not defined, and the compiler doesn’t know what to do with it. What is objError ?
There are worse crimes than burning books. One of them is not reading them. Ray Bradbury
posted 8 years ago
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
casey Gould wrote:
Am I wrong in doing it this way?
Yes — modern JSPs should contain no Java code. That’s an old holdover from JSP 1 which was superseded by JSP 2 in 2002 — 12 years ago!
I recommned novices to servlets and JSP read
The first makes sure you understand what JSP is all about (similar, but not identical, to ASP), and the second how to properly structure modern Java web apps.
casey Gould
Greenhorn
Posts: 17
posted 8 years ago
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
Thank you for help everyone, I believe I have gotten passed it.