Here is my code that has been giving the problems.
package ca.rhinoza.game;
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Dimension;
import javax.swing.JFrame;
public boolean running = false;
public class Game extends Canvas implements Runnable {
private static final long serialVersionUID = 1L;
public static final int WIDTH = 160;
public static final int HEIGHT = WIDTH / 12 * 9;
public static final int SCALE = 3;
public static final String NAME = "Game";
private JFrame frame;
public Game(){
setMinimumSize(new Dimension(WIDTH*SCALE, HEIGHT*SCALE));
setMaximumSize(new Dimension(WIDTH*SCALE, HEIGHT*SCALE));
setPreferredSize(new Dimension(WIDTH*SCALE, HEIGHT*SCALE));
frame = new JFrame(NAME);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(this, BorderLayout.CENTER);
frame.pack();
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public synchronized void start(){
new Thread(this).start();
}
public synchronized void stop(){
}
public void run() {
}
public static void main(String[] args){
new Game().start();
}
}
I have no idea why it is doing this.
Edit:
I edited as per your request to see more code.
user2314737
26.2k18 gold badges100 silver badges111 bronze badges
asked Jul 8, 2013 at 22:42
3
You are declaring a field outside of the class:
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Dimension;
import javax.swing.JFrame;
public boolean running = false; /// <=============== invalid location
public class Game extends Canvas implements Runnable { // <==== class starts here
private static final long serialVersionUID = 1L;
public static final int WIDTH = 160;
public static final int HEIGHT = WIDTH / 12 * 9;
public static final int SCALE = 3;
public static final String NAME = "Game";
...
It must be placed inside a class:
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Dimension;
import javax.swing.JFrame;
public class Game extends Canvas implements Runnable { // <==== class starts here
public boolean running = false; /// <=============== valid location
private static final long serialVersionUID = 1L;
public static final int WIDTH = 160;
public static final int HEIGHT = WIDTH / 12 * 9;
public static final int SCALE = 3;
public static final String NAME = "Game";
...
answered Jul 8, 2013 at 22:50
acdcjunioracdcjunior
130k36 gold badges331 silver badges303 bronze badges
1
You put
public boolean running = false;
outside of a class definition, effectively in the global namespace. But there are no globals in Java. This is not legal.
I’ll say, that’s a strange error message for that though. I would expect a little more from the compiler. Something to the effect of class
or interface
or enum
because once you start the statement with public
there are exactly three legal things that can follow. But, it is what it is. So, the compiler is right to complain, I just would have expected a more informative error message.
answered Jul 8, 2013 at 22:50
jasonjason
234k34 gold badges421 silver badges524 bronze badges
The answer is probably staring me in the face but I am unsure as to why I am receiving this error. I am receiving Syntax error on token «System» in my if
else
statements at the bottom of my code. All lines similar to line 131 onwards are receiving the error. Any help would be greatly appreciated.
Complete code so far;
import java.io.*;
import java.lang.*;
import java.util.*;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Assignment3 {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new FileReader("AssistantHoursAndRates.txt"));
double UnitRM1;
System.out.println("Enter recommended maximum staff cost of Unit 1");
UnitRM1 = console.nextDouble ();
System.out.println("Recommended maximum staff cost of Unit1 = "+UnitRM1);
System.out.printf("%10sn", " ");
double UnitRM2;
System.out.println("Enter recommended maximum staff cost of Unit 2");
UnitRM2 = console.nextDouble ();
System.out.println("Recommended maximum staff cost of Unit2 = "+UnitRM2);
System.out.printf("%10sn", " ");
double UnitRM3;
System.out.println("Enter recommended maximum staff cost of Unit 3");
UnitRM3 = console.nextDouble ();
System.out.println("Recommended maximum staff cost of Unit3 = "+UnitRM3);
System.out.printf("%10sn", " ");
double UnitRM4;
System.out.println("Enter recommended maximum staff cost of Unit 4");
UnitRM4 = console.nextDouble ();
System.out.println("Recommended maximum staff cost of Unit4 = "+UnitRM4);
System.out.printf("%10sn", " ");
double UnitRM5;
System.out.println("Enter recommended maximum staff cost of Unit 5");
UnitRM5 = console.nextDouble ();
System.out.println("Recommended maximum staff cost of Unit5 = "+UnitRM5);
System.out.printf("%10sn", " ");
double UnitRM6;
System.out.println("Enter recommended maximum staff cost of Unit 6");
UnitRM6 = console.nextDouble ();
System.out.println("Recommended maximum staff cost of Unit6 = "+UnitRM6);
System.out.printf("%10sn", " ");
double UnitRM7;
System.out.println("Enter recommended maximum staff cost of Unit 7");
UnitRM7 = console.nextDouble ();
System.out.println("Recommended maximum staff cost of Unit7 = "+UnitRM7);
System.out.printf("%10sn", " ");
double UnitRM8;
System.out.println("Enter recommended maximum staff cost of Unit 8");
UnitRM8 = console.nextDouble ();
System.out.println("Recommended maximum staff cost of Unit8 = "+UnitRM8);
System.out.printf("%10sn", " ");
double UnitRM9;
System.out.println("Enter recommended maximum staff cost of Unit 9");
UnitRM9 = console.nextDouble ();
System.out.println("Recommended maximum staff cost of Unit9 = "+UnitRM9);
double[] totals = new double[9];
int unit = 1;
while (input.hasNextLine()) {
String line = input.nextLine();
System.out.println(line);
double total = 0;
int assistants = input.nextInt();
System.out.println("Number of Assistants " + assistants);
System.out.println("Hours Rate");
System.out.println("------------");
for (int i = 0; i < assistants; i++) {
int hours = input.nextInt();
System.out.print(hours + " ");
double rate = input.nextDouble();
System.out.println(rate);
total += (hours * rate);
}
System.out.println("Total cost of Unit " + unit + " is " + total);
System.out.println();
totals[unit - 1] = total;
unit++;
if (input.hasNextLine()) {
input.nextLine();
input.next();
}
}
System.out.println("Comparisons are as follows;");
String fileName = "results.txt";
try {
PrintWriter outputStream = new PrintWriter(fileName);
if (UnitRM1 < totals[0])
outputStream.println(totals[0])
System.out.println("Unit 1 total staff cost is less than recommended maximum staff cost!");
else
System.out.println("Unit 1 total staff cost is more than recommended maximum staff cost!");
if (UnitRM2 < totals[1])
outputStream.println(totals[1])
System.out.println("Unit 2 total staff cost is less than recommended maximum staff cost!");
else
System.out.println("Unit 2 total staff cost is more than recommended maximum staff cost!");
if (UnitRM3 < totals[2])
outputStream.println(totals[2])
System.out.println("Unit 3 total staff cost is less than recommended maximum staff cost!");
else
System.out.println("Unit 3 total staff cost is more than recommended maximum staff cost!");
if (UnitRM4 < totals[3])
outputStream.println(totals[3])
System.out.println("Unit 4 total staff cost is less than recommended maximum staff cost!");
else
System.out.println("Unit 4 total staff cost is more than recommended maximum staff cost!");
if (UnitRM5 < totals[4])
outputStream.println(totals[4])
System.out.println("Unit 5 total staff cost is less than recommended maximum staff cost!");
else
System.out.println("Unit 5 total staff cost is more than recommended maximum staff cost!");
if (UnitRM6 < totals[5])
outputStream.println(totals[5])
System.out.println("Unit 6 total staff cost is less than recommended maximum staff cost!");
else
System.out.println("Unit 6 total staff cost is more than recommended maximum staff cost!");
if (UnitRM7 < totals[6])
outputStream.println(totals[6])
System.out.println("Unit 7 total staff cost is less than recommended maximum staff cost!");
else
System.out.println("Unit 7 total staff cost is more than recommended maximum staff cost!");
if (UnitRM8 < totals[7])
outputStream.println(totals[7])
System.out.println("Unit 8 total staff cost is less than recommended maximum staff cost!");
else
System.out.println("Unit 8 total staff cost is more than recommended maximum staff cost!");
if (UnitRM9 < totals[8])
outputStream.println(totals[8])
System.out.println("Unit 9 total staff cost is less than recommended maximum staff cost!");
else
System.out.println("Unit 9 total staff cost is more than recommended maximum staff cost!");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Errors are as follows;
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Syntax error on token "System", delete this token
out cannot be resolved or is not a field
Syntax error on token "System", delete this token
out cannot be resolved or is not a field
Syntax error on token "System", delete this token
out cannot be resolved or is not a field
Syntax error on token "System", delete this token
out cannot be resolved or is not a field
Syntax error on token "System", delete this token
out cannot be resolved or is not a field
Syntax error on token "System", delete this token
out cannot be resolved or is not a field
Syntax error on token "System", delete this token
out cannot be resolved or is not a field
Syntax error on token "System", delete this token
out cannot be resolved or is not a field
Syntax error on token "System", delete this token
out cannot be resolved or is not a field
at Assignment3.main(Assignment3.java:131)
Line 131 is;
System.out.println("Unit 1 total staff cost is less than recommended maximum staff cost!");
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!
THE CODE:
<%@ page import=»javax.naming.*,java.sql.*,java.io.*,java.lang.*,java.text.*,java.util.*»%>
<%
public class ConnectionPool implements Runnable
{
private int m_InitialConnectionCount = 5; // Number of initial connections to make.
private Vector m_AvailableConnections = new Vector();// A list of available connections for use.
private Vector m_UsedConnections = new Vector();// A list of connections being used currently.
private String m_URLString = null;// The URL string used to connect to the database
private String m_UserName = null; // The username used to connect to the database
private String m_Password = null;// The password used to connect to the database
private Thread m_CleanupThread = null;// The cleanup thread
//Constructor
public ConnectionPool(String urlString, String user, String passwd) throws SQLException
{
// Initialize the required parameters
m_URLString = urlString;
m_UserName = user;
m_Password = passwd;
for(int cnt=0; cnt<m_InitialConnectionCount; cnt++)
{
m_AvailableConnections.addElement(getConnection());// Add a new connection to the available list.
}
// Create the cleanup thread
m_CleanupThread = new Thread(this);
m_CleanupThread.start();
}
private Connection getConnection() throws SQLException
{
return DriverManager.getConnection(m_URLString, m_UserName, m_Password);
}
public synchronized Connection checkout() throws SQLException
{
Connection newConnxn = null;
if(m_AvailableConnections.size() == 0)
{
newConnxn = getConnection();// Im out of connections. Create one more.
m_UsedConnections.addElement(newConnxn);// Add this connection to the «Used» list.
// We dont have to do anything else since this is
// a new connection.
}
else
{
// Connections exist !
newConnxn = (Connection)m_AvailableConnections.lastElement();// Get a connection object
m_AvailableConnections.removeElement(newConnxn);// Remove it from the available list.
m_UsedConnections.addElement(newConnxn); // Add it to the used list.
}
return newConnxn;// Either way, we should have a connection object now.
}
public synchronized void checkin(Connection c)
{
if(c != null)
{
m_UsedConnections.removeElement(c);// Remove from used list.
m_AvailableConnections.addElement(c); // Add to the available list
}
}
public int availableCount()
{
return m_AvailableConnections.size();
}
public void run()
{
try
{
while(true)
{
synchronized(this)
{
while(m_AvailableConnections.size() > 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.
import java.sql.*;
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];
for(int i=0; i<connArr.length;i++)
{
connArr[i] = cp.checkout();
out.print(«Checking out…» + connArr[i]);
out.print(«Available Connections … » + cp.availableCount());
}
for(int i=0; i><connArr.length;i++)
{
cp.checkin(connArr[i]);
out.print(«Checked in…» + connArr[i]);
out.print(«Available Connections … » + cp.availableCount());
}
}
catch(SQLException sqle)
{
sqle.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
%>
sashacui 0 / 0 / 0 Регистрация: 27.07.2022 Сообщений: 16 |
||||
1 |
||||
27.07.2022, 18:53. Показов 850. Ответов 4 Метки нет (Все метки)
только начал изучение java. решил написать простейший конвертер валюты.
__________________
0 |
Folian 1702 / 1102 / 337 Регистрация: 25.01.2019 Сообщений: 2,890 |
||||
27.07.2022, 19:43 |
2 |
|||
Тут? У тебя блок if закончился, else не последовало, пошли другие инструкции.
Syntax error on token «else», delete this token. К чему этот else привязывать-то? Добавлено через 4 минуты
1 |
0 / 0 / 0 Регистрация: 27.07.2022 Сообщений: 16 |
|
27.07.2022, 19:47 [ТС] |
3 |
уже сам с этим разобрался — спасибо! но вот второй вопрос остается открытым — почему он не хочет никак воспринимать второе условие, которое не равно рублю? при любых условиях выдает рубль. Добавлено через 19 секунд
0 |
Нарушитель 14042 / 8230 / 2485 Регистрация: 21.10.2017 Сообщений: 19,708 |
|
27.07.2022, 20:09 |
4 |
0 |
Folian 1702 / 1102 / 337 Регистрация: 25.01.2019 Сообщений: 2,890 |
||||
27.07.2022, 20:17 |
5 |
|||
Сообщение было отмечено sashacui как решение Решение
почему он не хочет
+ сюда почитай,
0 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
27.07.2022, 20:17 |
Помогаю со студенческими работами здесь Parse error: syntax error, unexpected token «public» Ошибка There was an error parsing the query. [ Token line number = 1,Token line offset = 43,Token in error = записи ] using System; Ошибка при разборе запроса. [ Token line number = 1,Token line offset = 26,Token in error = Наименование ] Ошибка компиляции «parse error before `>>’ token» using namespace std; int… Ошибка syntax error before `(‘ token Ошибка «Parse error before token» Работа с файлами и ошибка Syntax error before `{‘ token говорит здесь ошибка: Искать еще темы с ответами Или воспользуйтесь поиском по форуму: 5 |
Содержание
- Syntax error on token «Invalid Character», delete this token
- 11 Answers
- Syntax Error On Token Invalid Character Delete This Token
- java — Syntax error on token “Invalid Character”, delete .
- Syntax error on token “Invalid Character”, delete this .
- Java: syntax error on token “else”, delete this token
- java — Syntax error on token «else», delete this — Stack .
- java — Syntax error on tokens — Stack Overflow
- 关于Syntax error on tokens, delete these tokens错误,大家帮帮 …
- Syntax Error On Token Invalid Character Delete This Token Fixes & Solutions
- Синтаксическая ошибка токена «Недопустимый символ», удалите этот токен.
- 11 ответы
- How do I solve the problem:Syntax error on tokens, delete these tokens?
Syntax error on token «Invalid Character», delete this token
I am not sure why is it giving this error. Braces seem to be right. Another thing is that the same program works in Windows-eclipse but not in eclipse for Mac. What could be the reason?
11 Answers
Ah, ok — it’s probably a control-Z or other unprintable character at the end of the file that is ignored in Windows but not on the Mac. You copied the source from Windows to the Mac. Delete the last few characters and re-enter them — I think it will go away. I don’t do Mac, though — I’m just guessing.
I had the same problem importing my projects from mac to linux Slackware. Mac OSX creates some temporary files with the same name of the files in folders (._filename) in all folders. Usually these files are invisible in Mac OSX, but in the other OSs no. Eclipse can find these files and tries to handle like sources (._filename.java). I solved deleting these files.
Only way i could resolve this problem was press Ctrl+A to select all text of file then Ctrl+C to copy them then delete file and create new class with intellij idea then Ctrl+P to paste text in new file. this resolve my problem and compiler never show error after do this solution.
It can happen when we copy and paste .It happens when there may be some character which is unrecognized in one platform but recognized in other.
I would suggest don’t copy rather try to write the entire code by yourself. It should work
I got the same error when I imported a project I created in a Mac, to Windows. As @Massimo says Mac creates ._filename,java files which eclipse running in windows consider as source files. This is what causes the problem.
They are hidden files, which you can see when you select the option, «Show hidden files and folders» under folder options in Windows machine. Deleting these files solves the problem.
Источник
Syntax Error On Token Invalid Character Delete This Token
We have collected for you the most relevant information on Syntax Error On Token Invalid Character Delete This Token, as well as possible solutions to this problem. Take a look at the links provided and find the solution that works. Other people have encountered Syntax Error On Token Invalid Character Delete This Token before you, so use the ready-made solutions.
java — Syntax error on token “Invalid Character”, delete .
- https://stackoverflow.com/questions/33360800/syntax-error-on-token-invalid-character-delete-this-token
- Is it only telling you the line the problem is on, or the exact character it considers invalid? Have you edited this file on another system or in another editor at some point, or pasted the contents in from elsewhere? – nitind Oct 27 ’15 at 6:06
Syntax error on token “Invalid Character”, delete this .
- https://izziswift.com/syntax-error-on-token-invalid-character-delete-this-token/
- Dec 26, 2020 · There are probably hidden characters in the line. If you move your cursor through the characters and your cursor doesn’t move in one character, that means there is an invalid character in the line. Delete those and it should work. Also try copying and pasting the line to an hex editor and you will see the invalid characters in it. Solution no. 8:
Java: syntax error on token “else”, delete this token
- http://chronicles.blog.ryanrampersad.com/2012/02/java-syntax-error-on-token-else-delete-this-token/
- Before school ended, I donated some of my time to helping out the Intro to Java kids. In that class, I realized that when you tell beginning programmers “End each line with a semi-colon,” they think you really mean it. As in, every single line with actual code (e.g. not brackets) must end with a semi-colon.
java — Syntax error on token «else», delete this — Stack .
- https://stackoverflow.com/questions/18185023/syntax-error-on-token-else-delete-this
- The problem is in the code you provided on your paste bin. You use two else statements, so Java complains as it doesn’t know which to go to after the initial if statement.
java — Syntax error on tokens — Stack Overflow
- https://stackoverflow.com/questions/20702050/syntax-error-on-tokens
- The statement precedence.put(«+», 2); has to be within a method or a block.. For example, you can place it within the constructor. public stringCalculator() < precedence.put(«+», 2); >Not related to the problem you have, classes need to start with a capital letter, according to the Java Naming Conventions
关于Syntax error on tokens, delete these tokens错误,大家帮帮 …
- https://bbs.csdn.net/topics/330145823
- Mar 19, 2011 · 我жЇз…§зќЂй©¬еЈ«е…µиЂЃеё€зљ„视频写的,可жЇе‡єзЋ°дє†иї™д№€е¤љй”™иЇЇ
Syntax Error On Token Invalid Character Delete This Token Fixes & Solutions
We are confident that the above descriptions of Syntax Error On Token Invalid Character Delete This Token and how to fix it will be useful to you. If you have another solution to Syntax Error On Token Invalid Character Delete This Token or some notes on the existing ways to solve it, then please drop us an email.
Источник
Синтаксическая ошибка токена «Недопустимый символ», удалите этот токен.
Я не уверен, почему он выдает эту ошибку. Подтяжки кажутся правильными. Другое дело, что эта же программа работает в Windows-eclipse, но не в eclipse для Mac. Что может быть причиной?
@Richa в вашем коде всего 29 строк — Eng.Fouad
11 ответы
Ах, ладно — это, вероятно, Control-Z или другой непечатаемый символ в конце файла, который игнорируется в Windows, но не на Mac. Вы скопировали исходный код из Windows на Mac. Удалите несколько последних символов и введите их заново — думаю, это уйдет. Но я не занимаюсь Mac — я просто догадываюсь.
ответ дан 20 авг.
Вы также должны иметь возможность преобразовать разделители строк (что, как я подозреваю, является реальной проблемой) из меню «Файл». — нитинд
@nitind, будут ли сообщаться о проблемах с разделителями строк как в строке после последней строки в файле? Я ожидал увидеть их в строке 1 или 2. Неужели та же настройка незаметно убирает и другие вещи? — Эд Стауб
Возможно, сложно предположить, где он мог бы сообщить о проблеме. Все, что делает это действие, — это преобразование разделителей строк — все, что оно очищает, очищается только потому, что разделители строк были изменены. — нитинд
Я получил эту ошибку, когда в моем JSP попал обратный апостроф (`). Вы также можете использовать функцию Notepad ++ «Показать все символы», чтобы увидеть символы, которые не отображаются. — Филип Рего
У меня была такая же проблема с импортом моих проектов с Mac на Linux Slackware. Mac OSX создает временные файлы с тем же именем, что и файлы в папках (._filename) во всех папках. Обычно эти файлы невидимы в Mac OSX, но в других ОС их нет. Eclipse может найти эти файлы и пытается работать с исходными кодами (._filename.java). Я решил удалить эти файлы.
Единственный способ решить эту проблему — нажать Ctrl + A, чтобы выделить весь текст файла, затем Ctrl + C, чтобы скопировать их, затем удалить файл и создать новый класс с помощью intellij idea, затем Ctrl + P, чтобы вставить текст в новый файл. это решает мою проблему, и компилятор никогда не показывает ошибку после этого решения.
ответ дан 21 дек ’14, 10:12
Это может произойти, когда мы копируем и вставляем. Это происходит, когда может быть какой-то символ, который не распознается на одной платформе, но распознается на другой.
Я бы посоветовал не копировать, а попытаться написать весь код самостоятельно. Он должен работать
У меня такая же ошибка, когда я импортировал проект, созданный на Mac, в Windows. Как говорит @Massimo, Mac создает ._filename, java файлы, которые eclipse запущены в Windows, считаются исходными. Вот в чем проблема.
Это скрытые файлы, которые можно увидеть, выбрав параметр «Показать скрытые файлы и папки» в параметрах папок на компьютере с Windows. Удаление этих файлов решает проблему.
Создан 02 июля ’15, 20:07
Я получил это сообщение при попытке вызвать подзадание из компонента tRunJob. В tRunJob я как проверил «передать весь контекст», так и перечислил отдельные параметры в поле параметров / значений. Как только я удалил дополнительные параметры, все заработало.
ответ дан 17 авг.
Вероятно, в строке есть скрытые символы. Если вы перемещаете курсор между символами, а ваш курсор не перемещается на один символ, это означает, что в строке есть недопустимый символ. Удалите их, и он должен работать. Также попробуйте скопировать и вставить строку в шестнадцатеричный редактор, и вы увидите в нем недопустимые символы.
Я много раз сталкивался с этой проблемой во время затмения. Я обнаружил, что выделите весь код — вырежьте его, используя Ctrl + x, а затем сохраните файл и снова вставьте код, используя Ctrl + V. У меня это работает много раз, когда я копирую код из другого редактора.
ответ дан 01 мар ’19, в 05:03
Какие-либо конкретные причины, по которым это работает для вас? — Entpnerd
Я также столкнулся с аналогичной проблемой при копировании кода с одной машины на другую.
Проблема была с пробелом, вам нужно было только идентифицировать красную метку в вашем коде затмения.
ответ дан 17 окт ’19, 09:10
В Windows, если вы скопируете исходный код в Блокнот — сохраните файл (как угодно), убедившись, что выбрана кодировка ASCI — символ будет преобразован в вопросительный знак, который вы затем можете удалить, а затем скопируйте код обратно в Eclipse.
ответ дан 24 апр.
В eclipse щелкните правой кнопкой мыши файл -> Свойства -> ресурсы. В кодировке текстового файла выберите US-ASCII.
Таким образом, вы увидите все специальные символы, затем вы сможете найти и заменить, а затем отформатировать код
Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками java eclipse macos syntax-error or задайте свой вопрос.
Источник
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,
Источник
Did you know that in Java’s standard library, there are a total of more than 500 different exceptions! There lots of ways for programmers to make mistakes — each of them unique and complex. Luckily we’ve taken the time to unwrap the meaning behind many of these errors, so you can spend less time debugging and more time coding. To begin with, let’s have a look at the syntax errors!
Syntax Errors
If you just started programming in Java, then syntax errors are the first problems you’ll meet! You can think of syntax as grammer in English. No joke, syntax errors might look minimal or simple to bust, but you need a lot of practice and consistency to learn to write error-free code. It doesn’t require a lot of math to fix these, syntax just defines the language rules. For further pertinent information, you may refer to java syntax articles.
Working with semicolons (;)
Think of semi-colons (;) in Java as you think of a full-stop (.) in English. A full stop tells readers the message a sentence is trying to convey is over. A semi-colon in code indicates the instruction for that line is over. Forgetting to add semi-colons (;) at the end of code is a common mistake beginners make. Let’s look at a basic example.
This snippet will produce the following error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Syntax error, insert ";" to complete BlockStatements
at topJavaErrors.JavaErrors.main(JavaErrors.java:3)
You can resolve this error by adding a ; at the end of line 3.
String x = "A";
Braces or parentheses [(), {}]
Initially, it can be hard keeping a track of the starting / closing parenthesis or braces. Luckily IDEs are here to help. IDE stands for integrated development environment, and it’s a place you can write and run code. Replit for example, is an IDE. Most IDEs have IntelliSense, which is auto-complete for programmers, and will add closing brackets and parentheses for you. Despite the assistance, mistakes happen. Here’s a quick example of how you can put an extra closing bracket or miss the ending brace to mess up your code.
If you try to execute this, you’ll get the following error.
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Syntax error on token ")", delete this token
at topJavaErrors.SyntaxErrors.main(SyntaxErrors.java:11)
You can resolve this exception by removing the extra )
on line 9.
Output
My full name is: Justin Delaware
Double Quotes or Quotation Marks (“ ”)
Another pit fall is forgetting quotation marks not escaping them propperly. The IntelliSense can rescue you if you forget the remaining double quotes. If you try including quotation marks inside strings, Java will get confused. Strings are indicated using quotation marks, so having quotation marks in a string will make Java think the string ended early. To fix this, add a backslash () before quotation marks in strings. The backslash tells Java that this string should not be included in the syntax.
Output
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Syntax error on token "Java", instanceof expected
The preview feature Instanceof Pattern is only available with source level 13 and above
is cannot be resolved to a type
Syntax error, insert ")" to complete MethodInvocation
Syntax error, insert ";" to complete Statement
The method favourtie(String) is undefined for the type SyntaxErrors
Syntax error on token "language", ( expected
at topJavaErrors.SyntaxErrors.main(SyntaxErrors.java:5)
In order for you avoid such exceptions, you can add backslahes to the quotes in the string on line 4.
Output
What did Justin say?
Justin said, "Java is my favourite language"
Here’s your required output, nicely put with double quotes!
Other Miscellaneous Errors
Accessing the “Un-Initialized” Variables
If you’re learning Java and have experience with other programming languages (like C++) then you might have a habit of using un-initialized variables (esp integers). Un-initialized variables are declared variables without a value. Java regulates this and doesn’t allow using a variable that has not been initialized yet.
If you attempt to access an uninitialized variable then you’ll get the following exception.
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The local variable contactNumber may not have been initialized
at topJavaErrors.UninitialziedVars.main(UninitialziedVars.java:5)
You can initialize the variable “contactNumber” to resolve this exception.
int contactNumber = 9935856;
Accessing the “Out of Scope” Variables
If you define a variable in a certain method you’re only allowed to access that in the defined scope of it. Like each state has their legitimate currency, and that cannot be used in another state. You cannot use GBP in place of USD in America. Similarly, a variable defined in one method has restricted scope to it. You cannot access a local variable defined in some function in the main method. For further detailed illustration let’s look at an example.
Output
As soon as you run this snippet, you’ll get the exception
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
country cannot be resolved to a variable
at topJavaErrors.OutOfScopeVars.main(OutOfScopeVars.java:9)
You can not access the variable “country” outside the method getPersonalDetails since its scope is local.
Modifying the “CONSTANT” Values
Java and other programming languages don’t allow you to update or modify constant variables. You can use the keyword “final” before a variable to make it constant in Java. Apart from that, it’s a convention to write a constant in ALL CAPS for distinction purposes, As a constant resource is often used cross methods across a program.
Output
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The final field ConstVals.SSN cannot be assigned
at topJavaErrors.ConstVals.main(ConstVals.java:5)
Remove line 4 for the perfectly functional code.
Misinterpretted Use of Operators ( == vs .equals())
A lot of beginners start working with integers while learning the basics of a programming language. So it can be a challenge to remember that for string comparisons we use the “.equals()” method provided by Java and not == operator like in integers.
Output
It's not a Wednesday!
It's a Wednesday!
The output is contradictory because “today” and “thirdWeekDay” are referred to 2 different objects in the memory. However, the method “.equals()” compares the content stored in both arrays and returns true if it’s equal, false otherwise.
Accessing a non-static resource from a static method
If you want to access a non-static variable from a static method [let’s say the main method] then you need to create an instance of that object first. But if you fail to do that, java will get angry.
Output
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Cannot make a static reference to the non-static field postalCode
at topJavaErrors.NonStaticAccess.main(NonStaticAccess.java:17)
You can fix it, just by replacing line 9.
// Accessing the non-static member variable
// by creating an instance of the object
System.out.println("What's the postal code of your area? " + address.postalCode);
Conclusion
Programming errors are a part of the learning curve. Frequent errors might slow you down. But as a new programmer, it’s okay to learn things slowly. Now you’re familiar with some of the most common issues. Make sure you practise enough to get ahead of them. Happy coding and keep practising!