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] ).
Similar Messages
-
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; -
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 -
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();
} -
Illegal start of expression error
Hi, I keep getting an illegal start of expression error at the first parentheses of the main method, and I can't find the reason why. Any hints?
import java.util.*;
import java.io.*;
import java.text.*;
public class driver
public static void main(String[] args)
private String numerator, denominator;
private Scanner inScan = new Scanner(System.in);
System.out.print("Enter a numerator: ");
numerator = inScan.nextLine(); //get numerator
System.out.print("Enter a denominator: ");
denominator = inScan.nextLine(); //get denominator
EgyptianFraction fraction = new EgyptianFraction(numerator,denominator);
}String numerator, numerator;
Scanner inScan = new Scanner(System.in);Variables numerator, numerator and inScan are local variable, so there is no private modifer.
Suggestion: name your class Driver. There is a widely held coding convention that classes should start with a capital letter. -
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? -
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. -
Easy Question: Illegal Start of Expression
This is a ridiculously easy question... but I am having trouble with it...
Anyway, here is the line of code that is giving me trouble:
jButtons = {{jButton1, jButton5, jButton9, jButton13},
{jButton2, jButton6, jButton10, jButton14},
{jButton3, jButton7, jButton11, jButton15},
{jButton4, jButton8, jButton12, jButton16}};
That's it. jButton1 through jButton16 are all jButton objects (for a GUI). jButtons is an array (4 by 4) of jButton. All are global variables, the buttons are all initilized (in fact, that was the problem I had before, and why I need to put this here: otherwise I get a null pointer exception).
Surprisingly, such a simple line of code causes TONS of errors to occur. To save space, {...} * 2 means that the exception occurs twice in a row, errors are separated by comma's.
{ Illegal Start of Expression, {Not a statement, ; required} * 2} * 4, Empty statement
A similar statement (int[] test = {{1,2,3},{4,5,6}};) works perfectly fine.
Please help, doing this will reduce the size of my code to about a third of the size of the code. And then I can laugh in the faces of those people who say that I write long, and in-efficient code! MWHAHAHAHAHAHA!!
However, I will keep at it, and Murphy's Law states I will find a solution 10 seconds after posting. If I do, I will edit this post, and tell you guys the answer ;)
[Edit]In case you are wondering... all my other code is correct. Here is the adjacent 3 methods:
private void jButton16ActionPerformed(java.awt.event.ActionEvent evt) {
ButtonClick(3,3);
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton10;
private javax.swing.JButton jButton11;
private javax.swing.JButton jButton12;
private javax.swing.JButton jButton13;
private javax.swing.JButton jButton14;
private javax.swing.JButton jButton15;
private javax.swing.JButton jButton16;
private javax.swing.JButton jButton17;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JButton jButton5;
private javax.swing.JButton jButton6;
private javax.swing.JButton jButton7;
private javax.swing.JButton jButton8;
private javax.swing.JButton jButton9;
private javax.swing.JLabel jLabel1;
// End of variables declaration
* @param args the command line arguments
public static void main(String args[])
jButtons = {{jButton1, jButton5, jButton9, jButton13},
{jButton2, jButton6, jButton10, jButton14},
{jButton3, jButton7, jButton11, jButton15},
{jButton4, jButton8, jButton12, jButton16}};
int[][] test = {{1,2,3},{4,5,6}};
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new GameWindow().setVisible(true);
String[] row1 = {"1", "5", "9", "13"};
String[] row2 = {"2", "6", "10", "14"};
String[] row3 = {"3", "7", "11", "15"};
String[] row4 = {"4", "8", "12", ""};
String[][] labels = {row1, row2, row3, row4};
int blankX = 3;
int blankY = 3;
static javax.swing.JButton[][] jButtons;
private void DisableAll()
for (int looperX = 0; looperX < 4; looperX++)
for (int looperY = 0; looperY < 4; looperY++)
jButtons[looperX][looperY].setEnabled(false);
Edited by: circularSquare on Oct 13, 2008 5:49 PM
Edited by: circularSquare on Oct 13, 2008 5:52 PMYou can only initialise an array like that when you declare it at the same time. Otherwise you have to do as suggested above.
int[] numbers = {1,2,3,4}; //ok
int[] numbers;
numbers = {1,2,3,4}; // not ok -
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. -
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. -
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;
} -
Illegal start of expression, request.getParameter
Hello,
I added the following to my jsp page
<% String username = request.getParameter("username"); %>and an error pops up saying "illegal start of expression", am I missing something?
Thanks
EDIT: Problem solved, other code was causing the problem ;)
Edited by: KyleG on Dec 17, 2008 3:18 AMimport java.util.*;
* Write a description of class PhoneCompany here.
* @author (your name)
* @version (a version number or a date)
public class PhoneCompany
private ArrayList<Account> accounts;
private ArrayList<TextMessage> textMessages;
private int collectRevenues;
* Constructor for objects of class PhoneCompany
public PhoneCompany()
accounts = new ArrayList<Account>();
textMessages = new ArrayList<TextMessage>();
collectRevenues = 0;
public void readAccounts(String fileName)
String[] lines = LineIO.readAllLines (fileName);
for (String line : lines)
String [] a = line.split("&");
if(line.startsWith("p")) {
PrepaidAccount p = new PrepaidAccount(a[1], a[2], a[3], Integer.parseInt(a[4]), 30);
accounts.add(p);
if(line.startsWith("c")) {
ContractAccount c = new ContractAccount(a[1], a[2], a[3], Integer.parseInt(a[5]), Integer.parseInt(a[6]), a[4]);
accounts.add(c);
System.out.println(line);
public void readTextMessages(String fileName)
String[] lines = LineIO.readAllLines (fileName);
for (String line : lines)
String [] b = line.split("&");
TextMessage theTxtMsg = new TextMessage(b[1], b[2], b[3], b[4]);
System.out.print(line);
public int collectRevenues()
int total = 0;
for (Account a: accounts)
total += a.collectRevenue();
System.out.print(total);
return total;
} -
Illegal start of expression erro
I'm getting at error at line 20 of my code. The error is illegal start of expression. I can't seem to find the error, if someone could go through my code. It's small. Thank you
public class FootballPlayer {
// setting up variables
private int height, weight;
private String firstName, lastName, position;
// creating constructor
public FootballPlayer() {
this.height = height;
this.weight = weight;
this.firstName = firstName;
this.lastName = lastName;
this.position = position;
// error is on the next line...
public String toString() {
return "<Player Information: [" + firstName + ", " + lastName + "], position: [" + position + "], height: [" + height + "], weight: [" + weight + "]>";
}You constructor needs a closing }.
Also, you are assigning variables to themselves in the constructor, since you do not have an argument list. However, this is not causing your error, it is just useless code.
� {� -
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
Maybe you are looking for
-
Hard Drive Failed - iPod synced with previous iTunes Library - HELP!
The hard drive on our Dell laptop recently failed. We had to replace it and completely reinstall the operating system, which wiped out everything, including iTunes. All of our music currently resides on our iPod (thousands of songs!). After reinstall
-
Internal pdf links not working in chrome and firefox
I have some PDF files that I am adding links to additional PDF files that are located in the same folder on our webserver using Acrobat Pro XI. The links work fine in IE and the other PDF files open up and display well in the IE browser, but the link
-
We have just purchased CC for teams and cannot update PS CC to 14.1
I have tried everything for both mac and PC and nothing seems to work. This is really disappointing. I have been trying since last week and still not working as of today. Can somebody please help and get us to this new update.
-
OSB to RestFul with Custom Header and Authentication
I am trying to add to OSB a RestFul service which requires authentication and custom http headers. I am able to register the RestFul service as Business Service with following parameter - Service Type: Messaging Service - Request Message Type: None -
-
Adding Text To A Background Image
Hi, I'm still very new to Dreamweaver, and would appreciate your insight. I've attached an image for reference. Green is for the banner/menu bar. In Photoshop, I sliced up a banner/background image combo, saved for web/devices, and imported it onto a