error I see: Syntax error on token «package», assert expected
Источник
How do I solve the problem:Syntax error on tokens, delete these tokens?
I need help to solve the errors that I am getting for my connection pooling code:-
Generated servlet error:
Syntax error on token «import», delete this token
Generated servlet error:
Syntax error on tokens, delete these tokens
Please do help, thanks!
m_InitialConnectionCount)
<
// Clean up extra available connections.
Connection c = (Connection)m_AvailableConnections.lastElement();
m_AvailableConnections.removeElement(c);
c.close(); // Close the connection to the database.
>
// Clean up is done
>
out.print(«CLEANUP : Available Connections : » + availableCount());
// Now sleep for 1 minute
Thread.sleep(60000 * 1);
>
>
catch(SQLException sqle)
<
sqle.printStackTrace();
>
catch(Exception e)
<
e.printStackTrace();
>
>
>
// Example code using ConnectionPool.
public class Main
<
public static void main (String[] args)
<
try
<
Class.forName(«org.gjt.mm.mysql.Driver»).newInstance();
>
catch (Exception E)
<
out.print(«Unable to load driver.»);
E.printStackTrace();
>
try
<
ConnectionPool cp = new ConnectionPool(«jdbc:mysql://localhost/publications», «books», «books»);
Connection []connArr = new Connection[7];
Problem with import statement,
There are some syntactically wrong with this import tag, How can you import more than one package in JSP page ?
I know the answer but I want you to find out
Thanks, I just tried the below :-
import= javax.naming.*;
import = java.sql.*;
import = java.io.*;
import = java.lang.*;
import = java.text.*;
import = java.util.*;
. and I got more errors. Can you please give me another hint coz i’m totally lost
The errors:-
An error occurred at line: 1 in the jsp file: /publications/connpool.jsp
Generated servlet error:
Syntax error on token «import», invalid Expression
An error occurred at line: 1 in the jsp file: /publications/connpool.jsp
Generated servlet error:
Syntax error on tokens, SimpleName expected instead
An error occurred at line: 1 in the jsp file: /publications/connpool.jsp
Generated servlet error:
Syntax error on tokens, SimpleName expected instead
An error occurred at line: 1 in the jsp file: /publications/connpool.jsp
Generated servlet error:
Syntax error on tokens, SimpleName expected instead
An error occurred at line: 1 in the jsp file: /publications/connpool.jsp
Generated servlet error:
Syntax error on tokens, SimpleName expected instead
An error occurred at line: 1 in the jsp file: /publications/connpool.jsp
Generated servlet error:
Syntax error on tokens, SimpleName expected instead
An error occurred at line: 1 in the jsp file: /publications/connpool.jsp
Generated servlet error:
Syntax error on token «*», Identifier expected
An error occurred at line: 1 in the jsp file: /publications/connpool.jsp
Generated servlet error:
Syntax error on token «import», delete this token
An error occurred at line: 1 in the jsp file: /publications/connpool.jsp
Generated servlet error:
Syntax error on tokens, delete these tokens
Please hheelllpp.
Nothing wrong with your import statement, in jsp page you can always have multiple imports. But something looks wrong with you class declarations, in a jsp page we can only declare abstract or final classes. Another mistake is here.
// Example code using ConnectionPool.
In a jsp page you can not use the import statement any where, it has to come under page directive typically the first statement.
Moreover I am not being able to make out what exactly you want to do, why so many class declarations in side a jsp page?
Ok, I think the problem is in this import , but there is one more import statement in the code, which I haven’t seen previously,
Источник
Adblock
detector
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 |
Синтаксическая ошибка в токене «пакет», ожидается импорт (Java)
Я пытаюсь импортировать java.lang.Math в Java на Eclipse и получаю сообщение об ошибке в заголовке. Вот начало моего кода:
import java.lang.Math;
package test1;
Эта ошибка появляется в разделе «package test1;»
2 ответы
Компания package
оператор должен быть первым в файле, прежде чем что-либо, даже импорт:
package hw1;
import java.lang.Math;
Кроме того, вам не нужно импортировать java.lang.Math
, или что-нибудь в java.lang
в этом отношении.
Компания JLS, глава 7 говорит:
Модуль компиляции автоматически получает доступ ко всем типам, объявленным в его пакете, а также автоматически импортирует все общедоступные типы, объявленные в предварительно определенном пакете java.lang.
Создан 20 сен.
Поместите объявление пакета перед оператором импорта
package hw1;
import java.lang.Math;
Компания import
сам оператор не нужен, так как все классы в java.lang
импортируются по умолчанию.
Читать Создание пакета
Создан 21 сен.
Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками
java
or задайте свой вопрос.
Я использую Eclipse
Version: Mars.2 Release (4.5.2)
Build id: 20160218-0600
и maven (mvn -v)
Apache Maven 3.3.3 (7994120775791599e205a5524ec3e0dfe41d4a06; 2015-04-22T13:57:37+02:00)
Maven home: C:Datenmaven
Java version: 1.8.0_60, vendor: Oracle Corporation
Java home: C:Program FilesJavajdk1.8.0_60jre
Default locale: de_DE, platform encoding: Cp1252
OS name: "windows 7", version: "6.1", arch: "amd64", family: "dos"
my% JAVA_HOME% установлен на
C:Program FilesJavajdk1.8.0_60
и моя java (java -version)
java version "1.8.0_60"
Java(TM) SE Runtime Environment (build 1.8.0_60-b27)
Java HotSpot(TM) 64-Bit Server VM (build 25.60-b23, mixed mode)
Я запускаю eclipse с -vm (версия java jdk), и я добавил внешнюю установку maven в eclipse. после того, как я импортировал проект и получил поведение strang. Некоторые классы красны в eclispe, а некоторые нет. Я проверяю с помощью javap -version, и все они скомпилированы с основной версией 52. Я создал новое рабочее пространство и получил тот же результат. очень странно. Если я открою «красный» Java-класс с eclipse и просто сохраню его, он станет нормально (без ошибок компиляции).
Я действительно не знаю, в чем проблема.
Ошибки, которые я получаю в eclipse
Syntax error on token "package", assert expected
Syntax error on token "import", throw expected
как родительский pom Я использую spring -boot-starter-parent с версией 1.3.3-RELEASE
Я также указал все свойства, которые я знаю как java.version, maven.compiler.source/target и источник сборки проекта и выходное кодирование. также попытался определить плагин компилятора maven. не помогло.
содержащий пример кода
package com.test;
public class AExample {
public static void main(String[] args) {
System.out.println(args.length);
}
}
похоже, что он полностью зависит от пакета, в который я помещал класс.
с некоторым пакетом он просто компилируется, как обычно, с некоторыми имеет следующие erros
com.test cannot be resolved to a type AExample.java line 1
Illegal modifier for the local class AExample; only abstract or final is permitted AExample.java line 3
Syntax error on token "package", assert expected AExample.java line 1
Syntax error, insert "ClassBody" to complete ClassDeclaration AExample.java line 3
The nested type AExample cannot hide an enclosing type AExample.java line 3
тот же самый класс в другом пакете не вызывал этой ошибки. только в определенном пакете. любые идеи, что я могу проверить?
13 Years Ago
why do i get this syntax error at the line shown below
package org.temp2.cod1;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.io.*;
public class Code1 {
byte[] plaintext = new byte[32]; // <<<<<<<<<<<<<<<<<<<<<<<<<< syntax error
for (int i = 0; i < 32; i++) {
plaintext[i] = (byte) (i % 16);
}
byte[] key = new byte[16];
SecureRandom r = new SecureRandom();
r.nextBytes(key);
//byte[] key = ;//... secret sequence of bytes
//byte[] dataToSend = ; //...
Cipher c = Cipher.getInstance("AES");
SecretKeySpec k = new SecretKeySpec(key, "AES");
c.init(Cipher.ENCRYPT_MODE, k);
byte[] encryptedData = c.doFinal(plaintext);
}
}
-
5
Contributors -
4
Replies -
21K
Views -
2 Years
Discussion Span -
Latest Post
10 Years Ago
Latest Post
by LaughingOtter
Recommended Answers
The reason you get a syntax error in that code is that you have an extra bracket.
Try the following code:
1. package org.temp2.cod1; 2. import java.security.*; 3. import javax.crypto.*; 4. import javax.crypto.spec.*; 5. import java.io.*; 6. 7. public class Code1 { 8. 9. 10. byte[] …
Jump to Post
All 4 Replies
13 Years Ago
The reason you get a syntax error in that code is that you have an extra bracket.
Try the following code:
1.
package org.temp2.cod1;
2.
import java.security.*;
3.
import javax.crypto.*;
4.
import javax.crypto.spec.*;
5.
import java.io.*;
6.
7.
public class Code1 {
8.
9.
10.
byte[] plaintext = new byte[32]; // <<<<<<<<<<<<<<<<<<<<<<<<<< syntax error
11.
for (int i = 0; i < 32; i++) {
12.
plaintext[i] = (byte) (i % 16);
13.
}
14.
15.
16.
17.
byte[] key = new byte[16];
18.
SecureRandom r = new SecureRandom();
19.
r.nextBytes(key);
20.
21.
22.
//byte[] key = ;//... secret sequence of bytes
23.
//byte[] dataToSend = ; //...
24.
25.
Cipher c = Cipher.getInstance("AES");
26.
SecretKeySpec k = new SecretKeySpec(key, "AES");
27.
c.init(Cipher.ENCRYPT_MODE, k);
28.
byte[] encryptedData = c.doFinal(plaintext);
29.
}
masijade
1,351
Industrious Poster
Team Colleague
Featured Poster
13 Years Ago
Nope. The real problem is that that code needs to be inside a method. You can’t simply code loops and other actions as part of the class definition, but rather as method/constructor/block definitions inside the class.
13 Years Ago
Java class construct:
public class Foo {
private String datum;
private int datum2;
private void helperMethod() { ... }
public String exposedMethod(int param) { helperMethod(); }
public void main(String[] args) { //Special method invoked when java Foo is run; }
}
You need to study the Java syntax a little more carefully, I think.
10 Years Ago
I guess I do, since masijade’s and Cronless’ answers were the right ones.
Edited
10 Years Ago
by LaughingOtter
Reply to this topic
Be a part of the DaniWeb community
We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.
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.