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

Similar Messages

  • 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 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 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"

  • 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.

  • 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();

  • 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

  • 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

  • HELP!What's wrong with my GZIP program?

    Here's part of the source code:
    static void Compress(String strfilename)     
         int iTemp;
         try
              BufferedReader brIn=new BufferedReader(new FileReader(strfilename));
              BufferedOutputStream bosOut=new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream(strfilename+".gz")));
              while(true)
                   iTemp=brIn.read();
                   if(iTemp==-1) break;
                   bosOut.write(iTemp);                         }
              brIn.close();
              bosOut.close();
         catch(Exception e)
              System.out.println("Error: "+e);
    If I use it to compress a small file(20k),the compression is successful,and I can also see it using WINRAR;but once I decompress
    this GZIP file,all the English words are correct,while other unicodes
    such as Chinese become unrecognizable;
    If I use it to compress a "large" file(3M) such as abc.chm,the size of the compressed file is about 2M(INCREDIBLE! WINRAR can only decrease
    the size of this file by 30k);But..the size of decompressed file is
    still about 2M,and windows cannot read it (Invalid page error).
    I wonder what's wrong with my program? Even if I use "javac -encoding
    gb2312 ..." to compile my program,the result is also the same.
    HOW SHOULD I DO??

    Hi, jchc,
    Let me help you a little bit, here. hwalkup is correct that for data compression you should use input and output stream instead of readers and writers. I don't think that mixing a reader with an output stream would work anyway as streams read and write bytes (8-bit data), while readers and writers read and write characters (16-bit data). hwalkup is also correct to suggest that you should use a buffer (a byte[]) to improve the performance of your streaming processes.
    Here is code for methods to compress and decompress one file into another. Note: the decompress() method will throw an IOException if the file to decompress (inFile) is not actually compressed in the first place.
        public static void compress(File inFile, File outFile)
                throws FileNotFoundException, IOException {
            InputStream in = null;
            OutputStream out = null;
            try {
                in = new BufferedInputStream(new FileInputStream(inFile));
                GZIPOutputStream gzipOut = new GZIPOutputStream(
                                           new FileOutputStream(outFile));
                out = new BufferedOutputStream(gzipOut);
                byte[] buffer = new byte[512];
                for (int i = 0; (i = in.read(buffer)) > -1; ) {
                    out.write(buffer, 0, i);
                out.flush();
                gzipOut.finish(); // absolutely necessary
            } finally {
                // always close your output streams before your input streams
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
        public static void decompress(File inFile, File outFile)
                throws FileNotFoundException, IOException {
            InputStream in = null;
            OutputStream out = null;
            try {
                GZIPInputStream gzipIn = new GZIPInputStream(
                                         new FileInputStream(inFile));
                in = new BufferedInputStream(gzipIn);
                out = new BufferedOutputStream(new FileOutputStream(outFile));
                byte[] buffer = new byte[512];
                for (int i = 0; (i = in.read(buffer)) > -1; ) {
                    out.write(buffer, 0, i);
                out.flush();
            } finally {
                // always close your output streams before your input streams
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
        }Shaun

  • Does ANYONE know whats wrong with this program?!?!

    Hey(again),
    Does anyone know whats wrong with this program?:
    public class FloatingNumbersTest
    public static void main(String args[])
    float float1 =50.0f;
    float closeFloat=0.001f
    float farfloat=100.0f
    if (float1<=closeFloat)
    System.out.print("Float1 pretty close to zero");
    if (float1>=closeFloat)
    System.out.print("Float1 is near 0");
    if (float1>=farfloat)
    System.out.print("Float1 is not even close to zero!"0
    }There has seemed to be 5 errors!

    public class FloatingNumbersTest
    public static void main(String args[])
    float float1 =50.0f;
    float closeFloat=0.001f
    float farfloat=100.0f
    if (float1<=closeFloat)
    HERE        System.out.print("Float1 pretty close to zero");
    if (float1>=closeFloat)
    System.out.print("Float1 is near 0");
    if (float1>=farfloat)
    System.out.print("Float1 is not even close to zero!"0
    }you're missing the opening { for the first if.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • I can't figure out what's wrong with this code

    First i want this program to allow me to enter a number with the EasyReader class and depending on the number entered it will show that specific line of this peom:
    One two buckle your shoe
    Three four shut the door
    Five six pick up sticks
    Seven eight lay them straight
    Nine ten this is the end.
    The error message i got was an illegal start of expression. I can't figure out why it is giving me this error because i have if (n = 1) || (n = 2) statements. My code is:
    public class PoemSeventeen
    public static void main(String[] args)
    EasyReader console = new EasyReader();
    System.out.println("Enter a number for the poem (0 to quit): ");
    int n = console.readInt();
    if (n = 1) || (n = 2)
    System.out.println("One, two, buckle your shoe");
    else if (n = 3) || (n = 4)
    System.out.println("Three, four, shut the door");
    else if (n = 5) || (n = 6)
    System.out.println("Five, six, pick up sticks");
    else if (n = 7) || (n = 8)
    System.out.println("Seven, eight, lay them straight");
    else if (n = 9) || (n = 10)
    System.out.println("Nine, ten, this is the end");
    else if (n = 0)
    System.out.println("You may exit now");
    else
    System.out.println("Put in a number between 0 and 10");
    I messed around with a few other thing because i had some weird errors before but now i have narrowed it down to just this 1 error.
    The EasyReader class code:
    // package com.skylit.io;
    import java.io.*;
    * @author Gary Litvin
    * @version 1.2, 5/30/02
    * Written as part of
    * <i>Java Methods: An Introduction to Object-Oriented Programming</i>
    * (Skylight Publishing 2001, ISBN 0-9654853-7-4)
    * and
    * <i>Java Methods AB: Data Structures</i>
    * (Skylight Publishing 2003, ISBN 0-9654853-1-5)
    * EasyReader provides simple methods for reading the console and
    * for opening and reading text files. All exceptions are handled
    * inside the class and are hidden from the user.
    * <xmp>
    * Example:
    * =======
    * EasyReader console = new EasyReader();
    * System.out.print("Enter input file name: ");
    * String fileName = console.readLine();
    * EasyReader inFile = new EasyReader(fileName);
    * if (inFile.bad())
    * System.err.println("Can't open " + fileName);
    * System.exit(1);
    * String firstLine = inFile.readLine();
    * if (!inFile.eof()) // or: if (firstLine != null)
    * System.out.println("The first line is : " + firstLine);
    * System.out.print("Enter the maximum number of integers to read: ");
    * int maxCount = console.readInt();
    * int k, count = 0;
    * while (count < maxCount && !inFile.eof())
    * k = inFile.readInt();
    * if (!inFile.eof())
    * // process or store this number
    * count++;
    * inFile.close(); // optional
    * System.out.println(count + " numbers read");
    * </xmp>
    public class EasyReader
    protected String myFileName;
    protected BufferedReader myInFile;
    protected int myErrorFlags = 0;
    protected static final int OPENERROR = 0x0001;
    protected static final int CLOSEERROR = 0x0002;
    protected static final int READERROR = 0x0004;
    protected static final int EOF = 0x0100;
    * Constructor. Prepares console (System.in) for reading
    public EasyReader()
    myFileName = null;
    myErrorFlags = 0;
    myInFile = new BufferedReader(
    new InputStreamReader(System.in), 128);
    * Constructor. opens a file for reading
    * @param fileName the name or pathname of the file
    public EasyReader(String fileName)
    myFileName = fileName;
    myErrorFlags = 0;
    try
    myInFile = new BufferedReader(new FileReader(fileName), 1024);
    catch (FileNotFoundException e)
    myErrorFlags |= OPENERROR;
    myFileName = null;
    * Closes the file
    public void close()
    if (myFileName == null)
    return;
    try
    myInFile.close();
    catch (IOException e)
    System.err.println("Error closing " + myFileName + "\n");
    myErrorFlags |= CLOSEERROR;
    * Checks the status of the file
    * @return true if en error occurred opening or reading the file,
    * false otherwise
    public boolean bad()
    return myErrorFlags != 0;
    * Checks the EOF status of the file
    * @return true if EOF was encountered in the previous read
    * operation, false otherwise
    public boolean eof()
    return (myErrorFlags & EOF) != 0;
    private boolean ready() throws IOException
    return myFileName == null || myInFile.ready();
    * Reads the next character from a file (any character including
    * a space or a newline character).
    * @return character read or <code>null</code> character
    * (Unicode 0) if trying to read beyond the EOF
    public char readChar()
    char ch = '\u0000';
    try
    if (ready())
    ch = (char)myInFile.read();
    catch (IOException e)
    if (myFileName != null)
    System.err.println("Error reading " + myFileName + "\n");
    myErrorFlags |= READERROR;
    if (ch == '\u0000')
    myErrorFlags |= EOF;
    return ch;
    * Reads from the current position in the file up to and including
    * the next newline character. The newline character is thrown away
    * @return the read string (excluding the newline character) or
    * null if trying to read beyond the EOF
    public String readLine()
    String s = null;
    try
    s = myInFile.readLine();
    catch (IOException e)
    if (myFileName != null)
    System.err.println("Error reading " + myFileName + "\n");
    myErrorFlags |= READERROR;
    if (s == null)
    myErrorFlags |= EOF;
    return s;
    * Skips whitespace and reads the next word (a string of consecutive
    * non-whitespace characters (up to but excluding the next space,
    * newline, etc.)
    * @return the read string or null if trying to read beyond the EOF
    public String readWord()
    StringBuffer buffer = new StringBuffer(128);
    char ch = ' ';
    int count = 0;
    String s = null;
    try
    while (ready() && Character.isWhitespace(ch))
    ch = (char)myInFile.read();
    while (ready() && !Character.isWhitespace(ch))
    count++;
    buffer.append(ch);
    myInFile.mark(1);
    ch = (char)myInFile.read();
    if (count > 0)
    myInFile.reset();
    s = buffer.toString();
    else
    myErrorFlags |= EOF;
    catch (IOException e)
    if (myFileName != null)
    System.err.println("Error reading " + myFileName + "\n");
    myErrorFlags |= READERROR;
    return s;
    * Reads the next integer (without validating its format)
    * @return the integer read or 0 if trying to read beyond the EOF
    public int readInt()
    String s = readWord();
    if (s != null)
    return Integer.parseInt(s);
    else
    return 0;
    * Reads the next double (without validating its format)
    * @return the number read or 0 if trying to read beyond the EOF
    public double readDouble()
    String s = readWord();
    if (s != null)
    return Double.parseDouble(s);
    // in Java 1, use: return Double.valueOf(s).doubleValue();
    else
    return 0.0;
    Can anybody please tell me what's wrong with this code? Thanks

    String[] message = {
        "One, two, buckle your shoe",
        "One, two, buckle your shoe",
        "Three, four, shut the door",
        "Three, four, shut the door",
        "Five, six, pick up sticks",
        "Five, six, pick up sticks",
        "Seven, eight, lay them straight",
        "Seven, eight, lay them straight",
        "Nine, ten, this is the end",
        "Nine, ten, this is the end"
    if(n>0)
        System.out.println(message[n]);
    else
        System.exit(0);

  • What is wrong with as3

    this is not a question about 'how i do X'. is rather a 'discussion' (flame or whatever, but to defend or argue about aspects, not people) about 'what is wrong with as3' and what aspects whould be taken into consideration for updates. right now i am using as3, and since i paid for this license, i choose this tool over some alternatives and i am using it to do stuff for other people who pay me to do it, i think it can be helpful for all of us if some actions are started in the right direction. i have already posted about 'all people in adobe are dumbasses that do not know how to make a scripting tool and are messing up my work', but i was pissed at the time (i still am pissed) but i believe this is not the right aproach. instead, if this goes to the right people in adobe, we all may get something in the future, like better and easier todo apps and web presentations.
    pre: not only about the as3 specification, but COMPLY with the specification that you set. for example, some time ago there were problems with matrix transforms. this was corrected later with a patch. but this means it is not even doing what is is supposed to do
    1. scriptable masks and movement, sprites and child sprites: there is a sprite with a mask, the mask is a shape drawn via script, something like
    somemask=new shape();
    somemask.graphics.beginfill();
    (...etc)
    somesprite.mask=somemask;
    just like that. now add some child sprites to 'somesprite', and make 'somesprite' move, scale and rotate. there you will have something like a kaleidoscope, but not what you expected to do with your script. as the child sprites move in the parent mask, you will see that the child sprites appear or dissapear kind of randomly, and if the child sprites are textfields, it may be that the text is rendered outside the mask, or partially rendered outside the mask (as in only part of the text), rendered with the wrongf rotation or in the wrong place. some child sprites are clipped correctly, some dissapear totally when only a part should dissapear (clipped) etc.
    way around: have not tried it yet, but i have the impression that bitmaps have different criteria for clipping, so i am thinking of trying this: appli an empty filter (a filter with params so it does not have any effect on the sprite or in the textfield) so the sprite is rendered as bitmap before doing anything else with it. as i said, i have not done it yet, but it may be a way around this problem, to avoid all this inconsistency with clipping
    1-b. inconsistency between hierarchy and coordinates, specially masks: you apply a mask to a sprite, yet the sprite has a set of coordinates (so 'x' in the sprite means an x relative to its container), yet the mask applied to the very same sprite, as another reference as reference for coordinates (like the stage)
    2. painting via script: in any other languaje, in any other situation, something like:
    beginFill(params);
    (...stuff 1)
    endFill();
    beginFill(params);
    (...stuff 2)
    endFill();
    (...etc)
    means: render region of block 1, then render region of block 2 etc, and no matter what, it should be consistent, since there is noplace for ambiguity. if you read it, you may think what that means, even if you dont run it you may have an idea of the picture you want to draw, but not with as3. as3 somehow manages to screw something that simple, and mixes all the blocks, and somehow uses the boundaries of one block as boundaries for other block. is like all blocks are dumped into whatever, and then uses all lines defined into it as boundaries for a unique block. it changes all boundaries and generates inconsistency between what is shown and redraw regions of the resulting picture, like lines that go to the end of the screen and then dont go away in the next frames, even tough the beginfill endfill block should prevent it
    3. event flow: i dont know what was the policy behind as3 event flow design. it is in no way similar or an extension to previous event flow, neither with any event flow in any other plattform. i dont know how most people start with as3; in my case, i unpacked, installed and when i tried to do something with what i already knew i could not, so i started reading the as3 docs, and since is like 800 pages long, i just read the basics and the rest i would 'wing it'. in the part of the event flow, there was something about bubbling and stuff, it was not clear at all and when i tried to do what is was said in the documentation (like preventing events to 'bubble', as is called in the documentation), i could not see any effect but i could see it was a mess. flash is not the only thing out there to work with pictures or to work with mouse events, but is the only one that deals with things like 'target' and 'currentTarget'. my first experience on needing this was when i was dealing with my own event handlers (so the only thing that had control over mouse was the stage, and i would admin everything via script). there were events generated everywhere, the stage got events that were not genrated directly over the stage, but got there not with stage coordinates but the coordinates relative to the sprite that generated the event. so if i hover the mopuse over the stage, and the stage has some things on it how does it work? i get multiple event calls, like it was hovering multiple times over the stage in a single frame, but in each call with different coordinates? and what if i set all child sprites as mouseenabled=false or compare like 'if (event.target != event.currenttarget)', what if i move the mouse over a child, does it prevent the move mouse event at all? or does it filter only the event call with only stage coordinates? in my case, every time i move over another clip (with mouseenabled = true), the stage gets it as 'mouse up', even tough there was never a mouse release, what the hell? do even the people at adobe know how to handle events with their own tool when they require it? why does an event 'bubble' when i have not specifically tell it to do it? mi thought is that this event flow was very poorly conceived, and tough the intention may have been that there were different cases and it shopuld cover all cases, they actually introduced new problems that were not present in traditional ways to handle it, and it is neither the easier way to handle things, and this way, a very simple problem turns into a very ugly thing because it must handle things that were not neccesary to handle, or were implicit in other situations.
    4. legacy: since as3, all interaction is different, and if you want to do things in the new plattform, using the new features, what you already knew just goes to the garbage can. when a new tool arrives, it should be an extension to previous tools (which is a reason to update instead of just buying a new tool from a different vendor). if everything i had or knew just means nothing from now on, then i can not say 'i know flash script', and my previous knowledge gives me no advantage when aproaching the new version. as3 is a new aproach that requires doc reading and stuff, even if you knew something about previous as specifications or other oo languajes. if you decide to change things from now on, like the things mentioned in this post, instead of just throwing away everything the users alerady knew about the tool, do like in java releases, they mark some things as 'deprecated', they keep working as they should, give a warning, but also a message saying this feature is deprecated, we suggest you use this library instead.
    5. lack of previous functionality: if you 'update' something, it meand all previos functionality is still there (probably improved, but not with bugs if it was working fine), plus something else. now it seems backwards, there are some things that could be done in previous versions but not in this one, like 'duplicatemovieclip'
    6. inconsistency with scripting/programming paradigms: (ok, fancy work, but fits perfectly here): as3 proposed ways to handle things, but the people who designed it got 'too creative', and they did something that is not consistent neither with previous versions of as or with other languajes. the documentations is full of things like 'it looks like x languaje or languaje family, but instead of using XXX word, you must use YYY'. great, what is this? namespaces 'work like', but 'differently' for example from java, .net, .c. its got the idea that a namespace means a grouped functionality but there are rules about where should be placed the file (ok, java has this also, .net takes care of it automatically if all files are registered in the project), but what you got is a mess that 'if you know other languajes you got the general idea, but nonetheless, even if you knew this or previosu versions of as, you still have to read whatever we decided arbitrarily just to be different'. namespaces, event handling, vars definition which is not like previous scripting neither like fully typed languajes.. is just a mess.
    7. lack of scripting and graphics integration: unlike flash and adobe tools that just got on the graphics side leaving all the scripting integratuion apart, most tools from other vendors integrate very well interacton with what is on the screen. the script editor: very poor. autocompletion? a drop down list that does not heklp at all, appears in the wrong places, and when you need it to go, it does not go (so if i want to move away from the uncalled drop down list, i have to click somewhere else, making developement slowewr instead of helping, so the drop down list does not capture all events when i dont want to). in other ides you double click somewhere and it will go to the part of code relevant to that event or whatever. for example microsoft tools, ok i am antimicrosoft, and one of the reasons was that when windows 95 got to market proposing itself as the ONLY pc os you could use if you wanted to keep useing the apps you already had, it was a lousy product full of flaws but you had to keep using it because you had no choice. what is so different from what is happening with flash just now? yet the ide of c# is awesome, works very well and seems reliable.
    adobe people: not all user are designers that just make pretty pictures. if it is not intended for scripting then why is it there. and if there are corrections to be done, they should patch all versions, not only the last one. previous version users also paid for their versions.

    Well, there is no point in arguing.
    I personally believe AS3 does exactly what it promises to do within limits (read: reasonable limits) of ECMA type of language. And sometimes it doesn’t do what we expect it to for it cannot possibly emulate everyone’s thinking process. The task, I guess, is to learn to think in terms of AS3 – not to try to make AS3 think like us. No language covers all the grounds. And no, it is not Java - with no negative or positive connotation. It is what it is. Period. I just hope that AS5 will be more Java like.
    You are right about the fact that it is not necessary to know all the aspects of language in order to perform the majority of tasks. But it is paramount to have a clear idea about such fundamental concepts as display list model and events. For instance, depth swap has no meaning in terms of AS3 because display list object stacking is controlled automatically and there is no need for all these jumping through hoops one has to perform in order to control depth in AS2. There no more gaps in depths and one always know where to find things.
    Similarly, there is no point in having duplicateMovieClip method. More conventional OOP ways of object instantiation accomplishes just that and much more. Just because OOP object instantiation needs to be learned doesn’t mean past hacks have place in modern times. duplicateMovieClip is a horse carriage standing next to SUV. What one should choose to travel?
    Events are implemented to the tee in the context of ECMA specifications. I consider Events model as very solid, it works great (exactly as expected) and never failed me. True, it takes time to get used to it. But what doesn’t?
    By the way, speaking about events, contrary to believe in Adobe’s inconsideration to their following. Events are implemented with weakly reference set to false although it would be better to have it set to true. I think this is because there are smart and considerate people out there who knew how difficult it would be for programming novices to deal with lost listeners.
    I think AS3 is million times better than AS2. And one of the reasons it came out this way is that Adobe made a very brave and wise decision to break totally loose from AS2’s inherent crap. They have created a totally new and very solid language. If they had tried to make it backward compatible – it would be a huge screw up, similar to how our friends at Microsoft are prostituting VB and VBA – extremely irritating approach IMHO.
    Also, Flash legacy issues shouldn’t be overlooked. Flash did not start as a platform for programmers. Entire timeline concept in many ways is not compatible with the best OOP practices and advancements. I think for anyone who is used to writing classes the very fact of coding on timeline sounds awkward. It feels like a hack (and AS2 IS a pile of hacks) – the same things can be nicely packaged into classes and scale indefinitely. As such I wouldn’t expect Adobe to waste time on hacking timeline concept issues by making smarter editor. They have made a new one – FlexBuilder – instead. Serious programmers realize very soon that Flash IDE is not for developing industrial strength applications anyway. So, why bother with channeling great minds into polishing path to the dead end?
    I would like to state that all this is coming form a person who knew Flash when there was no AS at all. And I applaud every new generation of this wonderful tool.
    I believe Adobe does a great job making transition from timeline paradigm to total OOP venue as smooth as possible. And no, they don’t leave their devoted followers behind contrary to many claims. They are working on making developing Flash applications as easy as possible for people of all walks. Welcome Catalyst!
    Of course there is not enough information about AS3 capabilities and features. But, on the other hand, I don’t know any area of human kind activities that does.

Maybe you are looking for

  • How do i find out what is in the 'other' section of the usage bar

    i have 8gb 2nd gen touch. I have cleared all data i can see and deleted photos and music however the usage bar still tells me as well as 3gb apps I have 4gb other. Where is this other and how do I free it up? thnaks

  • How to  use Help View  in select options

    i had a chk table in which there are 5 fields  it is assign to a field in other table but when i wnat to c the help i am able to c only 3 fields ..can anyone suggest me why is so ? For the above reason i created a view but how to attach it in select

  • Problem with deploytool

    I'm using IPlanet 6 SP3 and am using the deploytool to deploy my application. The application deploys without errors, but one of my jar files that lives under WEB-INF/lib does not get fully unpacked. I have some dtd files which live in the JAR with t

  • Videos disappears from iPod!

    I'm using a third party encoder for videos for my iPod, and I'm able to view them perfectly, the problem is: When I update my videos (add/change/remove) on the iPod the ones that I didn't even touch will disappear and I'm only able to see them on iTu

  • MacBook Pro 3,1 Upgrade

    I've ordered two 2Gb sticks of ram for my computer and was wondering if there was a tool like Crucial uses to tell which hard drive I could replace my old one with. I have the following: Model Name: MacBook Pro Model Identifier: MacBookPro3,1 Process