Illegal start of expression while using "protected"
hi all,
class pTest{
public static void main(String arg[]){
System.out.println("hi");
protected int i=10;
System.out.println(i);
}when i run this i am getting
" illegal start of expression" what's wrong here
thanQ,
Han.
thanQ i understood,
but now it is a different case where i am trying to access a protected variable to the other class but i am getting following error.
cannot make a static reference to non-static field fieldNumberbut here the first class sample code is
public class ISOField
extends ISOComponent
implements Cloneable, Externalizable
protected int fieldNumber;
protected String value;
.and my accessing class is as below
public class UJposMsgs extends ISOField {
public static void main(String arg[]) {
ISOField mkeys = new ISOField();
int fnumber = fieldNumber;
String val = value;
Similar Messages
-
Using Annotation @AttributeOverrides - Illegal start of expression
Hi Forum,
I have several classes that use the @AttributeOverrides annotation on several methods as shown in the following example:
@Embedded
@AttributeOverrides({
@AttributeOverride(name = "calendar",
column = @Column(name=COLUMN_NAME_DAY_OF_AGGREGATION,
nullable = false)),
@AttributeOverride(name = "weekday",
column = @Column(name = COLUMN_NAME_WEEKDAY,
nullable = false)),
public Day getDayOfAggregation() {
return this.dayOfAggregation;
}This prevents Java-Doc generation for these classes and the Java-Doc compiler complains:
MyClass.java:503: illegal start of expression
I am using the Java-Doc tool included in Java SDK version 1.5.0_12
Any help would be greatly appreciated.
Thanks in advance,
Henning MalzahnHello,
yeah - solved that one with Leonid - soved it by removing the trailing comma.
I thought the trailing comma was ok like it is allowed in arry definitions...
Anyway thanks again to Leonid for suggesting his great Java Doc tool. I like the flexibility and
especially the various types of output. Quite handy to be able to generate an rtf doc from the same
API using the tool. I can recommend it definitely....
Bye,
Henning -
Applet has illegal start of expression at public VNCViewer() method{ )
package viewer;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Label;
public class VNCViewer extends java.applet.Applet implements Runnable
public static final String version = "4.1";
public static final String about1 = "VNC Viewer Free Edition "+version;
public static final String about2 = "Copyright (C) 2002-2005 RealVNC Ltd.";
public static final String about3 = ("See http://www.realvnc.com for "+
"information on VNC.");
public static final String aboutText = about1+"\n"+about2+"\n"+about3;
public static void main(String[] argv) {
VNCViewer viewer = new VNCViewer(argv);
viewer.start();
public VNCViewer(String[] argv) {
applet = false;
// Override defaults with command-line options
for (int i = 0; i < argv.length; i++) {
if (argv.equalsIgnoreCase("-log")) {
if (++i >= argv.length) usage();
System.err.println("Log setting: "+argv[i]);
rfb.LogWriter.setLogParams(argv[i]);
continue;
if (rfb.Configuration.setParam(argv[i]))
continue;
if (argv[i].charAt(0) == '-') {
if (i+1 < argv.length) {
if (rfb.Configuration.setParam(argv[i].substring(1), argv[i+1])) {
i++;
continue;
usage();
if (vncServerName.getValue() != null)
usage();
vncServerName.setParam(argv[i]);
public static void usage() {
String usage = ("\nusage: vncviewer [options/parameters] "+
"[host:displayNum] [options/parameters]\n"+
//" vncviewer [options/parameters] -listen [port] "+
//"[options/parameters]\n"+
"\n"+
"Options:\n"+
" -log <level> configure logging level\n"+
"\n"+
"Parameters can be turned on with -<param> or off with "+
"-<param>=0\n"+
"Parameters which take a value can be specified as "+
"-<param> <value>\n"+
"Other valid forms are <param>=<value> -<param>=<value> "+
"--<param>=<value>\n"+
"Parameter names are case-insensitive. The parameters "+
"are:\n\n"+
rfb.Configuration.listParams());
//System.err.print(usage);
//System.exit(1);
//Illegal Start of Expression is here...
public VNCViewer() {
applet = true;
firstApplet = true;
public static void newViewer(VNCViewer oldViewer) {
VNCViewer viewer = new VNCViewer();
viewer.applet = oldViewer.applet;
viewer.firstApplet = false;
viewer.start();
public void init() {
vlog.debug("init called");
setBackground(Color.white);
logo = getImage(getDocumentBase(), "logo150x150.gif");
public void start() {
vlog.debug("start called");
nViewers++;
if (firstApplet) {
alwaysShowServerDialog.setParam(true);
rfb.Configuration.readAppletParams(this);
String host = getCodeBase().getHost();
if (vncServerName.getValue() == null && vncServerPort.getValue() != 0) {
int port = vncServerPort.getValue();
vncServerName.setParam(host + ((port >= 5900 && port <= 5999)
? (":"+(port-5900))
: ("::"+port)));
thread = new Thread(this);
thread.start();
public void paint(Graphics g) {
g.drawImage(logo, 0, 0, this);
int h = logo.getHeight(this)+20;
g.drawString(about1, 0, h);
h += g.getFontMetrics().getHeight();
g.drawString(about2, 0, h);
h += g.getFontMetrics().getHeight();
g.drawString(about3, 0, h);
public void run() {
CConn cc = null;
try {
cc = new CConn(this);
if (cc.init(null, vncServerName.getValue(),
alwaysShowServerDialog.getValue())) {
while (true)
cc.processMsg();
} catch (rdr.EndOfStream e) {
vlog.info(e.toString());
} catch (Exception e) {
if (cc != null) cc.removeWindow();
if (cc == null || !cc.shuttingDown) {
e.printStackTrace();
new MessageBox(e.toString());
if (cc != null) cc.removeWindow();
nViewers--;
if (!applet && nViewers == 0) {
System.exit(0);
rfb.BoolParameter fastCopyRect
= new rfb.BoolParameter("FastCopyRect",
"Use fast CopyRect - turn this off if you get "+
"screen corruption when copying from off-screen",
true);
rfb.BoolParameter useLocalCursor
= new rfb.BoolParameter("UseLocalCursor",
"Render the mouse cursor locally", true);
rfb.BoolParameter autoSelect
= new rfb.BoolParameter("AutoSelect",
"Auto select pixel format and encoding", true);
rfb.BoolParameter fullColour
= new rfb.BoolParameter("FullColour",
"Use full colour - otherwise 6-bit colour is used "+
"until AutoSelect decides the link is fast enough",
false);
rfb.AliasParameter fullColor
= new rfb.AliasParameter("FullColor", "Alias for FullColour", fullColour);
rfb.StringParameter preferredEncoding
= new rfb.StringParameter("PreferredEncoding",
"Preferred encoding to use (ZRLE, hextile or"+
" raw) - implies AutoSelect=0", null);
rfb.BoolParameter viewOnly
= new rfb.BoolParameter("ViewOnly", "Don't send any mouse or keyboard "+
"events to the server", false);
rfb.BoolParameter shared
= new rfb.BoolParameter("Shared", "Don't disconnect other viewers upon "+
"connection - share the desktop instead", false);
rfb.BoolParameter acceptClipboard
= new rfb.BoolParameter("AcceptClipboard",
"Accept clipboard changes from the server", true);
rfb.BoolParameter sendClipboard
= new rfb.BoolParameter("SendClipboard",
"Send clipboard changes to the server", true);
rfb.BoolParameter alwaysShowServerDialog
= new rfb.BoolParameter("AlwaysShowServerDialog",
"Always show the server dialog even if a server "+
"has been specified in an applet parameter or on "+
"the command line", false);
rfb.StringParameter vncServerName
= new rfb.StringParameter("Server",
"The VNC server <host>[:<dpyNum>] or "+
"<host>::<port>", null);
rfb.IntParameter vncServerPort
= new rfb.IntParameter("Port",
"The VNC server's port number, assuming it is on "+
"the host from which the applet was downloaded", 0);
Thread thread;
boolean applet, firstApplet;
Image logo;
Label versionLabel;Looks like you have at least two missing "}"
You have commented out one that you seem to need, right at the error. -
Error: illegal start of expression
Hi, when I compile my program, I get an error that says
"A6Q1.java:96:illegal start of expression
public static int IndexOf(int comma) "
and ^ points to the p in public.
Here is a copy of the program (CSI1100 is a class that enables the read-in from the keyboard)
import java.io.* ;
class A6Q1
public static void main (String[] args) throws IOException
// DECLARE VARIABLES/DATA DICTIONARY
String FullName; // the string with the full name
char [] NameArray; // GIVEN: an array with the full name
String Abbreviated; // RESULT: the abbreviated name
// READ IN GIVENS
System.out.println("Please enter your full name in the format shown, then press ENTER:");
System.out.println("<Family name>, <Given name 1> <Given name 2> ...");
NameArray = CSI1100.readCharLine();
// BODY OF ALGORITHM
FullName = new String( NameArray );
Abbreviated = abbreviate(FullName);
// PRINT OUT RESULTS AND MODIFIEDS
System.out.println(Abbreviated);
// Definitions for the methods used by main go here.
// METHOD: abbreviate, which will abbreviate people's names from
// <Family name>, <Given name 1> <Given name 2> ... to
// <Family name>, <Initial1>. Initial2>. ..., where the full name is given
public static String abbreviate(String FullName)
// DECLARE VARIABLES/DATA DICTIONARY
int Icomma; // the index at which the comma occurs
int Ispace; // the index at which a space occurs
String Abbreviated; // the returned result
int comma; // the unicode value of a comma
int space; // the unicode value of a space
// BODY OF ALGORITHM
comma = (int) ',';
space = (int) ' ';
Icomma = IndexOf(comma);
Abbreviated = FullName.substring(0, Icomma+1);
Ispace = Icomma + 2;
Abbreviated = Abbreviated + " " + FullName.charAt(Ispace) + ".";
Ispace = IndexOf2(space, Ispace);
while (Ispace > (-1))
if (((int) Ispace) != ((int) Ispace) + 1)
Ispace = Ispace + 1;
Abbreviated = Abbreviated + " " + FullName.charAt(Ispace) + ".";
else
Ispace = Ispace + 1;
// RETURN RESULT
return Abbreviated;
public static int IndexOf(int comma)
int Icomma; // the index at which the comma occurs
FullName.charAt(Icomma) = comma;
return Icomma;
public static int IndexOf2(int space, int Ispace)
int Icomma; // the index at which the comma occurs
int end = -1; // if there is no comma
FullName.charAt(Ispace) = space;
if (Ispace >= Icomma)
return Ispace;
else
return end; //do nothing
}}I'd guess you're missing a } somewhere in there. I'm not going to try checking, because I'm not good at matching up braces which are all aligned on the left. (Hint: in future, when posting code wrap it in [code] ).
-
How am i getting an illegal start of expression error?
Hi,
i am new to this forumn, and still fairly new to java i gues. i get an illegal start of expression in the following code at the line...
data [arrayCounter] = {fn,ln,hp,ha,hc,hs,hz};
any ideas as to why?
public class customersDatabase {
String[] columnNames = new String[10];
private Object[][] theData = new Object[1000][10];
public customersDatabase() {
String[] employeeNameArray = new String[10];
String retrieveString = "SELECT * FROM customerTable";
Statement stmt;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch(java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
try {
con = DriverManager.getConnection(url, null, null);
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(retrieveString);
int arrayCounter = 0;
while (rs.next()) {
String fn = rs.getString("FIRSTNAME");
String ln = rs.getString("LASTNAME");
String hp = rs.getString("HOMEPHONE");
String ha = rs.getString("HOMEADDRESS");
String hc = rs.getString("HOMECITY");
String hs = rs.getString("HOMESTATE");
String hz = rs.getString("HOMEZIP");
data [arrayCounter] = {fn,ln,hp,ha,hc,hs,hz};
System.out.println(fn+ln+hp+ha+hc+hs+hz);
arrayCounter ++;
stmt.close();
con.close();
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}Change it to:
data [arrayCounter] = new String[] {fn,ln,hp,ha,hc,hs,hz};(or new Object[], but I don't know why your array is declared as Object[][], anyway, if you only put Strings in it.
You can only use the initialization you used when first declaring the variable.
Also, "data" should be "theData", I think. -
Illegal start to expression - java applet
Hi Guys,
this code is for a hangman game which will be in an applet. When I try putting the buttons in init, I'm getting an "illegal start of expression" for each button. Can someone tell me what I'm doing wrong?
Cheers,
* @(#)Hangman.java
* Sample Applet application
* @author
* @version 1.00 06/10/17
import java.util.Random;
import java.util.*;
import java.awt.*;
import java.applet.*;
import java.io.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.BorderLayout;
public class Hangman extends JApplet implements ActionListener
Scanner textfile =new Scanner ("list.txt"); //file with words in
int count=0;//count number of letters in chosen word
int lives=6;//lives left
String [] list= new String [count]; //word chosen stored in array
boolean [] listDisplay=new boolean [count]; //whether letters in word have been guessed correct
String guess=null; //guess
boolean cont=false; //whether game continues or not
public void read()
try
while (textfile.hasNext()==true)
count++;
for (int i=0;i<count;i++)
String input=null;
list=input;
catch (InputMismatchException e)
System.out.println ("Mismatch exception:" + e );
public String selectWord()
int index=0;
Random ind=new Random();
String word=null;
index=ind.nextInt();
word=list[index];
return word;
public void wrongGuess(int lives)
switch (lives)
case 6:
break;
case 5:
break;
case 4:
break;
case 3:
break;
case 2:
break;
case 1:
break;
case 0:
cont=false;
public void game()
String word=null;
read();
word=selectWord();
while (cont==true)
public void check(String letter)
boolean tried=false;
for (int i=0;i<list.length;i++)
if (list[i]==letter)
listDisplay[i]=true;
else
if (tried==false)
lives--;
tried=true;//guard to stop multiple lives lost by 1 letter
public void init()
//setup buttons
private JButton jbtA=new JButton("A");
private JButton jbtB=new JButton("B");
private JButton jbtC=new JButton("C");
private JButton jbtD=new JButton("D");
private JButton jbtE=new JButton("E");
private JButton jbtF=new JButton("F");
private JButton jbtG=new JButton("G");
private JButton jbtH=new JButton("H");
private JButton jbtI=new JButton("I");
private JButton jbtJ=new JButton("J");
private JButton jbtK=new JButton("K");
private JButton jbtL=new JButton("L");
private JButton jbtM=new JButton("M");
private JButton jbtN=new JButton("N");
private JButton jbtO=new JButton("O");
private JButton jbtP=new JButton("P");
private JButton jbtQ=new JButton("Q");
private JButton jbtR=new JButton("R");
private JButton jbtS=new JButton("S");
private JButton jbtT=new JButton("T");
private JButton jbtU=new JButton("U");
private JButton jbtV=new JButton("V");
private JButton jbtW=new JButton("W");
private JButton jbtX=new JButton("X");
private JButton jbtY=new JButton("Y");
private JButton jbtZ=new JButton("Z");
JPanel p1=new JPanel();
p1.add(jbtA);
p1.add(jbtB);
p1.add(jbtC);
p1.add(jbtD);
p1.add(jbtE);
p1.add(jbtF);
p1.add(jbtG);
p1.add(jbtH);
p1.add(jbtI);
p1.add(jbtJ);
p1.add(jbtK);
p1.add(jbtL);
p1.add(jbtM);
p1.add(jbtN);
p1.add(jbtO);
p1.add(jbtP);
p1.add(jbtQ);
p1.add(jbtR);
p1.add(jbtS);
p1.add(jbtT);
p1.add(jbtU);
p1.add(jbtV);
p1.add(jbtW);
p1.add(jbtX);
p1.add(jbtY);
p1.add(jbtZ);
getContentPane().add(p1,BorderLayout.CENTER);
public void start()
game();
public void paint(Graphics g)
g.drawString("Welcome to Java!!", 50, 60 );
public void actionPerformed(ActionEvent e)
if (e.getSource()==jbtA)
check("A");
if (e.getSource()==jbtB)
check("B");
if (e.getSource()==jbtC)
check("C");
if (e.getSource()==jbtD)
check("D");
if (e.getSource()==jbtE)
check("E");
if (e.getSource()==jbtF)
check("F");
if (e.getSource()==jbtF)
check("F");
if (e.getSource()==jbtG)
check("G");
if (e.getSource()==jbtH)
check("H");
if (e.getSource()==jbtI)
check("I");
if (e.getSource()==jbtJ)
check("J");
if (e.getSource()==jbtK)
check("K");
if (e.getSource()==jbtL)
check("L");
if (e.getSource()==jbtM)
check("M");
if (e.getSource()==jbtN)
check("N");
if (e.getSource()==jbtO)
check("O");
if (e.getSource()==jbtP)
check("P");
if (e.getSource()==jbtQ)
check("Q");
if (e.getSource()==jbtR)
check("R");
if (e.getSource()==jbtS)
check("S");
if (e.getSource()==jbtT)
check("T");
if (e.getSource()==jbtU)
check("U");
if (e.getSource()==jbtV)
check("V");
if (e.getSource()==jbtW)
check("W");
if (e.getSource()==jbtX)
check("X");
if (e.getSource()==jbtY)
check("Y");
if (e.getSource()==jbtZ)
check("Z");
/code]cheers for the reply :)
I've managed to compile the file, but nothing is displayed. I'm compiling using JDK 5. Any ideas?
* @(#)Hangman.java
* Sample Applet application
* @author
* @version 1.00 06/10/17
import java.util.Random;
import java.util.*;
import java.awt.*;
import java.applet.*;
import java.io.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.BorderLayout;
public class Hangman extends JApplet implements ActionListener
Scanner textfile =new Scanner ("list.txt"); //file with words in
int count=0;//count number of letters in chosen word
int lives=6;//lives left
String [] list= new String [count]; //word chosen stored in array
boolean [] listDisplay=new boolean [count]; //whether letters in word have been guessed correct
String guess=null; //guess
boolean cont=false; //whether game continues or not
JButton jbtA;
JButton jbtB;
JButton jbtC;
JButton jbtD;
JButton jbtE;
JButton jbtF;
JButton jbtG;
JButton jbtH;
JButton jbtI;
JButton jbtJ;
JButton jbtK;
JButton jbtL;
JButton jbtM;
JButton jbtN;
JButton jbtO;
JButton jbtP;
JButton jbtQ;
JButton jbtR;
JButton jbtS;
JButton jbtT;
JButton jbtU;
JButton jbtV;
JButton jbtW;
JButton jbtX;
JButton jbtY;
JButton jbtZ;
public void read()
try
while (textfile.hasNext()==true)
count++;
for (int i=0;i<count;i++)
String input=null;
list=input;
catch (InputMismatchException e)
System.out.println ("Mismatch exception:" + e );
public String selectWord()
int index=0;
Random ind=new Random();
String word=null;
index=ind.nextInt();
word=list[index];
return word;
public void wrongGuess(int lives)
switch (lives)
case 6:
break;
case 5:
break;
case 4:
break;
case 3:
break;
case 2:
break;
case 1:
break;
case 0:
cont=false;
public void game()
String word=null;
read();
word=selectWord();
while (cont==true)
public void check(String letter)
boolean tried=false;
for (int i=0;i<list.length;i++)
if (list[i]==letter)
listDisplay[i]=true;
else
if (tried==false)
lives--;
tried=true;//guard to stop multiple lives lost by 1 letter
public void init()
//setup buttons
jbtA=new JButton("A");
jbtB=new JButton("B");
jbtC=new JButton("C");
jbtD=new JButton("D");
jbtE=new JButton("E");
jbtF=new JButton("F");
jbtG=new JButton("G");
jbtH=new JButton("H");
jbtI=new JButton("I");
jbtJ=new JButton("J");
jbtK=new JButton("K");
jbtL=new JButton("L");
jbtM=new JButton("M");
jbtN=new JButton("N");
jbtO=new JButton("O");
jbtP=new JButton("P");
jbtQ=new JButton("Q");
jbtR=new JButton("R");
jbtS=new JButton("S");
jbtT=new JButton("T");
jbtU=new JButton("U");
jbtV=new JButton("V");
jbtW=new JButton("W");
jbtX=new JButton("X");
jbtY=new JButton("Y");
jbtZ=new JButton("Z");
JPanel p1=new JPanel();
p1.add(jbtA);
p1.add(jbtB);
p1.add(jbtC);
p1.add(jbtD);
p1.add(jbtE);
p1.add(jbtF);
p1.add(jbtG);
p1.add(jbtH);
p1.add(jbtI);
p1.add(jbtJ);
p1.add(jbtK);
p1.add(jbtL);
p1.add(jbtM);
p1.add(jbtN);
p1.add(jbtO);
p1.add(jbtP);
p1.add(jbtQ);
p1.add(jbtR);
p1.add(jbtS);
p1.add(jbtT);
p1.add(jbtU);
p1.add(jbtV);
p1.add(jbtW);
p1.add(jbtX);
p1.add(jbtY);
p1.add(jbtZ);
getContentPane().add(p1,BorderLayout.CENTER);
public void start()
game();
public void paint(Graphics g)
g.drawString("Welcome to Java!!", 50, 60 );
public void actionPerformed(ActionEvent e)
if (e.getSource()==jbtA)
check("A");
if (e.getSource()==jbtB)
check("B");
if (e.getSource()==jbtC)
check("C");
if (e.getSource()==jbtD)
check("D");
if (e.getSource()==jbtE)
check("E");
if (e.getSource()==jbtF)
check("F");
if (e.getSource()==jbtF)
check("F");
if (e.getSource()==jbtG)
check("G");
if (e.getSource()==jbtH)
check("H");
if (e.getSource()==jbtI)
check("I");
if (e.getSource()==jbtJ)
check("J");
if (e.getSource()==jbtK)
check("K");
if (e.getSource()==jbtL)
check("L");
if (e.getSource()==jbtM)
check("M");
if (e.getSource()==jbtN)
check("N");
if (e.getSource()==jbtO)
check("O");
if (e.getSource()==jbtP)
check("P");
if (e.getSource()==jbtQ)
check("Q");
if (e.getSource()==jbtR)
check("R");
if (e.getSource()==jbtS)
check("S");
if (e.getSource()==jbtT)
check("T");
if (e.getSource()==jbtU)
check("U");
if (e.getSource()==jbtV)
check("V");
if (e.getSource()==jbtW)
check("W");
if (e.getSource()==jbtX)
check("X");
if (e.getSource()==jbtY)
check("Y");
if (e.getSource()==jbtZ)
check("Z"); -
need some help figuring this out. When I try to compile it says:
compile:
[mkdir] Created dir: D:\sk\hiptop-sdk\examples\clock\work\2.3\classes
[javac] Compiling 5 source files to D:\sk\hiptop-sdk\examples\clock\work\2.3
\classes
[javac] D:\sk\hiptop-sdk\examples\clock\work\2.3\source\com\loo432\clock\Mai
nWindow.java:62: illegal start of expression
[javac] public static void recieveEvent() {
[javac] ^
[javac] 1 errorHere's my code
package com.loo432.clock;
import danger.app.Application;
import danger.app.Event;
import danger.ui.Color;
import danger.ui.Font;
import danger.ui.Menu;
import danger.ui.Pen;
import danger.ui.Rect;
import danger.ui.ScreenWindow;
import danger.util.DEBUG;
* Implements the main window class.
class MainWindow
extends ScreenWindow
implements Resources, Commands {
//* -------------------- clockWindow
public MainWindow() {
//* -------------------- adjustActionMenuState
public void adjustActionMenuState(Menu hwMenu) {
//Menu hwMenu = getActionMenu();
hwMenu.removeAllItems();
hwMenu.addFromResource(Application.getCurrentApp().getResources(), ID_MENU_CLOCK, this);
//* -------------------- paint
public void paint(Pen inPen) {
Rect bounds = getBounds();
Font font = Font.findBoldSystemFont();
String message = Application.getCurrentApp().getString(ID_STRING_CLOCK);
clear(inPen);
inPen.setColor(Color.BLACK);
inPen.drawRect(bounds);
inPen.setFont(font);
inPen.drawText((bounds.getWidth() -
font.getWidth(message)) / 2,
(bounds.getHeight() -
(font.getAscent() + font.getDescent())) / 2,
message);
//* -------------------- receiveEvent
* Handles events. Called automatically whenever the application
* receives an event.
public boolean receiveEvent(Event e) {
switch (e.type) {
case EVENT_ONE:
public static void recieveEvent(String[] arguments) {
// get current time and date
Calendar now = Calendar.getInstance();
int hour = now.get(Calendar.HOUR_OF_DAY);
int minute = now.get(Calendar.MINUTE);
int month = now.get(Calendar.MONTH) + 1;
int day = now.get(Calendar.DAY_OF_MONTH);
int year = now.get(Calendar.YEAR);
// display greeting
if (hour < 12)
System.out.println("Good morning.\n");
else if (hour < 17)
System.out.println("Good afternoon.\n");
else
System.out.println("Good evening.\n");
// begin time message by showing the minutes
System.out.print("It's");
if (minute != 0) {
System.out.print(" " + minute + " ");
System.out.print( (minute != 1) ? "minutes" :
"minute");
System.out.print(" past");
// display the hour
System.out.print(" ");
System.out.print( (hour > 12) ? (hour - 12) : hour );
System.out.print(" o'clock on ");
// display the name of the month
switch (month) {
case (1):
System.out.print("January");
break;
case (2):
System.out.print("February");
break;
case (3):
System.out.print("March");
break;
case (4):
System.out.print("April");
break;
case (5):
System.out.print("May");
break;
case (6):
System.out.print("June");
break;
case (7):
System.out.print("July");
break;
case (8):
System.out.print("August");
break;
case (9):
System.out.print("September");
break;
case (10):
System.out.print("October");
break;
case (11):
System.out.print("November");
break;
case (12):
System.out.print("December");
// display the date and year
System.out.println(" " + day + ", " + year + ".");
DEBUG.p("clock: Received kCmd_One");
return true;
case EVENT_TWO:
// Todo: Insert code here...
DEBUG.p("clock: Received kCmd_Two");
return true;
return super.receiveEvent(e);
//* -------------------- eventWidgetDown
public boolean eventWidgetDown(int inWhichWidget, Event inEvent) {
switch (inWhichWidget) {
case Event.DEVICE_WHEEL:
break;
case Event.DEVICE_MULTIPLE_WHEEL:
break;
case Event.DEVICE_WHEEL_BUTTON:
break;
case Event.DEVICE_ARROW_UP:
break;
case Event.DEVICE_ARROW_DOWN:
break;
case Event.DEVICE_ARROW_LEFT:
break;
case Event.DEVICE_ARROW_RIGHT:
break;
case Event.DEVICE_BUTTON_JUMP:
// Always make sure to call super.eventWidgetUp for this control so the system
// can execute the correct behavior (returning to the Jump screen with phone selected).
break;
return super.eventWidgetDown(inWhichWidget, inEvent);
//* -------------------- eventWidgetUp
public boolean eventWidgetUp(int inWhichWidget, Event inEvent) {
switch (inWhichWidget) {
case Event.DEVICE_WHEEL:
break;
case Event.DEVICE_MULTIPLE_WHEEL:
break;
case Event.DEVICE_WHEEL_BUTTON:
break;
case Event.DEVICE_ARROW_UP:
break;
case Event.DEVICE_ARROW_DOWN:
break;
case Event.DEVICE_ARROW_LEFT:
break;
case Event.DEVICE_ARROW_RIGHT:
break;
This demonstrates how to use a control from Sidekick2 in a way that is still compatible
with original Sidekick devices. We implement the DEVICE_BUTTON_CANCEL event which is
defined in the Sidekick2Events.java file. On original Sidekick devices, this event is
never sent. On Sidekick2 devices, you will get this event and should handle it appropriately.
case Hiptop2Events.DEVICE_BUTTON_CANCEL:
Application.getCurrentApp().returnToLauncher();
return true;
case Event.DEVICE_BUTTON_BACK:
Application.getCurrentApp().returnToLauncher();
return true;
case Event.DEVICE_BUTTON_JUMP:
// Always make sure to call super.eventWidgetUp for this control so the system
// can execute the correct behavior (returning to the Jump screen with phone selected).
break;
return super.eventWidgetUp(inWhichWidget, inEvent);
}The compiler is already telling you exactly where the error is:
[javac] D:\sk\hiptop-sdk\examples\clock\work\2.3\source\com\loo432\clock\MainWindow.java:62: illegal start of expression
[javac] public static void recieveEvent() {
[javac] ^
[javac] 1 errorIt's saying that on line 62 of MainWindow.java, you have an illegal start of expression, and it's showing you exactly the line of code that's causing it.
The fix is to stop doing what you're doing, because it's not valid Java. How you do that depends on what you're trying to accomplish with that particular line of code, which is what I was asking before. -
Compile error "illegal start of expression"
ok. so i have to make methods for a scrabble calculator applet, and just can't seem to get it right. this is my code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class scrabbleScore extends JApplet
implements ActionListener
* Make a text box
private JPanel display;
private JTextField word;
private JLabel number;
private JLabel d;
String s = "Type word here, then hit Enter";
String e = "|";
String f, c = " ";
int scr = 0;
String str[] = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
int score[] = {1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 3, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10};
public void init(){
//Make text box
word = new JTextField (
"Type word here, then hit Enter", 20);
word.setBackground(Color.white);
word.setEditable(true);
word.addActionListener(this);
word.selectAll();
word.requestFocus();
//Draw the # box
number = new JLabel("# Appears here");
d = new JLabel("Letter values appear here");
//Draw the pane
Container c = getContentPane();
c.setLayout(new FlowLayout());
c.add(word);
c.add(d);
c.add(number);
public void actionPerformed(ActionEvent e){
* check if word has text
JTextField word = (JTextField)e.getSource();
String w = word.getText();
w = w.toUpperCase();
w = w.trim();
if (validateData(w) == true) {
JOptionPane.showMessageDialog(this,
"You have not entered a valid word", "Error", JOptionPane.ERROR_MESSAGE);
else {
d.setText(wordValue(w));
number.setText("|| Value = " + computeScore(w) + " ||");
Boolean validateData(String w){
while (w.compareToIgnoreCase(s) != 0) {
return false;
return true;
//Method computeScore(String word)
String computeScore(String w){
*Put word in an array
String wrd[] = new String[w.length()];
for (int i = 0; i < w.length(); i++) {
wrd[i] = w.charAt(i) + "";
for (int i = 0; i < wrd.length; i++) {
String y = wrd;
int k = y.getValue();
scr += score[k];
public int getValue(String y) {
int num = 0;
String z = str[num];
while (y.compareTo(z) != 0) {
num++;
z = str[num];
return num;
//Return v to set text
String v = scr + "";
scr = 0;
return v;
String wordValue(String w){
char wrd[] = new char[w.length()];
for (int i = 0; i < w.length(); i++) {
wrd[i] = w.charAt(i);
for (int i = 0; i < wrd.length; i++) {
int value = Character.getNumericValue(wrd[i]);
value -= 10;
String a = " " + wrd[i] + " ";
c = "|" + a + "= " + score[value] + "|";
e = e + c;
f = e + "| ==>";
c = "";
e = "|";
return f;
}and i get an "illegal start or expression" compile error at the line public int getValue(String y). Does anyone know how i could fix this?Just so you guys can see it if you want to, here's my finished code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class scrabbleScore extends JApplet
implements ActionListener
* Make a text box
private JPanel display;
private JTextField word;
private JLabel number;
private JLabel d;
String s = "Type word here, then hit Enter";
String e = "|";
String f, c = " ";
int scr = 0;
String str[] = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
int score[] = {1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 3, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10};
public void init(){
//Make text box
word = new JTextField (
"Type word here, then hit Enter", 20);
word.setBackground(Color.white);
word.setEditable(true);
word.addActionListener(this);
word.selectAll();
word.requestFocus();
//Draw the # box
number = new JLabel("# Appears here");
d = new JLabel("Letter values appear here");
//Draw the pane
Container c = getContentPane();
c.setLayout(new FlowLayout());
c.add(word);
c.add(d);
c.add(number);
public void actionPerformed(ActionEvent e){
* check if word has text
JTextField word = (JTextField)e.getSource();
String w = word.getText();
w = w.toUpperCase();
w = w.trim();
if (validateData(w) == true) {
JOptionPane.showMessageDialog(this,
"You have not entered a valid word", "Error", JOptionPane.ERROR_MESSAGE);
else {
String[] wrd = makeArray(w);
d.setText(wordValue(w, wrd));
number.setText("|| Value = " + computeScore(w, wrd) + " ||");
resetValues();
Boolean validateData(String w){
while (w.compareToIgnoreCase(s) != 0) {
return false;
return true;
//Method getValue
int getValue(String y) {
int num = 0;
String z = str[num];
while (y.compareTo(z) != 0) {
num++;
z = str[num];
return num;
//Method makeArray
String[] makeArray(String w) {
String wrd[] = new String[w.length()];
for (int i = 0; i < w.length(); i++) {
wrd[i] = w.charAt(i) + "";
return wrd;
//method makeLetterValues
String makeLetterValues(String[] wrd, int i, int value) {
String a = " " + wrd[i] + " ";
c = "|" + a + "= " + score[value] + "|";
e = e + c;
return e;
//method resetValues
void resetValues() {
c = "";
e = "|";
scr = 0;
//Method computeScore(String word)
String computeScore(String w, String[] wrd){
//get score
for (int i = 0; i < wrd.length; i++) {
String y = wrd;
int k = getValue(y);
scr += score[k];
//Return v to set text
String v = scr + "";
return v;
//method wordValue
String wordValue(String w, String[] wrd){
//make letter value string
for (int i = 0; i < wrd.length; i++) {
int value = getValue(wrd[i]);
String e = makeLetterValues(wrd, i, value);
f = e + "| ==>";
return f; -
Illegal start of expression problem
In my app I' creating an action listener to check for the click of a button, but this is my first try with an action listener and i'm having a few issues. I'll give you the part of the program that goes before where I get the error.
import javax.swing.SpringLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.Container;
import java.awt.Toolkit;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class BattleSystem implements ActionListener {
private static void createAndShowGUI() {
int number = 10;
int secondNumber = 5;
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
//Create and set up the window.
JFrame frame = new JFrame("System");
Toolkit theKit = frame.getToolkit();
Dimension wndSize = theKit.getScreenSize();
frame.setBounds(wndSize.width/4, wndSize.height/4,
wndSize.width/4, wndSize.width/4);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up the content pane.
Container contentPane = frame.getContentPane();
SpringLayout layout = new SpringLayout();
contentPane.setLayout(layout);
//Buttons
JButton attack = new JButton("Clcik here!");
attack.addActionListener(this);
//Health Labels
JLabel label = new JLabel("Number 1: " + number);
JLabel eLabel = new JLabel("Number 2: " + secondNumber);
//Handle Button Events
public void actionPerformed(ActionEvent e) {
number--;
secondNumber--;
}It gives me the error illegal start of expression at this line:
public void actionPerformed(ActionEvent e) {
How can I get this to work?
On a differnt question how can I stop the user being able to resize the application window?
Finally, can you depot Java Applications (not Applets) or do they ahve to be an applet to use them outside the compiler?where i come from we say
"this just ain't right"
but i understand that you are new to java.
if you don't understand the modifications then you will have some
problems. you need to go through the problems one by one.
the modifications fix compiler errors but that doesn't mean it will work.
I think you have had bad advice in the past. after you think about it,
then if you have specific questions, then post applicable code and
tell us what the problem is and if it is due to compiler error or
runtime exception. give appropriate output.
public class BattleSystem implements ActionListener {
private int health;//modified
private int enemyHealth;//modified
public BattleSystem(){
health = 10; //added
enemyHealth = 5;//added
private static void createAndShowGUI() {
BattleSystem bs = new BattleSystem();//added
//health = 10; deleted
//enemyHealth = 5;deleted
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
//Create and set up the window.
JFrame frame = new JFrame("Battle System");
Toolkit theKit = frame.getToolkit();
Dimension wndSize = theKit.getScreenSize();
frame.setBounds(wndSize.width/4, wndSize.height/4,
wndSize.width/4, wndSize.width/4);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Buttons
JButton attack = new JButton("Attack!");
attack.addActionListener(bs);//modified
//Health Labels
JLabel healthLabel = new JLabel("Health: " + bs.health);//modified
JLabel eHealthLabel = new JLabel("Enemy Health: " + bs.enemyHealth);//modified
//Set up the content pane.
Container contentPane = frame.getContentPane();
SpringLayout layout = new SpringLayout();
contentPane.setLayout(layout);
//Add the labels to the frame
contentPane.add(healthLabel);
contentPane.add(eHealthLabel);
contentPane.add(attack);
//Adjust constraints for the eHealthLabel so its pos is 145,0
layout.putConstraint(SpringLayout.WEST, eHealthLabel,
145,
SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.NORTH, eHealthLabel,
0,
SpringLayout.NORTH, contentPane);
//Adjust constraints for the Attack so its pos is 145,0
layout.putConstraint(SpringLayout.WEST, attack,
0,
SpringLayout.WEST, contentPane);
layout.putConstraint(SpringLayout.NORTH, attack,
25,
SpringLayout.NORTH, contentPane);
//Display the window.
frame.setVisible(true);
//Handle Button Events
public void actionPerformed(ActionEvent e) {
health--;
enemyHealth--;
public static void main(String[] args) {
//Runs the program securely and shows GUI
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
} -
Plz tell me wht is error in code.its showing illegal start of expression
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
class Image01 extends Frame{ //controlling class
Image rawImage; //ref to raw image file fetched from disk
Image modImage; //ref to modified image
int rawWidth;
int rawHeight;
int inTop; //Inset values for the container object
int inLeft;
public static void main(String[] args) {
Image01 obj = new Image01(); //instantiate this object
obj.repaint(); //render the image
} //end main
public Image01()
{ //constructor
//Get an image from the specified file in the current directory on the local hard disk.
rawImage = Toolkit.getDefaultToolkit().getImage("myco.jpeg");
MediaTracker tracker = new MediaTracker(this);
tracker.addImage(rawImage,1);
try{ //because waitForID throws InterruptedException
if(!tracker.waitForID(1,10000))
System.out.println("Load error.");
System.exit(1);
catch(InterruptedException e)
System.out.println(e); }
this.setVisible(true);//make the Frame visible
rawWidth = rawImage.getWidth(this); //Raw image has been loaded. Establish width and
rawHeight = rawImage.getHeight(this); // height of the raw image.
inTop = this.getInsets().top; //Get and store inset data for the Frame object so
inLeft = this.getInsets().left; // that it can be easily avoided.
this.setSize(800,800);
//this.setSize(inLeft+rawWidth,inTop+2*rawHeight); //Use the insets and the size of the raw image to
this.setTitle("Copyright 1997, Baldwin"); // establish the overall size of the Frame object.
this.setBackground(Color.yellow); //Make the Frame object twice the height of the
// image so that the raw image and the modified image
// can both be rendered on the Frame object.
public void handlepixels(Image rawImage,int x,int y,int rawWidth, int rawHeight)
int[] pix = new int[rawWidth * rawHeight]; //Declare an array object to receive the pixel
// representation of the image
//Convert the rawImage to numeric pixel representation
try
PixelGrabber pgObj = new PixelGrabber(rawImage,0,0,rawWidth,rawHeight,pix,0,rawWidth);
if(pgObj.grabPixels() && ((pgObj.getStatus() & ImageObserver.ALLBITS) != 0) {
for (int j = 0; j <rawHeight ; j++) {
for (int i = 0; i < rawWidth; i++) {
handlesinglepixel(x+i, y+j, pixels[j * rawWidth + i]);
//end if statement
else System.out.println("Pixel grab not successful") }
catch(InterruptedException e)
System.out.println(e); }
modImage = this.createImage(new MemoryImageSource(rawWidth,rawHeight,pix,0,rawWidth)); //Use the createImage() method to create a new image
// from the array of pixel values.s
this.addWindowListener(new WindowAdapter() //Anonymous inner-class listener to terminate program
//anonymous class definition
public void windowClosing(WindowEvent e)
System.exit(0); //terminate the program
}//end windowClosing()
} //end WindowAdapter
);//end addWindowListener
}//end constructor
//Override the paint method to display both the rawImage
// and the modImage on the same Frame object.
public void paint(Graphics g)
if(modImage != null)
g.drawImage(rawImage,inLeft+50,inTop+50,this);
g.drawImage(modImage,inLeft+50,inTop+rawHeight+100,this);
}//end if
}//end paint()
}//end Image05 class plz tell me the how to remove errorimport java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
class Image01 extends Frame
Image rawImage;
Image modImage;
int rawWidth;
int rawHeight;
int inTop;
int inLeft;
public static void main(String[] args)
Image01 obj = new Image01();
obj.repaint();
public Image01()
rawImage = Toolkit.getDefaultToolkit().getImage("myco.jpeg");.
MediaTracker tracker = new MediaTracker(this);
tracker.addImage(rawImage,1);
try
if(!tracker.waitForID(1,10000))
System.out.println("Load error.");
System.exit(1);
catch(InterruptedException e)
System.out.println(e);
this.setVisible(true);
rawWidth = rawImage.getWidth(this);
rawHeight = rawImage.getHeight(this);
inTop = this.getInsets().top;
inLeft = this.getInsets().left;
this.setSize(800,800);
public void handlesinglepixel(int x, int y, int pixel) *// this line is showing error*
int alpha = (pixel >> 24) & 0xff;
int red = (pixel >> 16) & 0xff;
int green = (pixel >> 8) & 0xff;
int blue = (pixel ) & 0xff;
public void handlepixels(Image rawImage, int x, int y, rawWidth, rawHeight)
int[] pix = new int[rawWidth * rawHeight];
try
PixelGrabber pgObj = new PixelGrabber(rawImage,0,0,rawWidth,rawHeight,pix,0,rawWidth);
if(pgObj.grabPixels() && ((pgObj.getStatus() & ImageObserver.ALLBITS) != 0))
for (int j = 0; j <rawHeight ; j++)
for (int i = 0; i < rawWidth; i++)
handlesinglepixel(x+i, y+j, pix[j * rawWidth + i]);
else System.out.println("Pixel grab not successful");
catch(InterruptedException e)
System.out.println(e);
modImage = this.createImage(new MemoryImageSource(rawWidth,rawHeight,pix,0,rawWidth));
this.addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent e)
System.exit(0);
}//end windowClosing()
} //end WindowAdapter
);//end addWindowListener
}//end constructor
public void paint(Graphics g)
if(modImage != null)
g.drawImage(rawImage,inLeft+50,inTop+50,this);
g.drawImage(modImage,inLeft+50,inTop+rawHeight+100,this);
}//end if
}//end paint()
}//end Image05 classnow i have deleted all comments & also highlighted the line which is giving error & thanks a lot to all of u who tried to solve my problem but still its showing same error illegal start of expression .if i run this program without handlesinglepixel & handlepixels method its working properly -
Help with illegal start of expression in a heap please
hello, i am new to java and i am trying to figure out how to make a heap, then remove the max element (from root), add a new element, and reheap. i don't know if i did it correctly, but the only error that i have now is illegal start of expression. please help if you can - thanks
package dataStructures;
public class MaxHeapExtended extends MaxHeap {
// NO additional data members allowed
// constructors go here
public void changeMax(Comparable c) {
// your code goes here
//I NEED TO REMOVE THE MAXIMUM ELEMENT (remove)
// if heap is empty
if (size == 0) {
return null;
//the maximum element is in position 1
Comparable maxElement = heap[1];
//initialize
Comparable lastElement = heap[size--];
//build last element from root
int currentNode = 1,
//child of currentNode
child = 2;
while (child <= size) {
// heap[child] should be larger child of currentNode
if (child < size && heap[child].compareTo(heap[child + 1]) < 0) {
child++;
//should i put lastElement in heap[currentNode]?if yes:
if (lastElement.compareTo(heap[child]) >= 0) {
break;
else {
//moves the child up a level
heap[currentNode] = heap[child];
//moves the child down a level
currentNode = child;
child *= 2;
heap[currentNode] = lastElement;
//I NEED TO ADD THE NEW ELEMENT TO REPLACE ONE THAT WENT AWAY (put)
// increase array size if necessary
if (size == heap.length - 1) {
heap = (Comparable []) ChangeArrayLength.changeLength1D
(heap, 2 * heap.length);
// find place for theElement
// currentNode starts at new leaf and moves up tree
int currentNode = ++size;
while (currentNode != 1 && heap[currentNode / 2].compareTo(theElement) < 0) {
// cannot put theElement in heap[currentNode]
heap[currentNode] = heap[currentNode / 2]; // move element down
currentNode /= 2; // move to parent
heap[currentNode] = theElement;
//I NEED TO REHEAP
heap = theHeap;
size = theSize;
// heapify
for (int root = size / 2; root >= 1; root--) {
Comparable rootElement = heap[root];
// find place to put rootElement
int child = 2 * root; // parent of child is target
// location for rootElement
while (child <= size) {
// heap[child] should be larger sibling
if (child < size && heap[child].compareTo(heap[child + 1]) < 0) {
child++;
// can we put rootElement in heap[child/2]?
if (rootElement.compareTo(heap[child]) >= 0) {
break; // yes
else {
// no
heap[child / 2] = heap[child]; // move child up
child *= 2; // move down a level
heap[child / 2] = rootElement;
public static void main(String [] args) {
/* 8
7 6
3 5 1
// test constructor and put
MaxHeapExtended h = new MaxHeapExtended(6);
h.put(new Integer(8));
h.put(new Integer(7));
h.put(new Integer(6));
h.put(new Integer(3));
h.put(new Integer(5));
h.put(new Integer(1));
System.out.println("Elements in array order were");
System.out.println(h);
h.changeMax(new Integer(4));
System.out.println("Elements in array order after change are");
System.out.println(h);
}You need to decide on a style for the code your write. A basic decision is whether to put opening { on the same line or on a new line. Right now you have both and it is nearly impossible for anyone to tell whether there are an equal number of { and }. The error message is likely caused by having an unequal number of { and }. You should also have an indentation style for blocks of code. For examplewhile (child <= size) {
if (child < size && heap[child].compareTo(heap[child + 1]) < 0) {
child++;
if (lastElement.compareTo(heap[child]) >= 0) {
break;
} else {
heap[currentNode] = heap[child];
currentNode = child;
child *= 2;
heap[currentNode] = lastElement;
} -
An illegal start of expression!
Hi, A fairly simple question. trying to call a method from the same class gives me an illegal start of expression error. Any ideas how to sort it out.
methodname(); //thats how i am calling the method.
public void methodname() //this is my method
rubbish in it
ThanksHere is the code, I cannot spot what is causing it.
//<-----------------CODE---------------------->
import java.io.*;
class TempConvert
public static void main(String args[]) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("***Temperature Convertor***");
System.out.println("to Convert from Fahrenheit to Celcius enter 1");
System.out.println("to Convert from Celcius to Fahrenheit enter 2");
String choice = in.readLine();
int Choice = Integer.parseInt(choice);
if (Choice == 1)
Celcius(); //A Call to Celcius Method
else if (Choice == 2)
Fahrenheit(); //A Call to Fahrenheit Method
else
System.out.println("You have entered an invalid number --Please try again");
//Celcius Method
public void Celcius()
System.out.print("Enter the City: ");
String city = in.readLine();
System.out.print("Enter the Temperature in Degree Fahrenheit: ");
String fahrenheit = in.readLine();
double degreeF = Integer.parseInt(fahrenheit);
double degreeC = ((degreeF* 9/5) + 32);
System.out.print("The temperature in Degree Celcius for " + city);
System.out.println(" is " + degreeC);
//Fahrenheit Method
public void Fahrenheit()
System.out.print("Enter the City: ");
String city = in.readLine();
System.out.print("Enter the Temperature in Degree Celcius: ");
String celcius = in.readLine();
double degreeC = Integer.parseInt(celcius);
double degreeF = ((degreeC - 32) * 5/9);
System.out.print("The temperature in Degree Fahrenheit for " + city);
System.out.println(" is " + degreeF);
System.out.println("***Thanks for using the Temperature Convertor!***");
System.exit(0);
//<---------------------END CODES --------------------->
Thanks -
Why "illegal start of expression" error? Please help!
Hello great java minds. Could you please tell me why I get "illegal start of expression" errors for the following headers? Thanks for your wisdom!!
Lines generating this error:
public static String getName()--and--
public static void displayResults()Here is my first class (that includes this code):
import java.io.*;
import java.util.*;
public class ProductSurvey
public static void main(String [] args)
ProductData myData = new ProdcutData();
String name = getName();
openFile();
myData.setName(name);
myData.dataRetrieve(name);
myData.updateAverages(rating1totalLow, rating2totalLow, rating3totalLow, rating1totalMed, rating2totalMed, rating3totalMed, rating1totalHigh, rating2totalHigh, rating3totalHigh, inc1total, inc2total, inc3total);
mydata.setRating2ave1lower3(rating2lower1than3, lower1than3Total);
displayResults();
public static String getName()
System.out.println("Please enter income and product info file name: ");
Scanner keyboard = new Scanner(System.in);
String name = keyboard.next();
return name;
public static void openFile();
File fileObject = new File(name);
while ((! fileObject.exists()) || ( ! fileObject.canRead()))
if( ! fileObject.exists())
System.out.println("No such file");
else
System.out.println("That file is not readable.");
System.out.println("Enter file name again:");
name = keyboard.next();
fileObject = new File(name);
public static void displayResults()
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
System.out.println("*Average (rounded) product ratings, by income bracket, are as follows: ");
System.out.println(myData.toString());
System.out.print("\n*Total number of persons in Income Bracket $50000-$74999 ");
System.out.print("that rated all three products with a score of 5 ");
System.out.println("or higher: " + myData.getHighRaters());
System.out.print("\n*Average (rounded) rating for Product 2 by ");
System.out.println("persons who rated Product 1 lower than Product 3: " + myData.rating2ave1lower3);
}Here is the backup class (just for your reference):
import java.util.*;
import java.io.*;
class ProductData
private String name;
private int lineCount;
private double inc1total;
private double inc2total;
private double inc3total;
private int rating1totalLow;
private int rating2totalLow;
private int rating3totalLow;
private int rating1totalMed;
private int rating2totalMed;
private int rating3totalMed;
private int rating1totalHigh;
private int rating2totalHigh;
private int rating3totalHigh;
private int highRaters;
private double lower1than3Total;
private int rating2lower1than3;
private long rating2ave1lower3;
private long rating1averageLow;
private long rating2averageLow;
private long rating3averageLow;
private long rating1averageMed;
private long rating2averageMed;
private long rating3averageMed;
private long rating1averageHigh;
private long rating2averageHigh;
private long rating3averageHigh;
public ProductData()
name = null;
lineCount = 0;
inc1total = 0;
inc2total = 0;
inc3total = 0;
rating1totalLow = 0;
rating2totalLow = 0;
rating3totalLow = 0;
rating1totalMed = 0;
rating2totalMed = 0;
rating3totalMed = 0;
rating1totalHigh = 0;
rating2totalHigh = 0;
rating3totalHigh = 0;
highRaters = 0;
lower1than3Total= 0;
rating2lower1than3 = 0;
rating1averageLow = 0;
rating2averageLow = 0;
rating3averageLow = 0;
rating1averageMed = 0;
rating2averageMed = 0;
rating3averageMed = 0;
rating1averageHigh = 0;
rating2averageHigh = 0;
rating3averageHigh = 0;
public void setName(String newName)
String name = newName;
public void dataRetrieve(String name)
try
BufferedReader inputStream = new BufferedReader(new FileReader(name));
String trash = "No trash yet";
while ((trash = inputStream.readLine()) !=null)
StringTokenizer st = new StringTokenizer(trash);
int income = Integer.parseInt(st.nextToken());
int rating1 = Integer.parseInt(st.nextToken());
int rating2 = Integer.parseInt(st.nextToken());
int rating3 = Integer.parseInt(st.nextToken());
if(rating1<rating3)
lower1than3Total++;
rating2lower1than3 = rating2lower1than3 + rating2;
if(income<50000)
rating1totalLow = rating1totalLow + rating1;
rating2totalLow = rating2totalLow + rating2;
rating3totalLow = rating3totalLow + rating3;
inc1total++;
else if(income<75000)
rating1totalMed = rating1totalMed + rating1;
rating2totalMed = rating2totalMed + rating2;
rating3totalMed = rating3totalMed + rating3;
inc2total++;
if((rating1>=5) && (rating2>=5) && (rating3>=5))
highRaters++;
else if(income<100000)
rating1totalHigh = rating1totalHigh + rating1;
rating2totalHigh = rating2totalHigh + rating2;
rating3totalHigh = rating3totalHigh + rating3;
inc3total++;
lineCount++;
inputStream.close();
catch(IOException e)
System.out.println("Problem reading from file.");
public void updateAverages(int rating1totalLow, int rating2totalLow, int rating3totalLow, int rating1totalMed, int rating2totalMed, int rating3totalMed, int rating1totalHigh, int rating2totalHigh, int rating3totalHigh, long inc1total, long inc2total, long inc3total)
rating1averageLow = Math.round(rating1totalLow/inc1total);
rating2averageLow = Math.round(rating2totalLow/inc1total);
rating3averageLow = Math.round(rating3totalLow/inc2total);
rating1averageMed = Math.round(rating1totalMed/inc2total);
rating2averageMed = Math.round(rating2totalMed/inc2total);
rating3averageMed = Math.round(rating3totalMed/inc2total);
rating1averageHigh = Math.round(rating1totalHigh/inc3total);
rating2averageHigh = Math.round(rating2totalHigh/inc3total);
rating3averageHigh = Math.round(rating3totalHigh/inc3total);
public long setRating2ave1lower3(int rating2lower1than3, double lower1than3Total)
long rating2ave1lower3 = (rating2lower1than3/lower1than3Total);
return rating2ave1lower3;
public String toString()
return ("\nIncome level $26000-$49999:" + "\n" + "-Product 1: "
+ rating1AverageLow + "-Product 2: " + rating2AverageLow
+ "-Product 3: " + rating3AverageLow + "\n" + "\n" + "Income level $50000-$74999:" + "\n" + "-Product 1: "
+ rating1AverageMed + "-Product 2: " + rating2AverageMed
+ "-Product 3: " + rating3AverageMed + "\n" + "\n" + "Income level $75000-$100000:" + "\n" + "-Product 1: "
+ rating1AverageHigh + "-Product 2: " + rating2AverageHigh
+ "-Product 3: " + rating3AverageHigh);
public int getHighRaters()
return highRaters;
}You're trying to define those methods inside another method (the "main" method, in this case). Don't do that.
-
ERROR MESSAGE: 20: illegal start of expression
There is something wrong with my program because I have one error and it says "illegal start of expression" and all of my parenthesis and brackets are correct what else is wrong. Here is my program:
import javax.swing.*;
import java.util.*;
public class StudentApp
public static void main(String [] args) throws NullPointerException
//declare variables and initialize
String sID, sName, sHoursStr;
int choice = 0, sHours, i;
Student aStudent = Null;
Vector sVector = new Vector();
//add objects to Vector
Vector studentVector = new Vector();
studentVector = addStudent(studentVector);
sVector.add(aStudent);
public static Vector addStudent(Vector sVector)
public static Vector addStudent(Vector sVector)
sVector.remove(aStudent);
aStudent = (Student) sVector.get(i);
sID = aStudent.getID();
aStudent = (Student) sVector.get(i);
sHours = aStudent.getHours();
//get objects from a vector and print
for(i = 0; i < sVector.size(); i++)
aStudent = (String) sVector.get(i);
System.out.println(aStudent);
//copy vector contents into an Array
String [] anArray = new String[sVector.size()];
sVector.copyInto(anArray);
for(j = 0; j < anArray.length; j++)
System.out.println(anArray[j]);
System.exit(0);
System.exit(0);
public static Student[] addStudent(Student [] anArray)
String sID = JOptionPane.showInputDialog("Enter student's ID: ");
String sName = JOptionPane.showInputDialog("Enter student's name: ");
String sHoursStr = JOptionPane.showInputDialog("Enter student's hours: ");
int sHours = Integer.parseInt(sHoursStr);
Student aStudent = new Student(sID, sName, sHours);
for(int i = 0; i < anArray.length; i++)
if(anArray.getID() == "")
anArray[i] = aStudent;
System.out.println(anArray[i]);
break;
return(anArray);
public static void addHours(Student [] anArray)
int totalHours = 0;
for(int i = 0; i < anArray.length; i++)
totalHours += anArray[i].getHours();
JOptionPane.showMessageDialog(null, "Total hours are: " + totalHours);
public static void findStudent(Student [] anArray)
String requestedID = JOptionPane.showInputDialog("Enter ID of student: ");
boolean foundIt = false;
for(int i = 0; i < anArray.length; i++)
if(anArray[i].getID().equals(requestedID))
JOptionPane.showMessageDialog(null, anArray[i]);
foundIt = true;
break;
if(!foundIt)
JOptionPane.showMessageDialog(null, "Student not found");
Could someone help me out please?import javax.swing.*;
import java.util.*;
public class StudentApp
public static void main(String [] args) throws NullPointerException
//declare variables and initialize
String sID, sName, sHoursStr;
int choice = 0, sHours, i;
Student aStudent = Null;
Vector sVector = new Vector();
//add objects to Vector
Vector studentVector = new Vector();
studentVector = addStudent(studentVector);
sVector.add(aStudent);
//get objects from a vector and print
for(i = 0; i < sVector.size(); i++)
aStudent = (String) sVector.get(i);
System.out.println(aStudent);
//copy vector contents into an Array
String [] anArray = new String[sVector.size()];
sVector.copyInto(anArray);
for(j = 0; j < anArray.length; j++)
System.out.println(anArray[j]);
for(i = 0; i < studentArray.length; i++)
studentArray[i] = new Student(); // load the array with empty data
while(choice != 4) // keep repeating the menu until 4 is selected
String instructions = "Enter\n"
+ " 1 to add a Student\n"
+ " 2 to delete a Student given the ID\n"
+ " 3 to sum and display the semester hours for all the current Students\n"
+ " 4 to quit";
String choiceStr = JOptionPane.showInputDialog(instructions);
choice = Integer.parseInt(choiceStr);
switch(choice)
case 1:
studentArray = addStudent(studentArray); // call method, send array
break;
case 2:
deleteStudent(studentArray); // call method, send array
break;
case 3:
addHours(studentArray); // call method, send array
break;
} // end switch
System.exit(0);
} // end while
System.exit(0);
public static Vector addStudent(Vector sVector)
public static Vector addStudent(Vector sVector)
sVector.remove(aStudent);
aStudent = (Student) sVector.get(i);
sID = aStudent.getID();
aStudent = (Student) sVector.get(i);
sHours = aStudent.getHours();
Vector studentVector = new Vector();
studentVector = addStudent(studentVector);
sVector.add(aStudent);
String sID = JOptionPane.showInputDialog("Enter student's ID: ");
String sName = JOptionPane.showInputDialog("Enter student's name: ");
String sHoursStr = JOptionPane.showInputDialog("Enter student's hours: ");
int sHours = Integer.parseInt(sHoursStr);
Student aStudent = new Student(sID, sName, sHours);
for(int i = 0; i < anArray.length; i++)
if(anArray.getID() == "")
anArray[i] = aStudent;
System.out.println(anArray[i]);
break;
return(anArray);
System.exit(0);
public static void deleteStudent(Student [] anArray)
String requestedID = JOptionPane.showInputDialog("Enter ID of student that you would like to delete: ");
sVector.remove(aStudent);
aStudent = (Student) sVector.get(i);
sID = aStudent.getID();
sVector.remove(aStudent);
if(!foundIt)
JOptionPane.showMessageDialog(null, "Student not found");
public static void addHours(Student [] anArray)
for(i = 0; i < sVector.get; i++)
aStudent = (Student) sVector.get(i);
sHours = aStudent.getHours();
totalHours += sHours; // add up hours
JOptionPane.showMessageDialog(null, "Total hours are: " + totalHours);
Here is my program.. can someone please fix it? -
On MacBook Pro unable to print webpage; I get a single blank page. But I can print using Safari. Started last week while using Firefox 3.6. I downloaded Firefox 5.0--same problem.
I am now able to do live broadcasts with my i-sight, but my original problem still exisits....
Unsolved Problem:I need to be able to broadcast from CamTwist as CamTwist is the only program that will allow me to do what I need to do. Justin.tv and Ustream.tv do not recognize CamTwist for reasons I can not explain.
Maybe you are looking for
-
Mac running slow after downloading fonts
ppppppppplllllllllllllllllzzzzzzzzzzzzzz help me!!!! I downloadied fonts yesterday and now my mac is running really slow!!!!! and Sims 3 wont quit so i cant turn it off!!! HELP
-
Yellow warning messages while Using cells in a query
I created a query that uses cells and in each one there is a calculation. In my rows i have a structure that contains just titles, like Plan, actual, etc. I keep getting yellow warnings saying they are not defined. It lets me run the query and the
-
Very high latency in fetching static files
Problem : Really high latency in fetching static files upon first request. Environment : Weblogic V8.1 App Server and Web Server running using jdk1.4.2_13 Mem Setting: -Xmx2048M -XX:MaxPermSize=1024M Situaton: Restart the weblogic server, fetch a sta
-
Have a region generate result of expression on data reference
within a region, is there a suggested way to generate an evaled javascript output? spry:content doesn't really do it. say i have a function makePrettyName(name) that returns a string i'd like to insert the result of makePrettyName( {dsPerson::name} )
-
Supporting Multiple OO4O Versions
Is it possible for an application to support two different versions of the OO4O C++ Class Library without having to compile two different versions of said application? We'd like our application to be able to support an 8i AND a 9i version of OO4O. Ba