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.
Similar Messages
-
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. -
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. -
Adobe Acrobat 9.0 Pro crashes at start up: Runtime Error-please help
I have Adobe CS4 installed on my Windows 7 PC. In addition, I have Adobe Reader XI and InDesign 6 installed. If I remember correctly, after I installed Adobe Reader XI, I uninstalled the version of the Reader which came with CS4.
So here’s my problem: When I try to download a PDF that has been sent to me in an email or open one that already exists on my computer, this happens:
Runtime Error!
Program: C…
The application has requested the Runtime to terminate it in an unusual way.
When I click OK, I get this:
Adobe Acrobat 9.0 has stopped working.
If I try to Adobe Acrobat 9.0 Pro from my start menu, the same thing happens.
This makes no sense to me because
I don’t have the knowledge to figure this out. I have no idea what Runtime is.
Prior to a computer meltdown a couple of months ago and a complete reinstallation of everything, these very same programs all worked just fine.
I don’t understand why, when I try to open an emailed PDF, they don’t automatically open in Adobe Reader XI rather than Adobe Acrobat. Isn’t the general idea that people be able to open and view sent PDFs which they have been sent, which is what the Reader is for, and not usually edit them, which is what Adobe Acrobat is for?
If, instead of trying to open the emailed PDFs, I save them to my computer, I can launch Adobe Reader XI and open them from within that program without any problem. That’s OK if I just need to view the PDF, but I need to be able to edit PDFs too, so I must get Adobe Acrobat 9.0 to work.
Would reinstalling Adobe Acrobat 9.0 Pro help? Is there a way to reinstall that program only from the installation disks or would have to reinstall CS4 entirely?
I cannot open Adobe Acrobat 9.0 at all, so any solutions which must be done with the program open are not possible.
I would really appreciate some help.SOLVED!
Resetting Internet Explorer didn't work, Reinstalling Acrobat 9.0 Pro didn't work, but changing a registry key did.
Here's where I found the solution:
Microsoft Visual C++ Runtime Library error opening PDF files - Microsoft Community
Here is the relevant post, but before you try it, read my note below:
Hi,
This is known issue with Acrobat for several versions now, Adobe's current fix is just to update their software: http://kb2.adobe.com/cps/404/kb404597.html
The problem is with the application data being misdirected.
"The affected user has a redirected Application Data folder and as a result the network path containing the Application Data uses a UNC path that begins with \\. This UNC path causes Acrobat 9.0 or Adobe Reader 9.0 to incorrectly parse the Application Data path and give the error message."
A potential Solution would be to go into the registry. Left Click type "regedit" and right click and run the program with "run as administrator". Go to Hkey_Current_User\Software\Microsoft\Windows\Current Version\Explorer\User Shell Folders and make sure see where "AppData" is pointing. If it is pointing to "%UserProfile%/Application Data" change it to point to "%UserProfile%/AppData/Roaming".
BUT, be careful about one thing: This poster seems to have accidentally used forward slashes when he should have use back slashes. Look at the very last line of his post where he advises "If it is pointing to "%UserProfile%/Application Data" change it to point to "%UserProfile%/AppData/Roaming". You'll find, or at least I did, that this key has a back slash, not a forward slash, so changing what I found: "%UserProfile%\Application Data" to "%UserProfile%\AppData\Roaming" worked and now Acrobat 9.0 works fine. -
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 -
Invalid start of expression error
This is my first post, so I hope this is the right section.
I am trying to do an if statement to check for a flush in my poker game and I am getting an "Illegal start of expression " error.
Here is the loop:
for (int i = 0; i < numPlayers; i++)
if ((bestHands[0].getSuit() == bestHands[i][1].getSuit())&&(bestHands[i][0].getSuit() == bestHands[i][2].getSuit()) && (bestHands[i][0].getSuit()) == bestHands[i][3].getSuit()) && (bestHands[i][0].getSuit() == bestHands[i][4].getSuit())
flush = true;
Any help would be appreciatedYea, I did.
Here is the fixed code:
for (int i = 0; i < numPlayers; i++)
if ((bestHands[0].getSuit() == bestHands[i][1].getSuit())&&(bestHands[i][0].getSuit() == bestHands[i][2].getSuit()) && (bestHands[i][0].getSuit() == bestHands[i][3].getSuit()) && (bestHands[i][0].getSuit() == bestHands[i][4].getSuit()))
flush = true; -
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;
} -
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? -
Illegal start of expression and cannot resolve symbol HELP
Can someone pls help me?
These are the two problems:
--------------------Configuration: j2sdk1.4.1_02 <Default>--------------------
C:\Documents and Settings\Laila\My Documents\CMT2080\Coursework\Game\Mindboggler.java:291: illegal start of expression
public void inputJButtonActionPerformed( ActionEvent event )
^
C:\Documents and Settings\Laila\My Documents\CMT2080\Coursework\Game\Mindboggler.java:285: cannot resolve symbol
symbol: method inputJButtonActionPerformed (java.awt.event.ActionEvent)
inputJButtonActionPerformed( event);
Here is my code :
//Mind boggler quiz
//Marcelyn Samson
import java.awt.*;
import java.awt.event.*;
import java.text.DecimalFormat;
import javax.swing.*;
import javax.swing.border.*;
import java.lang.*;
public class Mindboggler extends JFrame
// JPanel for welcome window
private JPanel welcomeJPanel;
private JPanel presetJPanel;
private JLabel titleJLabel;
private JLabel quizJLabel;
private JLabel girlJLabel, headJLabel;
private JLabel introJLabel;
private JButton startJButton;
// JPanel for questionone window
private JPanel questiononeJPanel;
private JLabel textJLabel;
private JPanel becksJPanel;
private JButton oneJButton, twoJButton, threeJButton, fourJButton, nextJButton;
//JPanel for questiontwo window
private JPanel questiontwoJPanel;
private JPanel orlandoJPanel;
private JLabel q2JLabel;
private JCheckBox lordJCheckBox;
private JCheckBox faceJCheckBox;
private JCheckBox piratesJCheckBox;
private JButton next2JButton;
private JButton inputJButton;
//JPanel for questionthree
private JPanel questionthreeJPanel;
private JPanel howmuchJPanel;
private JLabel howmuchJLabel;
private JLabel nameJLabel;
private JTextField nameJTextField;
private JLabel moneyJLabel;
private JTextField moneyJTextField;
private JButton next3JButton;
//Publics
public JPanel welcomeJFrame, questionJFrame, questiontwoJFrame, questionthreeJFrame;
//contentPane
public Container contentPane;
//no argument constructor
public Mindboggler()
createUserInterface();
//create and position components
private void createUserInterface()/////////////////////////; semo colon do not edit copy paste
//get contentPane and set layout to null
contentPane = getContentPane();
contentPane.setLayout ( null );
welcome();
//set properties of applications window
setTitle( "Mindboggler" ); // set JFrame's title bar string
setSize( 600, 400 ); // set width and height of JFrame
setVisible( true ); // display JFrame on screen
} // end method createUserInterface
public void welcome(){
// set up welcomeJPanel
welcomeJPanel = new JPanel();
welcomeJPanel.setLayout( null );
welcomeJPanel.setBounds(0, 0, 600, 400);
welcomeJPanel.setBackground( Color.GREEN );
// set up textJLabel
titleJLabel = new JLabel();
titleJLabel.setText( "Mind Boggler" );
titleJLabel.setLocation( 30, 10);
titleJLabel.setSize( 550, 70);
titleJLabel.setFont( new Font( "SansSerif", Font.PLAIN, 30 ) );
titleJLabel.setHorizontalAlignment( JLabel.CENTER );
welcomeJPanel.add( titleJLabel );
// set up presetJPanel
presetJPanel = new JPanel();
presetJPanel.setLayout( null );
presetJPanel.setBounds( 150, 10, 300, 80 );
presetJPanel.setBackground( Color.GRAY );
welcomeJPanel.add( presetJPanel );
//setup Intro JLabel
introJLabel = new JLabel();
introJLabel.setText( "Think, think, think. Can you get all the questions right?" );
introJLabel.setBounds( 40, 100, 500, 200 );
introJLabel.setFont( new Font( "SansSerif", Font.PLAIN, 18 ) );
introJLabel.setHorizontalAlignment( JLabel.CENTER );
welcomeJPanel.add(introJLabel);
//set up head JLabel
headJLabel = new JLabel();
headJLabel.setIcon( new ImageIcon( "head.jpeg") );
headJLabel.setBounds( 540, 5, 40, 160 );
headJLabel.setHorizontalAlignment( JLabel.CENTER );
welcomeJPanel.add(headJLabel);
//setup girlJLabel
girlJLabel = new JLabel();
girlJLabel.setIcon( new ImageIcon( "girl.Jjpeg") );
girlJLabel.setBounds( 5, 10, 60, 100 );
girlJLabel.setHorizontalAlignment( JLabel.CENTER );
welcomeJPanel.add(girlJLabel);
//set up startJbutton
startJButton = new JButton();
startJButton.setText( "Start" );
startJButton.setBounds(250, 300, 100, 30);
startJButton.setFont( new Font( "SansSerif", Font.BOLD, 14) );
welcomeJPanel.add(startJButton);
contentPane.add(welcomeJPanel);
startJButton.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
question();
public void question()
//set up question one JPanel
welcomeJPanel.setVisible(false);
questiononeJPanel = new JPanel();
questiononeJPanel.setLayout( null );
questiononeJPanel.setBounds(0, 0, 600,400);
questiononeJPanel.setBackground( Color.GREEN );
// set up textJLabel
textJLabel = new JLabel();
textJLabel.setText( "Who did Beckham supposedly cheat with?" );
textJLabel.setLocation( 20, 20);
textJLabel.setSize( 550, 70);
textJLabel.setFont( new Font( "SansSerif", Font.BOLD, 20 ) );
textJLabel.setHorizontalAlignment( JLabel.CENTER );
questiononeJPanel.add( textJLabel );
// set up presetJPanel
becksJPanel = new JPanel();
becksJPanel.setLayout( null );
becksJPanel.setBorder( new TitledBorder(
"Question 1" ) );
becksJPanel.setBounds( 10, 10, 570, 80 );
becksJPanel.setBackground( Color.GRAY );
questiononeJPanel.add( becksJPanel );
// set up oneJButton
oneJButton = new JButton();
oneJButton.setBounds( 10, 120, 300, 40 );
oneJButton.setText( "Britney Spears" );
oneJButton.setBackground( Color.ORANGE );
questiononeJPanel.add( oneJButton );
// set up twoJButton
twoJButton = new JButton();
twoJButton.setBounds( 10, 180, 300, 40 );
twoJButton.setText( "Meg Ryan" );
twoJButton.setBackground( Color.ORANGE );
questiononeJPanel.add( twoJButton );
// set up threeJButton
threeJButton = new JButton();
threeJButton.setBounds( 10, 240, 300, 40 );
threeJButton.setText( "Rebecca Loos" );
threeJButton.setBackground( Color.ORANGE );
questiononeJPanel.add( threeJButton );
// set up fourJButton
fourJButton = new JButton();
fourJButton.setBounds( 10, 300, 300, 40 );
fourJButton.setText( "Angelina Jolie" );
fourJButton.setBackground( Color.ORANGE );
questiononeJPanel.add( fourJButton );
// set up nextJButton
nextJButton = new JButton();
nextJButton.setBounds ( 375, 300, 150, 40 );
nextJButton.setText("Next");
nextJButton.setBackground( Color.GRAY );
questiononeJPanel.add( nextJButton );
contentPane.add(questiononeJPanel);
nextJButton.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
questiontwo();
public void questiontwo()
//set up question two JPanel
questiononeJPanel.setVisible(false);
questiontwoJPanel=new JPanel();
questiontwoJPanel.setLayout(null);
questiontwoJPanel.setBounds(0, 0, 600, 400);
questiontwoJPanel.setBackground( Color.GREEN );
// set up q2JLabel
q2JLabel = new JLabel();
q2JLabel.setBounds( 20, 20, 550, 70 );
q2JLabel.setText( "What films has Orlando Bloom starred in?" );
q2JLabel.setFont(new Font( "SansSerif", Font.BOLD, 20 ) );
q2JLabel.setHorizontalAlignment( JLabel.CENTER );
questiontwoJPanel.add(q2JLabel);
//set up orlandoJPanel
orlandoJPanel = new JPanel();
orlandoJPanel.setLayout(null);
orlandoJPanel.setBorder( new TitledBorder("Question 2"));
orlandoJPanel.setBounds( 10, 10, 570, 80);
orlandoJPanel.setBackground(Color.GRAY);
questiontwoJPanel.add(orlandoJPanel);
// set up lordJCheckBox
lordJCheckBox = new JCheckBox();
lordJCheckBox.setBounds( 16, 112, 200, 24 );
lordJCheckBox.setText( "1. Lord of The Rings" );
questiontwoJPanel.add( lordJCheckBox );
// set up faceJCheckBox
faceJCheckBox = new JCheckBox();
faceJCheckBox.setBounds( 16, 159, 200, 24 );
faceJCheckBox.setText( "2. Face Off" );
questiontwoJPanel.add( faceJCheckBox );
// set up piratesJCheckBox
piratesJCheckBox = new JCheckBox();
piratesJCheckBox.setBounds( 16, 206, 200, 24 );
piratesJCheckBox.setText( "3. Pirates of The Caribean" );
questiontwoJPanel.add( piratesJCheckBox );
// set up inputJButton
inputJButton = new JButton();
inputJButton.setBounds(20, 256, 200, 21 );
inputJButton.setText( "Input answer" );
questiontwoJPanel.add( inputJButton );
inputJButton.addActionListener(
new ActionListener()
//event handler called when user clicks inputJButton
public void actionPerformed( ActionEvent event )
inputJButtonActionPerformed( event);
//show JOptionMessages when user clicks on JCheckBoxes and inputJButton
public void inputJButtonActionPerformed( ActionEvent event )
//display error message if no JCheckBoxes is checked
if ( ( !lordJCheckBox.isSelected() && !faceJCheckBox.isSelected() && !piratesJCheckBox.isSelected() ) )
//display error message
JOptionPane.showMessageDialog( null, "Please check two boxes", JOptionPane.ERROR_MESSAGE );
// if lordjcheckbox and pirates is selected = right
else
if ( ( lordJCheckBox.isSelected() && piratesJCheckBox.isSelected() ))
JOptionPane.showMessageDialog(null, "Thats RIGHT!");
//if others are selected = wrong
else
if ( (lordJCheckBox.isSelected() && faceJCheckBox.isSelected() ))
JOptionPane.showMessageDialog(null, "Thats WRONG");
else
( (faceJCheckBox.isSelected() && piratesJCheckBox.isSelected() ))
JOptionPane.showMessageDialog(null, "Thats WRONG");
// set up nest2JButton
next2JButton = new JButton();
next2JButton.setBounds( 155, 296, 94, 24 );
next2JButton.setText( "Next" );
questiontwoJPanel.add( next2JButton );
contentPane.add(questiontwoJPanel);
next2JButton.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
questionthree();
} // end questiontwo
public void questionthree()
//setup questionthree JPanel
questiontwoJPanel.setVisible(false);
questionthreeJPanel = new JPanel();
questionthreeJPanel.setLayout(null);
questionthreeJPanel.setBounds(0, 0, 600, 400);
questionthreeJPanel.setBackground( Color.GREEN);
// main method
public static void main( String[] args )
Mindboggler application = new Mindboggler();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
} // end method main
}// end class
WOULD BE VERY GEATFULJust want to say thank you by the way for trying to help. Ive moved public void inputJButtonActionPerformed( ActionEvent event ) outside of brackets. Now i have a different problem on it. Sorry about this.
PROBLEM: --------------------Configuration: <Default>--------------------
C:\Documents and Settings\Laila\My Documents\CMT2080\Coursework\Game\Mindboggler.java:353: 'else' without 'if'
else ( ( !lordJCheckBox.isSelected() && !faceJCheckBox.isSelected && !piratesJCheckBox.isSelected() ) )
^
1 error
Process completed.
MY CODE:
//Mind boggler quiz
//Marcelyn Samson
import java.awt.*;
import java.awt.event.*;
import java.text.DecimalFormat;
import javax.swing.*;
import javax.swing.border.*;
import java.lang.*;
public class Mindboggler extends JFrame
// JPanel for welcome window
private JPanel welcomeJPanel;
private JPanel presetJPanel;
private JLabel titleJLabel;
private JLabel quizJLabel;
private JLabel girlJLabel, headJLabel;
private JLabel introJLabel;
private JButton startJButton;
// JPanel for questionone window
private JPanel questiononeJPanel;
private JLabel textJLabel;
private JPanel becksJPanel;
private JButton oneJButton, twoJButton, threeJButton, fourJButton, nextJButton;
//JPanel for questiontwo window
private JPanel questiontwoJPanel;
private JPanel orlandoJPanel;
private JLabel q2JLabel;
private JCheckBox lordJCheckBox;
private JCheckBox faceJCheckBox;
private JCheckBox piratesJCheckBox;
private JButton next2JButton;
private JButton inputJButton;
//JPanel for questionthree
private JPanel questionthreeJPanel;
private JPanel howmuchJPanel;
private JLabel howmuchJLabel;
private JLabel nameJLabel;
private JTextField nameJTextField;
private JLabel moneyJLabel;
private JTextField moneyJTextField;
private JButton next3JButton;
//Publics
public JPanel welcomeJFrame, questionJFrame, questiontwoJFrame, questionthreeJFrame;
//contentPane
public Container contentPane;
//no argument constructor
public Mindboggler()
createUserInterface();
//create and position components
private void createUserInterface()/////////////////////////; semo colon do not edit copy paste
//get contentPane and set layout to null
contentPane = getContentPane();
contentPane.setLayout ( null );
welcome();
//set properties of applications window
setTitle( "Mindboggler" ); // set JFrame's title bar string
setSize( 600, 400 ); // set width and height of JFrame
setVisible( true ); // display JFrame on screen
} // end method createUserInterface
public void welcome(){
// set up welcomeJPanel
welcomeJPanel = new JPanel();
welcomeJPanel.setLayout( null );
welcomeJPanel.setBounds(0, 0, 600, 400);
welcomeJPanel.setBackground( Color.GREEN );
// set up textJLabel
titleJLabel = new JLabel();
titleJLabel.setText( "Mind Boggler" );
titleJLabel.setLocation( 30, 10);
titleJLabel.setSize( 550, 70);
titleJLabel.setFont( new Font( "SansSerif", Font.PLAIN, 30 ) );
titleJLabel.setHorizontalAlignment( JLabel.CENTER );
welcomeJPanel.add( titleJLabel );
// set up presetJPanel
presetJPanel = new JPanel();
presetJPanel.setLayout( null );
presetJPanel.setBounds( 150, 10, 300, 80 );
presetJPanel.setBackground( Color.GRAY );
welcomeJPanel.add( presetJPanel );
//setup Intro JLabel
introJLabel = new JLabel();
introJLabel.setText( "Think, think, think. Can you get all the questions right?" );
introJLabel.setBounds( 40, 100, 500, 200 );
introJLabel.setFont( new Font( "SansSerif", Font.PLAIN, 18 ) );
introJLabel.setHorizontalAlignment( JLabel.CENTER );
welcomeJPanel.add(introJLabel);
//set up head JLabel
headJLabel = new JLabel();
headJLabel.setIcon( new ImageIcon( "head.jpeg") );
headJLabel.setBounds( 540, 5, 40, 160 );
headJLabel.setHorizontalAlignment( JLabel.CENTER );
welcomeJPanel.add(headJLabel);
//setup girlJLabel
girlJLabel = new JLabel();
girlJLabel.setIcon( new ImageIcon( "girl.Jjpeg") );
girlJLabel.setBounds( 5, 10, 60, 100 );
girlJLabel.setHorizontalAlignment( JLabel.CENTER );
welcomeJPanel.add(girlJLabel);
//set up startJbutton
startJButton = new JButton();
startJButton.setText( "Start" );
startJButton.setBounds(250, 300, 100, 30);
startJButton.setFont( new Font( "SansSerif", Font.BOLD, 14) );
welcomeJPanel.add(startJButton);
contentPane.add(welcomeJPanel);
startJButton.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
question();
public void question()
//set up question one JPanel
welcomeJPanel.setVisible(false);
questiononeJPanel = new JPanel();
questiononeJPanel.setLayout( null );
questiononeJPanel.setBounds(0, 0, 600,400);
questiononeJPanel.setBackground( Color.GREEN );
// set up textJLabel
textJLabel = new JLabel();
textJLabel.setText( "Who did Beckham supposedly cheat with?" );
textJLabel.setLocation( 20, 20);
textJLabel.setSize( 550, 70);
textJLabel.setFont( new Font( "SansSerif", Font.BOLD, 20 ) );
textJLabel.setHorizontalAlignment( JLabel.CENTER );
questiononeJPanel.add( textJLabel );
// set up presetJPanel
becksJPanel = new JPanel();
becksJPanel.setLayout( null );
becksJPanel.setBorder( new TitledBorder(
"Question 1" ) );
becksJPanel.setBounds( 10, 10, 570, 80 );
becksJPanel.setBackground( Color.GRAY );
questiononeJPanel.add( becksJPanel );
// set up oneJButton
oneJButton = new JButton();
oneJButton.setBounds( 10, 120, 300, 40 );
oneJButton.setText( "Britney Spears" );
oneJButton.setBackground( Color.ORANGE );
questiononeJPanel.add( oneJButton );
// set up twoJButton
twoJButton = new JButton();
twoJButton.setBounds( 10, 180, 300, 40 );
twoJButton.setText( "Meg Ryan" );
twoJButton.setBackground( Color.ORANGE );
questiononeJPanel.add( twoJButton );
// set up threeJButton
threeJButton = new JButton();
threeJButton.setBounds( 10, 240, 300, 40 );
threeJButton.setText( "Rebecca Loos" );
threeJButton.setBackground( Color.ORANGE );
questiononeJPanel.add( threeJButton );
// set up fourJButton
fourJButton = new JButton();
fourJButton.setBounds( 10, 300, 300, 40 );
fourJButton.setText( "Angelina Jolie" );
fourJButton.setBackground( Color.ORANGE );
questiononeJPanel.add( fourJButton );
// set up nextJButton
nextJButton = new JButton();
nextJButton.setBounds ( 375, 300, 150, 40 );
nextJButton.setText("Next");
nextJButton.setBackground( Color.GRAY );
questiononeJPanel.add( nextJButton );
contentPane.add(questiononeJPanel);
nextJButton.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
questiontwo();
public void questiontwo()
//set up question two JPanel
questiononeJPanel.setVisible(false);
questiontwoJPanel=new JPanel();
questiontwoJPanel.setLayout(null);
questiontwoJPanel.setBounds(0, 0, 600, 400);
questiontwoJPanel.setBackground( Color.GREEN );
// set up q2JLabel
q2JLabel = new JLabel();
q2JLabel.setBounds( 20, 20, 550, 70 );
q2JLabel.setText( "What films has Orlando Bloom starred in?" );
q2JLabel.setFont(new Font( "SansSerif", Font.BOLD, 20 ) );
q2JLabel.setHorizontalAlignment( JLabel.CENTER );
questiontwoJPanel.add(q2JLabel);
//set up orlandoJPanel
orlandoJPanel = new JPanel();
orlandoJPanel.setLayout(null);
orlandoJPanel.setBorder( new TitledBorder("Question 2"));
orlandoJPanel.setBounds( 10, 10, 570, 80);
orlandoJPanel.setBackground(Color.GRAY);
questiontwoJPanel.add(orlandoJPanel);
// set up lordJCheckBox
lordJCheckBox = new JCheckBox();
lordJCheckBox.setBounds( 16, 112, 200, 24 );
lordJCheckBox.setText( "1. Lord of The Rings" );
questiontwoJPanel.add( lordJCheckBox );
// set up faceJCheckBox
faceJCheckBox = new JCheckBox();
faceJCheckBox.setBounds( 16, 159, 200, 24 );
faceJCheckBox.setText( "2. Face Off" );
questiontwoJPanel.add( faceJCheckBox );
// set up piratesJCheckBox
piratesJCheckBox = new JCheckBox();
piratesJCheckBox.setBounds( 16, 206, 200, 24 );
piratesJCheckBox.setText( "3. Pirates of The Caribean" );
questiontwoJPanel.add( piratesJCheckBox );
// set up inputJButton
inputJButton = new JButton();
inputJButton.setBounds(20, 256, 200, 21 );
inputJButton.setText( "Input answer" );
questiontwoJPanel.add( inputJButton );
inputJButton.addActionListener(
new ActionListener()
//event handler called when user clicks inputJButton
public void actionPerformed( ActionEvent event )
inputJButtonActionPerformed( event);
// set up nest2JButton
next2JButton = new JButton();
next2JButton.setBounds( 155, 296, 94, 24 );
next2JButton.setText( "Next" );
questiontwoJPanel.add( next2JButton );
contentPane.add(questiontwoJPanel);
next2JButton.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
questionthree();
} // end questiontwo
public void questionthree()
//setup questionthree JPanel
questiontwoJPanel.setVisible(false);
questionthreeJPanel = new JPanel();
questionthreeJPanel.setLayout(null);
questionthreeJPanel.setBounds(0, 0, 600, 400);
questionthreeJPanel.setBackground( Color.GREEN);
//setup howmuchJLabel
howmuchJLabel = new JLabel();
howmuchJLabel.setText("I'm a student and would be very greatful if you could donate some money as it would help me very much.");
howmuchJLabel.setBounds(20, 20, 550, 70);
howmuchJLabel.setFont(new Font("SansSerif",Font.BOLD,14));
howmuchJLabel.setHorizontalAlignment(JLabel.CENTER);
questionthreeJPanel.add(howmuchJLabel);
//setup howmuchJPanel
howmuchJPanel = new JPanel();
howmuchJPanel.setLayout(null);
howmuchJPanel.setBorder( new TitledBorder("Question 3"));
howmuchJPanel.setBounds(10, 10, 570, 80);
howmuchJPanel.setBackground( Color.GRAY);
questionthreeJPanel.add(howmuchJPanel);
//setup nameJLabel
nameJLabel = new JLabel();
nameJLabel.setText("Name");
nameJLabel.setBounds(10, 160, 150, 24);
nameJLabel.setFont(new Font("SansSerif",Font.BOLD,12));
questionthreeJPanel.add(nameJLabel);
//setup nameJTextField
nameJTextField = new JTextField();
nameJTextField.setBounds(125, 160, 200, 24 );
questionthreeJPanel.add(nameJTextField);
contentPane.add(questionthreeJPanel);
//show JOptionMessages when user clicks on JCheckBoxes and inputJButton
public void inputJButtonActionPerformed( ActionEvent event )
//display error message if no JCheckBoxes is checked
else ( ( !lordJCheckBox.isSelected() && !faceJCheckBox.isSelected && !piratesJCheckBox.isSelected() ) )
//display error message
JOptionPane.showMessageDialog( null, "Please check two boxes", JOptionPane.ERROR_MESSAGE );
// if lordjcheckbox and pirates is selected = right
else
if ( ( lordJCheckBox.isSelected() && piratesJCheckBox.isSelected() ))
JOptionPane.showMessageDialog(null, "Thats RIGHT!");
//if others are selected = wrong
else
if ( (lordJCheckBox.isSelected() && faceJCheckBox.isSelected() ))
JOptionPane.showMessageDialog(null, "Thats WRONG");
else
( (faceJCheckBox.isSelected() && piratesJCheckBox.isSelected() ))
JOptionPane.showMessageDialog(null, "Thats WRONG");
// main method
public static void main( String[] args )
Mindboggler application = new Mindboggler();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
} // end method main
}// end class -
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] ).
-
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 -
cont contact apple server error please help with ipad touch 4. im just fed up with apple please help me because why is it only apple with these kind of problems?
If you mean updae server
Update Server
Try:
- Powering off and then back on your router.
- iTunes for Windows: iTunes cannot contact the iPhone, iPad, or iPod software update server
- Change the DNS to either Google's or Open DNS servers
Public DNS — Google Developers
OpenDNS IP Addresses
- For one user uninstalling/reinstalling iTunes resolved the problem
- Try on another computer/network
- Wait if it is an Apple problem
Otherwise what server are you talking about -
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 -
Average Grade using If else..1 error please help
Hi all..Okay I have to do this program that lets you input student info and 3 grades, figures out the average, and the letter grade using if else statements. I have only one error and cannot figure it out. Here is the error and a copy of my program. If someone can help me figure it out, I would appreciate it; I have tried everything I can think of. Thank you.
Error: Illegal start of expression for this line {if (avg >=80)&&(avg <90)
Here is my program:
class my_main
public static void main (String [] args) throws IOException
String Name;
String ID;
double grade1;
double grade2;
double grade3;
BufferedReader stdin;
stdin= new BufferedReader (new InputStreamReader (System.in));
System.out.println ("Please enter the following information: ");
System.out.print ("Student Name: ");
Name= stdin.readLine();
System.out.print ("Student ID: ");
ID= stdin.readLine();
System.out.print ("Grade One: ");
grade1= Double.parseDouble(stdin.readLine());
System.out.print ("Grade Two: ");
grade2= Double.parseDouble(stdin.readLine());
System.out.print ("Grade Three: ");
grade3=Double.parseDouble(stdin.readLine());
gradebook pt= new gradebook (grade1, grade2, grade3, Name, ID);
pt.display ();
class gradebook
int LG;
double gr1;
double gr2;
double gr3;
double avg;
String SName;
String IDNO;
public gradebook (double grade1, double grade2, double grade3, String Name, String ID) throws ArithmeticException
gr1= grade1;
gr2= grade2;
gr3= grade3;
IDNO=ID;
SName=Name;
avg=(gr1+gr2+gr3)/3;
if (avg >= 90)
LG='A';
else
{if (avg >=80)&&(avg <90)
LG='B';
else
{if (avg >=70)&&(avg <80)
LG='C';
else
{if (avg >=60)&&(avg <70)
LG='D';
else
{if (avg <= 59)
LG='F';
void display()
System.out.println ("Student Grades for "+SName);
System.out.println ("Student ID Number: "+IDNO);
System.out.println ("Grade One: "+gr1);
System.out.println ("Grade Two: "+gr2);
System.out.println ("Grade Three: "+gr3);
System.out.println ("Average: "+avg);
System.out.println ("Letter Grade: "+LG);
}Hi ,
There were some problems like you have defined any main method etc. I have corrected your code, and it is working....
Sandeep
* my_main.java
* Created on October 6, 2003, 12:53 PM
import java.io.*;
* @author sandeep
public class my_main {
public static void main(String args[]) throws IOException {
String Name;
String ID;
double grade1;
double grade2;
double grade3;
BufferedReader stdin;
stdin= new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter the following information: ");
System.out.print("Student Name: ");
Name= stdin.readLine();
System.out.print("Student ID: ");
ID= stdin.readLine();
System.out.print("Grade One: ");
grade1= Double.parseDouble(stdin.readLine());
System.out.print("Grade Two: ");
grade2= Double.parseDouble(stdin.readLine());
System.out.print("Grade Three: ");
grade3=Double.parseDouble(stdin.readLine());
gradebook pt= new gradebook(grade1, grade2, grade3, Name, ID);
pt.display();
class gradebook {
int LG;
double gr1;
double gr2;
double gr3;
double avg;
String SName;
String IDNO;
public gradebook(double grade1, double grade2, double grade3, String Name, String ID) throws ArithmeticException {
gr1= grade1;
gr2= grade2;
gr3= grade3;
IDNO=ID;
SName=Name;
avg=(gr1+gr2+gr3)/3;
if (avg >= 90) {
LG='A';
} else if ((avg >=80)&&(avg <90)) {
LG='B';
} else if ((avg >=70)&&(avg <80)) {
LG='C';
} else if ((avg >=60)&&(avg <70)) {
LG='D';
} else if (avg <= 59) {
LG='F';
void display() {
System.out.println("Student Grades for "+SName);
System.out.println("Student ID Number: "+IDNO);
System.out.println("Grade One: "+gr1);
System.out.println("Grade Two: "+gr2);
System.out.println("Grade Three: "+gr3);
System.out.println("Average: "+avg);
System.out.println("Letter Grade: "+LG);
Maybe you are looking for
-
Quicktime Streaming of keynotes does not work
When I want to watch the keynotes on apple.com all I get is stuttering audio and chopped video. Why? How can I solve this? It's independent of the resolution I select. btw. why am I forced to use that stone-aged Quicktime to watch a movie by the "HTM
-
Hello All, I installed remote on my iPhone yesterday, and today my wireless router doesn't work, it just seems not to work @ all. Probably just one those things but just want to throw it out there.
-
Purchase order and vendor declaration work list problem
Now, I'm testing GTS 8.0 for FTA related things. In the proceeding the test, I stuck in a problem. After making purchase order with order type NB, the system should make the worklist for the long-vendor declaration. But it dosen't make the worklist a
-
Can't send mail from my ibook g4 mac os x 10.3.9
Hello, Everything was working fine until yesterday (Oct 31st)- Suddenly i could receive mail directly via my mac ibook g4 (mac os x 10.3.9) but could no longer send anything out. How can i fix this problem and why did it suddenly happen? I don't thin
-
Hot backup getting delayed everyday
Hi All, Everyday our hot backup job is getting delayed by a significant time. Before the tablespaces are placed into begin backup mode we spotted the alert log flooded with the below message , Mon May 21 00:23:46 2012 Incremental checkpoint up to RBA