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
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();
}
}
}
%>
- Статус темы:
-
Закрыта.
-
В этой сфере я новичок, прибавьте мозгов по этой теме мне, пожалуйста.
1 Logger log = Logger.getLogger(«Minecraft»);
2 public void onEnable() {
3 getServer().getPluginManager().registerEvents(this, this);
4 getCommand(«inform»).setExecutor(new Commands(this));Ругается eclpse на 3-ю строчку с комментарием: «Syntax error on tokens, delete this tokens»
Строчку не подчёркивает, а помечает номер строчки крестиком. -
Slavkaa
Активный участник
Пользователь- Баллы:
- 76
- Имя в Minecraft:
- Slavok2001
Попробуй
Bukkit.getPluginManager…. -
Slavkaa
Активный участник
Пользователь- Баллы:
- 76
- Имя в Minecraft:
- Slavok2001
Что-то мне подсказывает, что у тебя скобок не хватает. Ну или лишние.
-
package ru;
import java.util.logging.Handler;
import java.util.logging.Logger;import org.bukkit.Bukkit;
import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;public class main extends JavaPlugin implements Listener {
Logger log = Logger.getLogger(«Minecraft»);
public void onEnable() {
getServer().getPluginManager().registerEvents(this, this);
getCommand(«inform»).setExecutor(new Commands(this));
getLogger().info(«on»);
}
public void onDisable() {
getLogger().info(«on»);}}
-
Slavkaa
Активный участник
Пользователь- Баллы:
- 76
- Имя в Minecraft:
- Slavok2001
Чет я не вижу, чтобы ошибка выделялась.
-
Обрезал случайно, напротив строчки стоит крестик с ошибкой «Syntax error on tokens, delete this tokens»
getServer().getPluginManager().registerEvents(this, this) -
Консолька
-
DonDays
Активный участник
Пользователь- Баллы:
- 96
- Имя в Minecraft:
- DonDays
лол, а разница?
скинь все содержимое файла
-
HunterGaming
Активный участник
Пользователь- Баллы:
- 96
- Имя в Minecraft:
- sqdFendy
Очевидно же, что у него либо где-то скобки нет либо лишняя
-
Cool_boy
Активный участник
Пользователь- Баллы:
- 96
- Имя в Minecraft:
- prettydude
Кто-то ещё берёт логера не через Bukkit.getLogger()? Или на какую версию ты пишешь?
-
DonDays
Активный участник
Пользователь- Баллы:
- 96
- Имя в Minecraft:
- DonDays
-
LuckyZeeRo
Активный участник
Пользователь- Баллы:
- 96
- Имя в Minecraft:
- i0xHeX
Можешь кинуть код нормально? А то мы как бы не экстрасенсы.
-
А так я полностью там и кинул, 10 строк.
-
Cool_boy
Активный участник
Пользователь- Баллы:
- 96
- Имя в Minecraft:
- prettydude
-
LuckyZeeRo
Активный участник
Пользователь- Баллы:
- 96
- Имя в Minecraft:
- i0xHeX
А сори, не увидел в дальнейших постах.
Скопипастил твой код — никаких ошибок. Значит дело скорее в эклипсе.
У меня такое было когда то (что есть ошибка там, где ее быть не может), помогло пересоздание проекта.
В общем у тебя вары: Пересоздать проект, Пересоздать проект в новой папке (рабочем пространстве), Переустановить эклипс (поставить там оксиген, думаю он более стабилен).Простейший выход из проблемы это закрыть проект, перезапустить эклипс и опять открыть проект. Все выше, если это не поможет.
-
Ну если ошибка в eclipse, то ошибок в консоли возникать-же не должно?
В консоли та же ошибка, что и в eclipse. Кодинг — не моё.[19:52:57 ERROR]: Error occurred while enabling TestPlugin (Is it up to date?)
java.lang.Error: Unresolved compilation problem:
Syntax error on tokens, delete these tokens -
LuckyZeeRo
Активный участник
Пользователь- Баллы:
- 96
- Имя в Minecraft:
- i0xHeX
Ошибка в консоли это ошибка, которую скомпилил сам эклипс.
-
xDark
Активный участник
Пользовательошибка компиляции, дятел.
лол че?
- Статус темы:
-
Закрыта.
Поделиться этой страницей
I have a JAVA project that has code in it to start but no code in the two classes it gives you. I am new to JAVA and really need help on this. I added my code to the Treasure class and now I am getting: Syntax error on tokens, delete these tokens and Syntax error, insert «;» to complete BlockStatements. Why am I getting these errors? What did I miss?
Here is the already Java code:
package mythical.controllers; import java.text.NumberFormat; import mythical.model.Treasure; public class TreasureDemo { private Treasure largeTreasure; private Treasure smallTreasure; private NumberFormat currencyFormatter; public TreasureDemo() { this.largeTreasure = new Treasure(105); this.smallTreasure = new Treasure(10); this.currencyFormatter = NumberFormat.getCurrencyInstance(); } public void testTreasure() { this.describeTreasure2("New large treasure", this.largeTreasure, 105, 25452.0); this.describeTreasure2("New small treasure", this.smallTreasure, 10, 2424.0); System.out.println(); System.out.println("~~~~ The treasures get found ~~~~"); this.largeTreasure.getsFound(); this.smallTreasure.getsFound(); System.out.println(); this.describeTreasure2("Found large treasure", this.largeTreasure, 0, 0.0); this.describeTreasure2("Found small treasure", this.smallTreasure, 0, 0.0); System.out.println(); } public void describeTreasure2(String message, Treasure theTreasure, int expectedWeight, double expectedValue) { System.out.println(message); System.out.println("tExpected weight: t" + expectedWeight); System.out.println("tActual weight: tt" + theTreasure.getWeight()); System.out.println("tExpected value: t" + this.currencyFormatter.format(expectedValue)); System.out.println("tActual value: tt" + this.currencyFormatter.format(theTreasure.getValue())); System.out.println(); } }
Here is the Class:
package mythical.model; public class Treasure { private int theTreasure; private int largeTreasure; private int smallTreasure; public Treasure() { this.theTreasure = 0; this.largeTreasure = 0; this.smallTreasure = 0; } public Treasure(int largeTreasure){ this.largeTreasure = largeTreasure; } public void getLargeTreasure(){ this.largeTreasure = this.largeTreasure + 105; } public void getSmallTreasure(){ this.smallTreasure = this.smallTreasure + 10; } public int getWeight(){ return this.largeTreasure; } public double getValue(){ return this.largeTreasure * 242.40; } public int getsFound(){ return this.largeTreasure; } public int expectedWeight(){ return this.largeTreasure + 105; } } } }
Please help me.
What I have tried:
I have tried different ways to start the constructor but no luck. New to JAVA.
We do not do your homework: it is set for a reason. It is there so that you think about what you have been told, and try to understand it. It is also there so that your tutor can identify areas where you are weak, and focus more attention on remedial action.
So start by re-reading your course notes and / or the book so far. The information you need will be there — and you will learn this basic stuff a lot better by working it out for yourself than by being given a «solution» with no context.
Try it yourself, you may find it is not as difficult as you think!
If you meet a specific problem, then please ask about that and we will do our best to help. But we aren’t going to do it all for you!
I found out what I did wrong within my code. Here is the corrected code.
public class Treasure { private int theTreasure; private int largeTreasure; private int smallTreasure; public Treasure(){ this.theTreasure = 0; this.largeTreasure = 0; this.smallTreasure = 0; } public Treasure(int largeTreasure){ this.largeTreasure = largeTreasure; } public void getLargeTreasure(){ this.largeTreasure = this.largeTreasure + 105; } public void getSmallTreasure(){ this.smallTreasure = this.smallTreasure + 10; } public int getWeight(){ return this.largeTreasure; } public double getValue(){ return this.largeTreasure * 242.40; } public int getsFound(){ return this.largeTreasure; } public int expectedWeight(){ return this.largeTreasure + 105; } }
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
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!