Help me please, what's wrong with my program...

My program has no problem writing data into file. But, I get garbages when my program retrieved data from file. How to solve this, anyone? I tried last 4 days still can't figure out. :(
/* myDate.java */
import java.util.*;
public class myDate extends Object{
private int year;
private int month;
private int day;
public myDate(String newDate) {
StringTokenizer st = new StringTokenizer(newDate, "/");
try {
this.day = Integer.parseInt(st.nextToken());
this.month = Integer.parseInt(st.nextToken());
this.year = Integer.parseInt(st.nextToken());
}catch (NumberFormatException nfe) {
System.out.println("Incorrect Date Format!!!");
System.out.println(nfe.getMessage());
public void setDay (int Day) { this.day = Day; }
public void setMonth (int Month) { this.month = Month; }
public void setYear (int Year) { this.year = Year; }
public String toString() {
return day + "/" + month + "/" + year;
public int getDay() { return day; }
public int getMonth() { return month; }
public int getYear() { return year;  }
/* Inventory.java
* Book Name: 30 bytes Characters
* Book ISBN: 10 bytes Characters
* Book Author: 30 bytes Characters
* Book Genre : 30 bytes Characters
* Book Quantity : 4 bytes integer
* Date of the book purchased : 10 bytes Characters.
import java.io.*;
class Inventory{
private String bookName, bookISBN, bookAuthor, bookGenre;
private int quantity;
private myDate datePurchased;
public Inventory() {
this.bookName = "";
this.bookISBN = "";
this.bookAuthor = "";
this.bookGenre = "";
this.quantity = 0;
this.datePurchased = new myDate("00/00/0000");
public void setBookName(String bookname) {
this.bookName = bookname;
public void setISBN(String BookISBN) {
this.bookISBN = BookISBN;
public void setAuthor(String author) {
this.bookAuthor = author;
public void setGenre(String genre) {
this.bookGenre = genre;
public void setQuantity(int qty) {
this.quantity = qty;
public void setPurchaseDate(String dateOfPurchase) {
this.datePurchased = new myDate(dateOfPurchase);
public String getBookName() { return bookName;}
public String getISBN() { return bookISBN;}
public String getAuthor() { return bookAuthor;}
public String getGenre() { return bookGenre;}
public int getQuantity() { return quantity;}
public String getPurchaseDate() { return datePurchased.toString();}
public String toString() {
return bookName + "\n" + bookISBN + "\n" + bookAuthor + "\n" +
bookGenre + "\n" + quantity + "\n" + datePurchased.toString() +
"\n";
public String fillData(RandomAccessFile raf, int len) throws
IOException {
char data[] = new char[len];
char temp;
for(int i = 0; i < data.length; i++) {
temp = raf.readChar();
data[i] = temp;
return new String(data).replace('\0', ' ');
public void writeStr(RandomAccessFile file, String data, int len)
throws IOException {
StringBuffer buf = null;
if(data != null)
buf = new StringBuffer(data);
else
buf = new StringBuffer(len);
buf.setLength(len);
file.writeChars(buf.toString());
public void writeRecord(RandomAccessFile rafile) throws
IOException {
writeStr(rafile, getBookName(), 30);
writeStr(rafile, getISBN(), 10);
writeStr(rafile, getAuthor(), 30);
writeStr(rafile, getGenre(), 30);
rafile.writeInt(getQuantity());
writeStr(rafile, getPurchaseDate(), 10);
public void readRecord(RandomAccessFile rafile) throws
IOException {
setBookName(fillData(rafile, 30));
setISBN(fillData(rafile, 10));
setAuthor(fillData(rafile, 30));
setGenre(fillData(rafile, 30));
setQuantity(rafile.readInt());
setPurchaseDate(fillData(rafile, 10));
public final static int size() {
return 114;
/* btnPanel.java */
import javax.swing.*;
import java.awt.*;
class btnPanel extends JPanel {
JButton btnSave, btnCancel;
public btnPanel() {
btnSave = new JButton("Save Changes");
btnCancel = new JButton("Cancel");
add(btnSave);
add(btnCancel);
/* inpPanel2.java */
import javax.swing.*;
import java.awt.*;
class inpPanel2 extends JPanel{
JTextField tfBookName, tfBookISBN, tfGenre, tfQuantity,
tfAuthor, tfDatePurchased;
JLabel lblBookName, lblBookISBN, lblAuthor, lblGenre,
lblQuantity, lblDatePurchased;
public inpPanel2() {
tfBookName = new JTextField("",30);
tfBookISBN = new JTextField("",10);
tfGenre = new JTextField("",30);
tfAuthor = new JTextField("",30);
tfQuantity = new JTextField("",10);
tfDatePurchased = new JTextField("",10);
lblBookName = new JLabel("Book Name ");
lblBookISBN = new JLabel("ISBN ");
lblAuthor = new JLabel("Author ");
lblGenre = new JLabel("Genre ");
lblQuantity = new JLabel("Quantity ");
lblDatePurchased = new JLabel("Date Purchased ");
setLayout(new GridLayout(6,2));
add(lblBookName);
add(tfBookName);
add(lblBookISBN);
add(tfBookISBN);
add(lblAuthor);
add(tfAuthor);
add(lblGenre);
add(tfGenre);
add(lblQuantity);
add(tfQuantity);
add(lblDatePurchased);
add(tfDatePurchased);
/* InventoryAdd.java */
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
class InventoryAdd extends JFrame {
btnPanel buttonPanel;
inpPanel2 inputPanel;
Inventory bookInventory;
RandomAccessFile rafile;
public InventoryAdd() {
super("Book Inventory - Add");
buttonPanel = new btnPanel();
buttonPanel.btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae){
openFile();
bookInventory = new Inventory();
bookInventory.setBookName(inputPanel.tfBookName.getText());
bookInventory.setISBN(inputPanel.tfBookISBN.getText());
bookInventory.setAuthor(inputPanel.tfAuthor.getText());
bookInventory.setGenre(inputPanel.tfGenre.getText());
bookInventory.setQuantity(
Integer.parseInt(
inputPanel.tfQuantity.getText()));
bookInventory.setPurchaseDate(inputPanel.tfDatePurchased.getText());
try {
bookInventory.writeRecord(rafile);
}catch(IOException ioe) {
System.out.println("Cannot Write Record into file...");
System.out.println(ioe.getMessage());
clearInput();
closeFile();
System.out.println(bookInventory.toString());
buttonPanel.btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae){
clearInput();
inputPanel = new inpPanel2();
Container c = getContentPane();
c.setLayout(new BorderLayout());
c.add(inputPanel, BorderLayout.CENTER);
c.add(buttonPanel, BorderLayout.SOUTH);
setSize(350, 190);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
public void clearInput() {
inputPanel.tfBookName.setText("");
inputPanel.tfBookISBN.setText("");
inputPanel.tfAuthor.setText("");
inputPanel.tfGenre.setText("");
inputPanel.tfQuantity.setText("");
inputPanel.tfDatePurchased.setText("");
public void openFile() {
try {
rafile = new RandomAccessFile("BOOK_INV.DAT","rw");
rafile.seek(rafile.length());
}catch(IOException ioe) {
System.out.println("Error, Cannot open File");
public void closeFile() {
try{
rafile.close();
}catch(IOException ioe) {
System.out.println("Error, Cannot Close File");
public static void main(String args[]) {
new InventoryAdd();
/* ReadInv.java */
import java.io.*;
class ReadInv {
RandomAccessFile rafile;
Inventory bookInv;
public ReadInv() {
bookInv = new Inventory();
try {
rafile = new RandomAccessFile("BOOK_INV.DAT","r");
rafile.seek(0);
for(int i=0; i < (rafile.length()/bookInv.size()); i++) {
bookInv.readRecord(rafile);
System.out.println(bookInv.toString());
}catch(IOException ioe) {}
public static void main(String args[]) {
new ReadInv();

it's hard to read. please use code tag.
why don't u use object serialization by implements Serializable?
import java.io.Serializable;
public class Inventory implements Serializable {
    // u don't need to change ur code here
}when saving & loading inventory, u can use ObjectOutputStream & ObjectInputStream.
here is an example:
Inventory i = new Inventory();
// set your inventory here
// save to file
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(
   "InventoryFile.dat")); // file name
out.writeObject(i);
// u can write many object to one single file.
out.close();
// load the file
ObjectInputStream in = new ObjectInputStream(new FileInputStream(
   "InventoryFile.dat"));
Inventory i = (Inventory) in.readObject();

Similar Messages

  • HELP!! WHAT'S WRONG WITH MY PROGRAM?

    It prints out "Please input next string" twice the first time and I can't figure out why. Here's the code:
    import java.util.*;
    public class VowelCounter {
         public static void main(String[] args) {
              Scanner read = new Scanner(System.in);
              int elements=0;
              // create string array
              System.out.print("How many strings do you want?");
              try{
                   elements = read.nextInt();
              catch (InputMismatchException ime){
                   System.err.println("Invalid data type!");
                   System.exit(0);
              String[] testArray = new String[elements];
              // populate String array
              for (int i=0;i<testArray.length;i++){
                   System.out.println("Please input next string:\n"+i);
                   testArray=read.nextLine();
              } // end for
              // test array and print out result
              System.out.println(mostVowels(testArray)+ " has the most vowels.");
         } // end method main
         public static String mostVowels(String[] test){
              // create array to store count
              int[] numVowels = new int[test.length];
              // check all strings in array
              for (int i=0;i<test.length;i++){
                   test[i].toLowerCase();
                   // check each char in string
                   for (int j=0; j<test[i].length();j++){
                        switch (test[i].charAt(j)){
                        case 'a': case 'e':case 'i':case 'o':case 'u':
                             numVowels[i]++;
                             break;
                        } // end switch
                   } // end for
              } // end for
              // find string with most vowels
              int most=0;
              for(int i=0;i<numVowels.length-1;i++){
                   if (numVowels[i]<numVowels[i+1]){
                        most = i+1;
              }// end for
              return test[most];
    } // end class VowelCounter
    Thanks a lot!

    Hi,
    U can do this with BufferedReader.
    here is ur code
    //It prints out "Please input next string" twice the first time and I can't figure out why. Here's the code:
    import java.util.*;
    import java.io.*;
    public class VowelCounter {
         public static void main(String[] args) {
              BufferedReader bf= new BufferedReader(new InputStreamReader(System.in));
              Scanner read = new Scanner(System.in);
              int elements=0;
              // create string array
              System.out.print("How many strings do you want?");
              try{
                   //elements = read.nextInt();
                   elements = Integer.parseInt(bf.readLine());
              catch (Exception ime){
                   System.err.println("Invalid data type!");
                   System.exit(0);
              String[] testArray = new String[elements];
              int xyz =0;
              // populate String array
              for (int i=0;i<elements;i++){
                   System.out.println(i+". Please input next string:\n");
                   try {
                        testArray=bf.readLine();
                   }catch(Exception ek){}
              } // end for
              // test array and print out result
              System.out.println(mostVowels(testArray)+ " has the most vowels.");
         } // end method main
         public static String mostVowels(String[] test){
              // create array to store count
              int[] numVowels = new int[test.length];
              // check all strings in array
              for (int i=0;i<test.length;i++){
                   test[i].toLowerCase();
                   // check each char in string
                   for (int j=0; j<test[i].length();j++){
                        switch (test[i].charAt(j)){
                             case 'a': case 'e':case 'i':case 'o':case 'u':
                                                                                         numVowels[i]++;
                                                                                         break;
                        } // end switch
                   } // end for
              } // end for
              // find string with most vowels
              int most=0;
              for(int i=0;i<numVowels.length-1;i++){
                   if (numVowels[i]<numVowels[i+1]){
                        most = i+1;
              }// end for
              return test[most];
    } // end class VowelCounter
    Ganesh

  • I need help figuring out what is wrong with my Macbook Pro

    I have a mid 2012 Macbook Pro with OS X Mavericks on it and for the past few weeks it has running VERY SLOW! I have no idea what is wrong with it, i have read other discussion forums trying to figure it out on my own. So far i have had no luck in fixing the slowness. When i open applications the icon will bounce in dock forever before opening and then my computer will freeze with the little rainbow wheel circling and circling for a few minutes... and if i try to browse websites it take forever for them to load or youtube will just stop working for me. Everything i do, no matter what i click, the rainbow wheel will pop up! The only thing i can think of messing it up was a friend of mine plugging in a flash drive a few weeks ago to take some videos and imovie to put on his Macbook Pro, he has said his laptop has been running fine though... so idk if that was the problem. Anyways, could someone please help me try something? Thank you!!

    OS X Mavericks: If your Mac runs slowly?
    http://support.apple.com/kb/PH13895
    Startup in Safe Mode
    http://support.apple.com/kb/PH14204
    Repair Disk
    Steps 1 through 7
    http://support.apple.com/kb/PH5836
    Reset SMC.     http://support.apple.com/kb/HT3964
    Choose the method for:
    "Resetting SMC on portables with a battery you should not remove on your own".
    Increase disk space.
    http://support.apple.com/kb/PH13806

  • What Is Wrong With My Program Help

    This Is The Assignment I Have To Do:
    Write a Java program that prints a table with a list of at least 5 students together with their grades earned (lab points, bonus points, and the total) in the format below.
    == Student Points ==
    Name Lab Bonus Total
    Joe 43 7 50
    William 50 8 58
    Mary Sue 39 10 49
    The requirements for the program are as follows:
    1.     Name the project StudentGrades.
    2.     Print the border on the top as illustrated (using the slash and backslash characters).
    3.     Use tab characters to get your columns aligned and you must use the + operator both for addition and string concatenation.
    4.     Make up your own student names and points -- the ones shown are just for illustration purposes. You need 5 names.
    This Is What I Have So Far:
    * Darron Jones
    * 4th Period
    * ID 2497430
    *I recieved help from the internet and the book
    *StudentGrades
      public class StudentGrades
         public static void main (String[] args )
    System.out.println("///////////////////\\\\\\\\\\\\\\\\\\");
    System.out.println("==          Student Points          ==");
    System.out.println("\\\\\\\\\\\\\\\\\\\///////////////////");
    System.out.println("                                      ");
    System.out.println("Name            Lab     Bonus   Total");
    System.out.println("----            ---     -----   -----");
    System.out.println("Dill             43      7       50");
    System.out.println("Josh             50      8       58");
    System.out.println("Rebbeca          39      10      49");When I Compile It Keeps Having An Error Thats Saying: "Illegal Escape Character" Whats Wrong With The Program Help Please

    This will work exactly as you want it to be....hope u like it
         public static void main(String[] args)
              // TODO Auto-generated method stub
              System.out.print("///////////////////");
              System.out.print("\\\\\\\\\\\\\\\\\\\\\\\\");
              System.out.println("\\\\\\\\\\\\\\");
              System.out.println("== Student Points ==");
              System.out.print("\\\\\\\\\\\\\\");
              System.out.print("\\\\\\\\\\\\");
              System.out.print("\\\\\\\\\\\\");
              System.out.print("///////////////////");
              System.out.println(" ");
              System.out.println("Name Lab Bonus Total");
              System.out.println("---- --- ----- -----");
              System.out.println("Dill 43 7 50");
              System.out.println("Josh 50 8 58");
              System.out.println("Rebbeca 39 10 49");
         }

  • What's wrong with this program?

    /* Daphne invests $100 at 10% simple interest. Deirdre invests $100 at 5% interest compounded annually. Write a program that finds how many years it takes for the value of Deirdre's investment to exceed the value of Daphne's investment. Aso show the two values at that time.*/
    #include <stdio.h>
    #define START 100.00
    int main(void)
    int counter = 1;
    float daphne = START;
    float deirdre = START;
    printf("Daphne invests $100 at 10 percent simple interest. Deirdre invests $100 at 5 percent interest compounded annually.
    When will Deirdre's account value exceed Daphne's?
    Let\'s find out.
    while (daphne > deirdre)
    daphne += 10.00;
    deirdre *= 1.05;
    printf("%f %f
    ", daphne, deirdre);
    printf("At year %d, Daphne has %.2f dollars. Deirdre has %.2f dollars.
    ", counter, daphne, deirdre);
    counter++;
    printf("By the end of year %d, Deirdre's account has surpassed Daphne's in value.
    ", counter);
    return 0;
    This is my output:
    *Daphne invests $100 at 10 percent simple interest. Deirdre invests $100 at 5 percent interest compounded annually.*
    *When will Deirdre's account value exceed Daphne's?*
    *Let's find out.*
    *By the end of year 1, Deirdre's account has surpassed Daphne's in value.*
    What's wrong with it?
    Message was edited by: musicwind95
    Message was edited by: musicwind95

    John hadn't responded at the time I started typing this, but I'll keep it posted anyways in order to expand on John's answer a little bit. The answer to your last question is that the loop's condition has to return true for it to run the first time around. To examine this further, let's take a look at the way you had the while loop before:
    while (daphne > deirdre)
    Now, a while loop will run the code between its braces as long as the condition inside the parenthesis (daphne > deirdre, in this case) is true. So, if the condition is false the first time the code reaches the while statement, then the loop will never run at all (it won't even run through it once -- it will skip over it). And since, before the while loop, both variables (daphne and dierdre) are set equal to the same value (START (100.00), in this case), both variables are equal at the point when the code first reaches the while statement. Since they are equal, daphne is NOT greater than dierdre, and therefore the condition returns false. Since the condition is false the first time the code reaches it, the code inside the loop's braces is skipped over and never run. As John recommended in the previous post, changing it to this:
    while (daphne >= deirdre)
    fixes the problem because now the condition is true. The use of the "greater than or equal to" operator (>=) instead of the "great than" operator (>) means that the condition can now be returned true even if daphne is equal to deirdre, not just if it's greater than deirdre. And since daphne and deirdre are equal (they are both 100.00) when the code first reaches the while loop, the condition is now returned true and the code inside the loop's braces will be run. Once the program reaches the end of the code inside the loop's braces, it will check to see if the condition is still true and, if it is, it will run the loop's code again (and again and again and again, checking to see if the condition is still true each time), and if it's not true, it will skip over the loop's bottom brace and continue on with the rest of the program.
    Hope this helped clear this up for you. Please ask if you have any more questions.

  • What's wrong with my program?

    Mission: A program which returns a digit based on what character you enter, and it should follow this structure:
    Digit to output / Character entered
    2 / ABC
    3 / DEF
    4 / GHI
    5 / JKL
    6 / MNO
    7 / PRS
    8 / TUV
    9 / WXY
    If you enter the letters Q, Z or any nonalphabetic letter, the program should output that an error was encountered. Must have two buttons, one for "Ok" and one for "Quit".
    I made this code so far, which gives me tons of errors I don't get much out of:
    import java.awt.*;
    import java.awt.event.*;
    public class digit
    // Define action listener for alphabetic buttons
    private static class ButtonHandler implements ActionListener
    public void actionPerformed(ActionEvent event)
    char charEntered; // Holds the character entered
    String whichButton; // Button's name
    // Get the right button
    charEntered = inputField.getText();
    whichButton = event.getActionCommand;
    // If-Else procedures, to determine which button is pressed and what action to perform
    if (whichButton.equals("ok"))
    if (charEntered.equals("A"))
    outputLabel.setText("Your digit is 2");
    else if (charEntered == D || E || F)
    outputLabel.setText("Your digit is 3");
    else if (charEntered == G || H || I)
    outputLabel.setText("Your digit is 4");
    else if (charEntered == J || K || L)
    outputLabel.setText("Your digit is 5");
    else if (charEntered == M || N || O)
    outputLabel.setText("Your digit is 6");
    else if (charEntered == P || R || S)
    outputLabel.setText("Your digit is 7");
    else if (charEntered == T || U || V)
    outputLabel.setText("Your digit is 8");
    else if (charEntered == W || X || Y)
    outputLabel.setText("Your digit is 9");
    else outputLabel.setText("An error occured.");
    private static class ButtonHandler2 implements ActionListener
    public void actionPerformed(ActionEvent event)
    dFrame.dispose();
    System.exit(0);
    private static TextField inputField; // Input field
    private static Label outputLabel; // Output Label
    private static Frame dFrame; // Frame
    public static void main(String [] args)
    // Declare alphabetic listener
    ButtonHandler operation;
    ButtonHandler2 quitoperation;
    Label entryLabel; // Label for inputfield
    Label outputLabel_label; // Label for outputfield
    Button ok; // Ok Button
    Button quit; // quit button
    operation = new Buttonhandler();
    quitoperation = new ButtonHandler2();
    // New frame
    dFrame = new Frame();
    dFrame.setLayout(new GridLayout(4,2));
    entryLabel = new Label("Enter letter here");
    outputLabel_label = new Label("The result is");
    outputLabel = new Label("0");
    // Instantiate buttons
    ok = new Button("Ok");
    quit = new Button("Quit");
    // Name the button events
    ok.setActionCommand("ok");
    quit.setActionCommand("quit");
    // Register the button listeners
    ok.addActionListener(operation);
    quit.addActionListener(operation);
    // Add interface to the Frame
    dFrame.add(entryLabel);
    dFrame.add(inputField);
    dFrame.add(outputLabel_label);
    dFrame.add(outputLabel);
    dFrame.add(ok);
    dFrame.add(quit);
    dFrame.pack();
    dFrame.show();
    dFrame.addWindowListener(new WindowAdapter()
    public void windowClosing(WindowEvent event)
    dFrame.dispose();
    System.exit(0);
    I get these errors:
    fnatte:~/inda/java/chapter6>javac digit.java
    digit.java:23: incompatible types
    found : java.lang.String
    required: char
    charEntered = inputField.getText();
    ^
    digit.java:24: cannot resolve symbol
    symbol : variable getActionCommand
    location: class java.awt.event.ActionEvent
    whichButton = event.getActionCommand;
    ^
    digit.java:31: char cannot be dereferenced
    if (charEntered.equals("A"))
    ^
    digit.java:33: cannot resolve symbol
    symbol : variable D
    location: class digit.ButtonHandler
    else if (charEntered == D || E || F)
    ^
    digit.java:33: cannot resolve symbol
    symbol : variable E
    location: class digit.ButtonHandler
    else if (charEntered == D || E || F)
    ^
    digit.java:33: cannot resolve symbol
    symbol : variable F
    location: class digit.ButtonHandler
    else if (charEntered == D || E || F)
    ^
    digit.java:35: cannot resolve symbol
    symbol : variable G
    location: class digit.ButtonHandler
    else if (charEntered == G || H || I)
    ^
    digit.java:35: cannot resolve symbol
    symbol : variable H
    location: class digit.ButtonHandler
    else if (charEntered == G || H || I)
    ^
    digit.java:35: cannot resolve symbol
    symbol : variable I
    location: class digit.ButtonHandler
    else if (charEntered == G || H || I)
    ^
    digit.java:37: cannot resolve symbol
    symbol : variable J
    location: class digit.ButtonHandler
    else if (charEntered == J || K || L)
    ^
    digit.java:37: cannot resolve symbol
    symbol : variable K
    location: class digit.ButtonHandler
    else if (charEntered == J || K || L)
    ^
    digit.java:37: cannot resolve symbol
    symbol : variable L
    location: class digit.ButtonHandler
    else if (charEntered == J || K || L)
    ^
    digit.java:39: cannot resolve symbol
    symbol : variable M
    location: class digit.ButtonHandler
    else if (charEntered == M || N || O)
    ^
    digit.java:39: cannot resolve symbol
    symbol : variable N
    location: class digit.ButtonHandler
    else if (charEntered == M || N || O)
    ^
    digit.java:39: cannot resolve symbol
    symbol : variable O
    location: class digit.ButtonHandler
    else if (charEntered == M || N || O)
    ^
    digit.java:41: cannot resolve symbol
    symbol : variable P
    location: class digit.ButtonHandler
    else if (charEntered == P || R || S)
    ^
    digit.java:41: cannot resolve symbol
    symbol : variable R
    location: class digit.ButtonHandler
    else if (charEntered == P || R || S)
    ^
    digit.java:41: cannot resolve symbol
    symbol : variable S
    location: class digit.ButtonHandler
    else if (charEntered == P || R || S)
    ^
    digit.java:43: cannot resolve symbol
    symbol : variable T
    location: class digit.ButtonHandler
    else if (charEntered == T || U || V)
    ^
    digit.java:43: cannot resolve symbol
    symbol : variable U
    location: class digit.ButtonHandler
    else if (charEntered == T || U || V)
    ^
    digit.java:43: cannot resolve symbol
    symbol : variable V
    location: class digit.ButtonHandler
    else if (charEntered == T || U || V)
    ^
    digit.java:45: cannot resolve symbol
    symbol : variable W
    location: class digit.ButtonHandler
    else if (charEntered == W || X || Y)
    ^
    digit.java:45: cannot resolve symbol
    symbol : variable X
    location: class digit.ButtonHandler
    else if (charEntered == W || X || Y)
    ^
    digit.java:45: cannot resolve symbol
    symbol : variable Y
    location: class digit.ButtonHandler
    else if (charEntered == W || X || Y)
    ^
    digit.java:79: cannot resolve symbol
    symbol : class Buttonhandler
    location: class digit
    operation = new Buttonhandler();
    ^
    25 errors
    I don't get what's wrong... I know it's something with the "equals" method.. but I can't get a grip on it.

    Hi again,
    Thanks, I'm beginning to understand the structure... charAt(0) means take character at index 0, i.e the first character.
    I also understood how the || works, and I managed to compile the thing without errors. Now my code looks like this:
    import java.awt.*;
    import java.awt.event.*;
    public class digit
        // Define action listener for alphabetic buttons
        private static class ButtonHandler implements ActionListener
         public void actionPerformed(ActionEvent event)
         char  charEntered;    // Holds the character entered
         String whichButton;  // Button's name
         // Get the right button
         charEntered = inputField.getText().charAt(0);
         whichButton = event.getActionCommand();
         // If-Else procedures, to determine which button is pressed and what action to perform
         if (whichButton.equals("ok"))
              if (charEntered == 'A' || charEntered == 'B' || charEntered ==  'C')
             outputLabel.setText("Your digit is 2");
         else if (charEntered == 'D' || charEntered == 'E' || charEntered ==  'F')
             outputLabel.setText("Your digit is 3");
         else if (charEntered == 'G' || charEntered == 'H' || charEntered ==  'I')
             outputLabel.setText("Your digit is 4");
         else if (charEntered == 'J' || charEntered == 'K' || charEntered ==  'L')
             outputLabel.setText("Your digit is 5");
         else if (charEntered == 'M' || charEntered == 'N' || charEntered ==  'O')
             outputLabel.setText("Your digit is 6");
         else if (charEntered == 'P' || charEntered == 'R' || charEntered ==  'S')
             outputLabel.setText("Your digit is 7");
         else if (charEntered == 'T' || charEntered == 'U' || charEntered ==  'V')
             outputLabel.setText("Your digit is 8");
         else if (charEntered == 'W' || charEntered == 'X' || charEntered ==  'Y')
             outputLabel.setText("Your digit is 9");
         else outputLabel.setText("An error occured.");
    private static class ButtonHandler2 implements ActionListener
        public void actionPerformed(ActionEvent event)
         dFrame.dispose();
         System.exit(0);
    private static TextField inputField; // Input field
    private static Label outputLabel; // Output Label
    private static Frame dFrame; // Frame
    public static void main(String [] args)
        // Declare alphabetic listener
        ButtonHandler operation; 
        ButtonHandler2 quitOperation;
        Label entryLabel; // Label for inputfield
        Label outputLabel_label;  // Label for outputfield
        Button ok; // Ok Button
        Button quit; // quit button
        operation = new ButtonHandler();
        quitOperation = new ButtonHandler2();
        // New frame
        dFrame = new Frame();
        dFrame.setLayout(new GridLayout(4,2));
        entryLabel = new Label("Enter letter here");
        outputLabel_label = new Label("The result is");
        outputLabel = new Label("0");
        // Instantiate buttons
        ok = new Button("Ok");
        quit = new Button("Quit");
        // Name the button events
        ok.setActionCommand("ok");
        quit.setActionCommand("quit");
        // Register the button listeners
        ok.addActionListener(operation);
        quit.addActionListener(operation);
        // Add interface to the Frame
        dFrame.add(entryLabel);
        dFrame.add(inputField);
        dFrame.add(outputLabel_label);
        dFrame.add(outputLabel);
        dFrame.add(ok);
        dFrame.add(quit);
        dFrame.pack();
        dFrame.show();
        dFrame.addWindowListener(new WindowAdapter()
             public void windowClosing(WindowEvent event)
              dFrame.dispose();
              System.exit(0);
    }And I get this error while I'm trying to run it:
    fnatte:~/inda/java/chapter6>java digit
    Exception in thread "main" java.lang.NoSuchMethodError: main

  • What is wrong with this program segment? I could not understand the error..

    public class Hmw3
         public static char[] myMethod(char[]p1,int p2, char p3)
         {                             //13 th row
              if(p2<p1.length)
                   p1[p2]=p3;
                   System.out.println(p1);
         public static void main(String[] args)
              String sentence="It snows";
              char[] tmp=sentence.toCharArray();
              System.out.println(tmp);
              myMethod(tmp,3,'k');
              sentence=String.copyValueOf(tmp);
              System.out.println(sentence);     
    i wrote this program segment and compiler gave this error:
    C:\Program Files\Xinox Software\JCreator LE\MyProjects\hmw3\Hmw3.java:13: missing return statement
    What is wrong???

    Your method signature states that myMethod should return an array for chars.
    But in ur implementation of myMethod, there is nothing returned.
    Just add a return statement like "return p1"

  • Need help figuring out what's wrong with my code!

    I am having a few problems with my code and can't see what I've done wrong. Here are my issues:
    #1. My program is not displaying the answers to my calculations in the table.
    #2. The program is supposed to pause after 24 lines and ask the user to hit enter to continue.
    2a. First, it works correctly for the first 24 lines, but then jumps to every 48 lines.
    2b. The line count is supposed to go 24, 48, etc...but the code is going from 24 to 74 to 124 ... that is NOT right!
    import java.text.DecimalFormat; //needed to format decimals
    import java.io.*;
    class Mortgage2
    //Define variables
    double MonthlyPayment = 0; //monthly payment
    double Principal = 200000; //principal of loan
    double YearlyInterestRate = 5.75; //yearly interest rate
    double MonthlyInterestRate = (5.75/1200); //monthly interest rate
    double MonthlyPrincipal = 0; //monthly principal
    double MonthlyInterest = 0; //monthly interest
    double Balance = 0; //balance of loan
    int TermInYears = 30; //term of loan in yearly terms
    int linecount = 0; //line count for list of results
    // Buffered input Reader
    BufferedReader myInput = new BufferedReader (new
    InputStreamReader(System.in));
    //Calculation Methods
    void calculateMonthlyPayment() //Calculates monthly mortgage
    MonthlyPayment = Principal * (MonthlyInterestRate * (Math.pow(1 + MonthlyInterestRate, 12 * TermInYears))) /
    (Math.pow(1 + MonthlyInterestRate, 12 * TermInYears) - 1);
    void calculateMonthlyInterestRate() //Calculates monthly interest
    MonthlyInterest = Balance * MonthlyInterestRate;
    void calculateMonthlyPrincipal() //Calculates monthly principal
    MonthlyPrincipal = MonthlyPayment - MonthlyInterest;
    void calculateBalance() //Calculates balance
    Balance = Principal + MonthlyInterest - MonthlyPayment;
    void Amortization() //Calculates Amortization
    DecimalFormat df = new DecimalFormat("$,###.00"); //Format decimals
    int NumberOfPayments = TermInYears * 12;
    for (int i = 1; i <= NumberOfPayments; i++)
    // If statements asking user to enter to continue
    if(linecount == 24)
    System.out.println("Press Enter to Continue.");
    linecount = 0;
    try
    System.in.read();
    catch(IOException e) {
    e.printStackTrace();
    else
    linecount++;
    System.out.println(i + "\t\t" + df.format(MonthlyPrincipal) + "\t" + df.format(MonthlyInterest) + "\t" + df.format(Balance));
    //Method to display output
    public void display ()
    DecimalFormat df = new DecimalFormat(",###.00"); //Format decimals
    System.out.println("\n\nMORTGAGE PAYMENT CALCULATOR"); //title of the program
    System.out.println("=================================="); //separator
    System.out.println("\tPrincipal Amount: $" + df.format(Principal)); //principal amount of the mortgage
    System.out.println("\tTerm:\t" + TermInYears + " years"); //number of years of the loan
    System.out.println("\tInterest Rate:\t" + YearlyInterestRate + "%"); //interest rate as a percentage
    System.out.println("\tMonthly Payment: $" + df.format(MonthlyPayment)); //calculated monthly payment
    System.out.println("\n\nAMORTIZATION TABLE"); //title of amortization table
    System.out.println("======================================================"); //separator
    System.out.println("\nPayment\tPrincipal\tInterest\t Balance");
    System.out.println(" Month\t Paid\t\t Paid\t\tRemaining");
    System.out.println("--------\t---------\t--------\t-------");
    public static void main (String rgs[]) //Start main function
    Mortgage2 Mortgage = new Mortgage2();
    Mortgage.calculateMonthlyPayment();
    Mortgage.display();
    Mortgage.Amortization();
    ANY help would be greatly appreciated!
    Edited by: Jeaneene on May 25, 2008 11:54 AM

    From [http://developers.sun.com/resources/forumsFAQ.html]:
    Post once and in the right area: Multiple postings are allowed, but they make the category lists longer and create more email traffic for developers who have placed watches on multiple categories. Because of this, duplicate posts are considered a waste of time and an annoyance to many community members, that is, the people who might help you.

  • Help!! what's wrong with my new ipod classic??

    Hi there, I have a brand new 80G ipod classic to replace my older 8G nano. I've been using itunes as usual but when I plugged my new ipod into the PC to transfer my existing itunes library and purchased tracks to my new ipod I got the message "attempting to copy to the disk failed. The disk could not be read from or written to." I was then prompted to 'restore' the ipod. I retried downloading a number of times. Each time the message appeared after downloading only a few of the saved music tracks (5,162,190,19), and each time I had to restore the ipod. I'm sure this isn't a problem with my PC software as my wife is using a brand new 8G nano from the same PC without issue. Could it be that the ipod hard drive is crashing during the download process? I'm really stuck and would love to use my christmas gift as intended! Hope someone can help.
    Many thanks.

    See if this troubleshooting article helps.
    Disk cannot be read from or written to error syncing iPod in iTunes.

  • What's wrong with this program that about socket

    package example;
    import java.net.*;
    import java.io.*;
    public class Server implements Runnable{
        Thread t;
        ServerSocket sSocket;
        int sPort=6633;
        public Server(){
            try{
                sSocket=new ServerSocket(sPort);
                System.out.println("server start....");
            }catch(IOException e){
                e.printStackTrace();
            t=new Thread(this);
            t.start();
        public void run(){
            try{
                while(true){
                    Socket cSocket=sSocket.accept();
                    ClientThread cThread=new ClientThread(cSocket);
                    cThread.start();
            }catch(IOException e){
                e.printStackTrace();
       public static void main(String[] args){
            new Server();
    package example;
    import java.net.*;
    import java.io.*;
    public class ClientThread extends Thread{
        Socket cSocket;
        PrintStream writer;
        BufferedReader reader;
        public ClientThread(Socket s){
            cSocket=s;
            try{
                writer=new PrintStream(cSocket.getOutputStream());
                reader=new BufferedReader(new InputStreamReader(cSocket.getInputStream()));
            }catch(IOException e){
                e.printStackTrace();
        public void run(){
            try{
                while(true){
                    String message=reader.readLine();
                    System.out.println("Server get:"+message);
            }catch(IOException e){
                e.printStackTrace();
    package example;
    import java.net.*;
    import java.io.*;
    public class Client{
        public static void main(String[] args){
            String ipaddr="localhost";
            PrintStream writer;
            try{
                Socket  cSocket=new Socket(ipaddr,6633);
                System.out.println(cSocket);
                writer=new PrintStream(cSocket.getOutputStream());
                System.out.println("client send:hello");
                writer.print("hello");
            catch(Exception e){
                e.printStackTrace();
    }first,I run Server,and then I run Client,
    output at Server:
    server start....
    java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(SocketInputStream.java:168)
    at java.net.SocketInputStream.read(SocketInputStream.java:90)
    at sun.nio.cs.StreamDecoder$ConverterSD.implRead(StreamDecoder.java:285)
    at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:182)
    at java.io.InputStreamReader.read(InputStreamReader.java:167)
    at java.io.BufferedReader.fill(BufferedReader.java:136)
    at java.io.BufferedReader.readLine(BufferedReader.java:299)
    at java.io.BufferedReader.readLine(BufferedReader.java:362)
    at example.ClientThread.run(ClientThread.java:20)
    what' wrong??????

    In your Client class, after doing writer.print("hello"); you should flush
    the output stream. As it is now, you attempt to write something (without actually
    sending something to your server) and main simply terminates. The server,
    still waiting for some input (you didn't flush on the client side), is confronted with
    a closed client socket (main on the client side terminated and implicitly closed
    the client socket), hence the 'connection reset' exception on the server side.
    kind regards,
    Jos

  • When measuring 6 voltage signals in labview I found that there was a difference in voltage signals in my program but not in the test panel. The test panel is correct. What is wrong with my program?

    My labview program is not displaying equivelent voltages, but labview test panel is. So the computer is seeing the correct signals. My program is displaying a small difference in 3 out of 6 channels. All channels should be equal.

    G'Day Pops,
    You haven't really given us enough to go on - could you please post your VI so we can have a look at it?
    cheers,
    Christopher
    Christopher G. Relf
    Certified LabVIEW Developer
    [email protected]
    Int'l Voicemail & Fax: +61 2 8080 8132
    Aust Voicemail & Fax: (02) 8080 8132
    EULA
    1) This is a private email, and although the views expressed within it may not be purely my own, unless specifically referenced I do not suggest they are necessarily associated with anyone else including, but not limited to, my employer(s).
    2) This email has NOT been scanned for virii - attached file(s), if any, are provided as is. By copying, detaching and/or opening attached files, you agree to indemnify the sender of such responsibility.
    3) B
    ecause e-mail can be altered electronically, the integrity of this communication cannot be guaranteed.
    Copyright © 2004-2015 Christopher G. Relf. Some Rights Reserved. This posting is licensed under a Creative Commons Attribution 2.5 License.

  • What is wrong with this program?

    When I run a get these messages:
    ^
    MULTIPLYIMP.java:25: 'class' or 'interface' expected
    ^
    MULTIPLYIMP.java:7: cannot resolve symbol
    symbol : class UnicastRemoteObject
    location: class MULTIPLYIMP
    UnicastRemoteObject implements multiply {
    ^
    MULTIPLYIMP.java:6: MULTIPLYIMP should be declared abstract; it does not define
    greet() in MULTIPLYIMP
    public class MULTIPLYIMP extends
    ^
    MULTIPLYIMP.java:11: cannot resolve symbol
    symbol : method supa ()
    location: class MULTIPLYIMP
    supa (); //Export
    ^
    MULTIPLYIMP.java:15: missing method body, or declare abstract
    public int mult (int a,int b) throws RemoteException
    ^
    9 errors
    //MULTIPLYIMPL.JAVA
    import java.rmi.*;
    import .rmi.server.*;
    public class MULTIPLYIMP extends
    unicastRemoteObject implements multiply {
    public MULTIPLYIMPL () throwsRemoteException {
    supa (); //Export
    public int mult (int a,int b) throws RemoteException
    return (a * b)
    public String greet () throws RemoteException
    return("CCM 3061");

    When I run a get these messages:
    ^
    MULTIPLYIMP.java:25: 'class' or 'interface' expected
    ^
    MULTIPLYIMP.java:7: cannot resolve symbol
    symbol : class UnicastRemoteObject
    location: class MULTIPLYIMP
    UnicastRemoteObject implements multiply {
    ^
    You haven't imported the right package.
    You need to import
    java.rmi.server.UnicastRemoteObject
    or
    java.rmi.server.*
    MULTIPLYIMP.java:6: MULTIPLYIMP should be declared
    abstract; it does not define
    greet() in MULTIPLYIMP
    public class MULTIPLYIMP extends
    ^
    It says that you don't define greet() because it doesn't have curly braces after the method name.
    I'm reasonably sure
    public String greet () throws RemoteException
    return("CCM 3061");is not acceptable, usepublic String greet () throws RemoteException
    return("CCM 3061");
    MULTIPLYIMP.java:11: cannot resolve symbol
    symbol : method supa ()
    location: class MULTIPLYIMP
    supa (); //Export
    ^
    MY GOD MAN, SUPER(), SUPER!!!!!!
    MULTIPLYIMP.java:15: missing method body, or declare
    abstract
    public int mult (int a,int b) throws RemoteException
    ^
    9 errors
    Same with mult(), need to have curly braces around the method body
    //MULTIPLYIMPL.JAVA
    import java.rmi.*;
    WHAT IS THIS LINE?
    import java.rmi.server.*
    import .rmi.server.*;
    public class MULTIPLYIMP extends
    unicastRemoteObject implements multiply {
    public MULTIPLYIMPL () throwsRemoteException {
    supa (); //Export
    public int mult (int a,int b) throws RemoteException
    return (a * b)
    public String greet () throws RemoteException
    return("CCM 3061");
    }Messy messy code mate,
    Good luck,
    Radish21

  • What is wrong with this program it keeps telling me the file doesn't exist?

    this program is supposed to write the file so why does it need the file to already exist?
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.ArrayList;
    import java.util.Scanner;
    public class NewClass implements ActionListener{
        static List list = new List();
        static TextField input = new TextField(20);
        static Button submit = new Button("Submit");
        static Frame f = new Frame("RealmList editor");
        static File file = new File("/Applications/World of Warcraft/realmlist.wtf");
        static Label status = new Label("");
        static Button selected = new Button("Change to Selected");
        static File config = new File("/Applications/RealmLister/config.txt");
        static File dir = new File("/Applications/RealmLister/");
        public static void main(String[] args) {
            f.setLayout(new BorderLayout());
            f.add(list, BorderLayout.CENTER);
            Panel p = new Panel();
            p.add(input);
            p.add(submit);
            p.add(selected);
            f.add(p, BorderLayout.NORTH);
            f.add(status, BorderLayout.SOUTH);
            new NewClass();
            f.setSize(500,500);
            f.setVisible(true);
            try {
                loadConfig();
            } catch(Exception e) {}
            f.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent we) {
                    try {
                      writeConfig();
                      System.exit(0);
                    } catch(Exception e) {
                       status.setText("Error: config couldn't be written!("+e+")");
        public NewClass() {
            submit.addActionListener(this);
            input.addKeyListener(new KeyAdapter() {
                public void keyPressed(KeyEvent e) {
                    if(e.getKeyCode() == KeyEvent.VK_ENTER) {
                    try {
                    editRealmlist(input.getText(), true);
                    input.setText("");
                 catch(Exception ex) {
                   status.setText("Error: "+e);
            selected.addActionListener(this);
        public void actionPerformed(ActionEvent e) {
            if(e.getSource() == submit) {
                try {
                    editRealmlist(input.getText(), true);
                    input.setText("");
                } catch(Exception ex) {
                   status.setText("Error: "+e);
                   wait(3000);
                   status.setText("");
            if(e.getSource() == selected) {
                try {
                    editRealmlist(list.getSelectedItem(),false);
                } catch(Exception ex) {
                    status.setText("Error: "+e);
                    wait(3000);
                    status.setText("");
        public static void loadConfig() throws Exception{
            if(config.exists()) {
                Scanner scan = new Scanner(config);
                ArrayList<String> al = new ArrayList<String>();
                while(scan.hasNext()) {
                    al.add(scan.nextLine());
                for(int i = 0; i < al.size(); i++) {
                    list.add(al.get(i));
        public static void writeConfig() throws Exception{
            FileWriter fw = new FileWriter(config);
            dir.mkdir();
            config.mkdirs();
            String temp = "";
            for(int i = 0; i < list.getItemCount(); i++) {
                temp += list.getItem(i)+"\n";
            fw.write(temp);
            fw.flush();
            System.gc();
        public static void editRealmlist(String realm, boolean addtoList) throws Exception{
            FileWriter fw = new FileWriter(file);
            fw.write("set realmlist "+realm+"\nset patchlist us.version.worldofwarcraft.com");
            fw.flush();
            status.setText("Editing RealmList.wtf Please Wait...");
            Thread.sleep(3000);
            status.setText("");
            System.gc();
            if(addtoList)
                list.add(realm);
        public void wait(int time) {
            try {
                Thread.sleep(time);
            catch(Exception e) {}
    }

    Erm, you should call mkdirs() on a File object that represents a directory.

  • Please wat is wrong with this program

    I want to reverse the user input but when I run this program it only asks for the input and when i key it in and press enter nothing happens.It just freezes.
    Sorry the code is a bit long .
    import java.io.*;
    class StackX
    private int maxSize;
    private char[] stackArray;
    private int top;
    public StackX(int max)  
           maxSize=max;
           stackArray=new char[maxSize];
           top=-1;
    public void push(char j) 
         stackArray[++top]=j;
    public char pop()    
         return stackArray[top--];
    public char peek()  
         return stackArray[top];
    public boolean isEmpty()   
         return (top==-1);
    class Reverser
         private String input;  
         private String output; 
    public Reverser(String in)
         {input = in;}
             public String doRev( )    
         int stackSize=input.length( ); 
         StackX theStack = new StackX(stackSize);
         for(int j=0;j<input.length( );j++)
         char ch=input.charAt(j); 
         theStack.push(ch);
         output ="";
         while( !theStack.isEmpty() )
         char ch=theStack.pop();
         output=output+ch; 
         return output;
    class ReverseApp
         public static void main(String[]args)throws IOException
         String input, output;
         while(true)
         System.out.print("Enter a string:");
         System.out.flush();
         input=getString();
         if( input.equals(""))
          break;
         Reverser theReverser = new Reverser(input);
         output = theReverser.doRev();
         System.out.println("Reversed: " + output);
    public static String getString()throws IOException
         InputStreamReader isr = new InputStreamReader(System.in);
         BufferedReader br= new BufferedReader(isr);
         String s = br.readLine();
         return s;
    }

    One potential problem is that you're using a new reader around system.in every time. I don't know what happens when you do that. Just make it a member variable, or create it once in main and pass it to getString.
    Asid from that, put a bunch of print statements in or use a debugger to see what's happening at each step of the way. You might be getting into an infinite loop somewhere in your reverse operation.

  • What's wrong with this program, nothing displays.

    Compile ok, but nothing displays.
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    public class Card{
    JFrame f;
    JLabel nameTF;
    JComboBox jobChoice;
    JButton B1, B2, B3, B4;
    public static void main(String[] av) {
    new Card( );
    public Card( ) {
    f=new JFrame();
    f.setSize(500,500);
    Container cp = f.getContentPane( );
    cp.setLayout(new GridLayout(0, 1));
    f.addWindowListener(new WindowAdapter( ) {
    public void windowClosing(WindowEvent e) {
    f.setVisible(false);
    f.dispose( );
    System.exit(0);
    JMenuBar mb = new JMenuBar( );
    f.setJMenuBar(mb);
    JMenu aMenu;
    aMenu = new JMenu("filemenu");
    mb.add(aMenu);
    JMenuItem mi = new JMenuItem("exit");
    aMenu.add(mi);
    mi.addActionListener(new ActionListener( ) {
    public void actionPerformed(ActionEvent e) {
    System.exit(0);
    aMenu = new JMenu("editmenu");
    mb.add(aMenu);
    aMenu = new JMenu("viewmenu");
    mb.add(aMenu);
    aMenu = new JMenu("optionsmenu");
    mb.add(aMenu);
    aMenu =new JMenu("helpmenu");
    mb.add(aMenu);
    JPanel p1 = new JPanel( );
    p1.setLayout(new GridLayout(0, 1, 50, 10));
    nameTF = new JLabel("My Name", JLabel.CENTER);
    nameTF.setFont(new Font("helvetica", Font.BOLD, 18));
    nameTF.setText("MYNAME");
    p1.add(nameTF);
    jobChoice = new JComboBox( );
    jobChoice.setFont(new Font("helvetica", Font.BOLD, 14));
    String next;
    int i=1;
    do {
    next = "job_title" + i;
    if (next != null)
    jobChoice.addItem(next);
    } while (next != null);
    p1.add(jobChoice);
    cp.add(p1);
    JPanel p2 = new JPanel( );
    p2.setLayout(new GridLayout(2, 2, 10, 10));
    B1 = new JButton( );
    B1.setText("button1.label");
    p2.add(B1);
    B2 = new JButton( );
    B2.setText("button2.label");
    p2.add(B2);
    B3 = new JButton( );
    B3.setText("button3.label");
    p2.add(B3);
    B4 = new JButton( );
    B4.setText("button4.label");
    p2.add(B4);
    cp.add(p2);
    f.pack( );
    f.show();
    }

    hi there
    try this code i changed a little bil and one more thing yr LOOP is not working Properly check that out
    rest is fine
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    public class Card extends JFrame
        JLabel nameTF;
        JComboBox jobChoice;
        JButton B1, B2, B3, B4;
        public static void main(String[] av)
            Card C = new Card( );
            C.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        public Card( )
            setSize(500,500);
            Container cp = getContentPane( );
            cp.setLayout(new GridLayout(0, 1));
            addWindowListener(new WindowAdapter( )
                public void windowClosing(WindowEvent e)
                    dispose( );
                    System.exit(0);
        JMenuBar mb = new JMenuBar( );
        setJMenuBar(mb);
        JMenu aMenu;
        aMenu = new JMenu("filemenu");
        mb.add(aMenu);
        JMenuItem mi = new JMenuItem("exit");
        aMenu.add(mi);
        mi.addActionListener(new ActionListener( )
            public void actionPerformed(ActionEvent e)
                dispose( );
                System.exit(0);
        aMenu = new JMenu("editmenu");
        mb.add(aMenu);
        aMenu = new JMenu("viewmenu");
        mb.add(aMenu);
        aMenu = new JMenu("optionsmenu");
        mb.add(aMenu);
        aMenu =new JMenu("helpmenu");
        mb.add(aMenu);
        JPanel p1 = new JPanel( );
        p1.setLayout(new GridLayout(0, 1, 50, 10));
        nameTF = new JLabel("My Name", JLabel.CENTER);
        nameTF.setFont(new Font("helvetica", Font.BOLD, 18));
        nameTF.setText("MYNAME");
        p1.add(nameTF);
        jobChoice = new JComboBox( );
        jobChoice.setFont(new Font("helvetica", Font.BOLD, 14));
        String next;
    //    int i=1;
    //    do
    //        next = "job_title" + i;
    //        if (next != null)
    //           jobChoice.addItem(next);
    //    } while (next != null);
        p1.add(jobChoice);
        cp.add(p1);
        JPanel p2 = new JPanel( );
        p2.setLayout(new GridLayout(2, 2, 10, 10));
        B1 = new JButton( );
        B1.setText("button1.label");
        p2.add(B1);
        B2 = new JButton( );
        B2.setText("button2.label");
        p2.add(B2);
        B3 = new JButton( );
        B3.setText("button3.label");
        p2.add(B3);
        B4 = new JButton( );
        B4.setText("button4.label");
        p2.add(B4);
        cp.add(p2);
        pack( );
        setVisible(true);
    }Regards
    Satinderjit

Maybe you are looking for

  • How to change the image of a selected File/Directory in JFileChooser while

    Hi all, I am trying to customize JFileChooser. Basically, I want to display a checked Icon for a selected directory(s) in JFileChooser I know that fileView class returns icon for directory/files, but I am not sure how to change their images on select

  • Hello, can't get my mac to upgrade to latest versions of quicktime, itunes or any other os

    Hello, can't get my mac to upgrade to latest versions of quicktime, itunes or any other os

  • Kernel update problem

    when i try to update my kernel this is what happens. [root@myhost abhi]# pacman -S kernel26 resolving dependencies... looking for inter-conflicts... Targets: klibc-1.5-5  klibc-extras-2.4-1  klibc-udev-116-3           klibc-module-init-tools-3.2.2-3 

  • Using Submit statement

    Hi, I want to create a delivery from sales order using 'Submit'. Is this a correct program? What needs to be populated in the table rspar_tab? Please provide your input. data: rspar_tab  TYPE TABLE OF rsparams. SUBMIT SAPMV50A USING SELECTION-SCREEN

  • Regarding Transformation

    Hi All, I have created datasource to upload flat file. I've used )amount field but i havent give currncy field in flat file. So at the time of transformation it is showing error  "Source unit is not assigned". I already tried to correct this in Trans