Java fundamentals..

In the following code,in the line labled Here,Can we call this as method overloading? I also have a doubt whether it is possible to overload a method of super class, in subclass?
class A
     public void calculate( int x, int y ){
          System.out.println(x+" "+y);
class B extends A
     B(){
          super();
     public void calculate( int x, float y ){          //Here
          System.out.println("in B "+x+" "+y);
     public static void main(String args[]){
          new A().calculate(1,2);
          new B().calculate(1,2.0f);
};

Generally speaking there can be non-trivial issues though.
In this C++ example the method foo(int) hides the method foo() of its parent class.
class a {
public:
void foo();
class b : public a {
public:
void foo(int i);
int main(int argc,char *argv[]) {
b* w = new b();
//     w->foo();     // does not compile
     w->a::foo();     // does compile
}

Similar Messages

  • What is a good java book

    I am new to java. I had a class on it and the book we used in there was cumbersome and unorganized at best. I am wondering what other people have found are good books to help you get better at java. I need something that I can find answers to basic questions and also more advanced ones. If possible I'm looking for one that can also work like a reference book where if I need to know something specific that I can find that pretty quickly too.
    Is there such a thing out there? Or am I looking for the impossible? Please help... anyone?

    Core Java Fundamentals - ISBN - 0130471771
    Core Java Advanced features - ISBN - 0130927384
    These assume you know another object orientated language.
    The best refrence is the java documentation available at java.sun.com or it can be downloaded.
    Andrew

  • Help with Java to XML

    All I need to know is how to bold the tag <CompanyID> </CompanyID> OR the text within it (1001, in given sample).
    Here's a sample line of the data.txt file I'm working with:
    1001,"Fitzsimmons, Des Marteau, Beale and Nunn",109,"COD","Standard",,109,8/14/1998 8:50:02
    Thanks in advance!
    public class PracticeExerciseOne {
        public static void main(String [] args){
            DocumentBuilderFactory domFac = null;
            DocumentBuilder domBuild = null;
            //Element tags
            final String COMPANY = "Companies";
            final String COMPANY_ID = "CompanyID";
            //rest too long to post
            //Regex to be used for each field in the CSV file
            ArrayList<Pattern> patterns = new ArrayList<Pattern>();
            patterns.add(Pattern.compile("[0-9]+,"));
            patterns.add(Pattern.compile("\".+?\","));
            patterns.add(Pattern.compile("[0-9]+,"));
            patterns.add(Pattern.compile("\".+?\","));
            patterns.add(Pattern.compile("\".+?\","));
            patterns.add(Pattern.compile("[^,]*,"));
            patterns.add(Pattern.compile("[0-9]+,"));
            patterns.add(Pattern.compile("[^,]+ [^,]+"));
            //Store element tags in an array - too long to post
            try{
                //Build a new documet
                domFac = DocumentBuilderFactory.newInstance();
                domBuild = domFac.newDocumentBuilder();
                Document doc = domBuild.newDocument();
                //Create a new root element
                Element rootElement = doc.createElement(COMPANY);
                doc.appendChild(rootElement);
                //Read in the file
                BufferedReader in = new BufferedReader(new FileReader(new File("texts/data.txt")));
                BufferedWriter out = new BufferedWriter(new FileWriter(new File("texts/dataOut.xml")));
                int tempI;
                String line = in.readLine();
                //We will cut this string down after every element we take out of it
                String temp = line;
                String tempElement = "";
                while(line != null){
                    for(int i = 0; i < patterns.size(); i++){
                        //Matches a pattern to a field, starting with the first pattern
                        //Matchup should be 1st pattern = 1st field
                        Matcher matcher = patterns.get(i).matcher(temp);
                        if(matcher.find()){
                            //if we haven't reached the last field
                            if(i != 7){
                                //we want to get the index of the last comma within the matched group
                                tempI = matcher.group().lastIndexOf(',');
                                //create an element using the beginning of the given string and the last comma within that data
                                tempElement = temp.substring(0,tempI);
                            else{
                                //no comma in last field, so we just want to get the whole field
                                tempI = 0;
                                tempElement = temp.substring(0);
                            //if an empty element appears, add a space for tags to be placed correctly
                            if(tempElement.equals("")){
                                tempElement = " ";
                            //temp will be set to the remaining string, once we have taken the nth field out
                            temp = temp.substring(tempI+1);
                            //create an element with tags and append to document
                            Element em = doc.createElement(tags);
    em.appendChild(doc.createTextNode(tempElement));
    rootElement.appendChild(em);
    line = in.readLine();
    temp = line;
    //Transformer will create a new XML document using the Document we have built
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(out);
    transformer.transform(source, result);
    out.close();
    in.close();
    catch(Exception e){
    System.err.println("Exception: " + e.getMessage());
    e.printStackTrace();

    maybe this can help You for now and future,
    in this site You can download a sample codes publish in this books - java fundamentals and advanced features.,
    in 2nd book, is a big chapter about java and xml. Please read this code, i will hope, this can help You.
    http://www.horstmann.com/corejava.html (for mod: this is not SPAM)

  • IKM Java J2EE Test

    I am about to take IKM Java J2EE test ! If anyone has taken this up before kindly share me the
    topics and your experience regarding same ?

    Hi Guys,
    I thought I will share IKM experience, for people who are planning to take.
    I have just finished doing an IKM Exam, 10 minutes back. Overall, I have done four IKM Exams, this year, and two of it in the last one week..
    1. Distributed Programming
    2. XML
    3. Java2 Programming
    4. Java2 / J2EE Programming.
    You are expecting a tough exam. Atleast, it was tough for me, all of them :)
    Exam Pattern:
    It is objective based with three possible answers, but not always and does not say how many answers / question, either. Credit is provided as long as you are able to get close to the answers. Say two answers are correct out of 3. Conversely, you have deductions in credit, if you blindly choose anything irrelevant. (that proves absolutely no knowledge in that area) .
    You cannot go back to a question, that you have answered already
    Questions are made increasingly difficult, when you are answering good and if you find an easy question, all of a sudden, you already know how you have been answering the previous question.
    Questions:
    On average, you have around 30 - 40 questions and the time limit is 90 minutes maximum. Expect plenty of code based questions.
    Syllabus: I do not know if they provide any definite syllabus beforehand and the questions are from all possible areas inside the topic. e.g., when I did the xml IKM, the questions were from XDR, Xpointer, XLink, Xquery and all sorts...
    Test Results: The test results shows you are overall percentage. It shows your strengths on each subtopics related to the exam, on three grades (Strong,Proficient,Weak)
    You can see your test results, if the test organiser has set up that way. I had an opportunity to see only for Java 2 Programming. So added the topics below
    Java 2 Programming: Usual Java (fundamentals,package,i/o,operators,threads., etc.,) + JVM Memory Management + Security Framework + AWT
    Hope it helps.

  • Learning Swing - Can't get JLabel to appear in JFrame

    Hi,
    I'm a complete beginner to Java. I'm taking a course that's moving way too fast, in my opinion, and we're currently studying Swing. I've likely missed a lot of basic basic Java fundamentals due to the speed of this class, so if I'm making a ridiculous mistake, please let me know.
    I'm trying to create the following:
    +"Create a GUI interface using the Swing API. Use the JOptionPane class to create a dialog box to ask the+
    +user for the University Name. Create a JFrame that has a label with the University name and create your+
    +own logo. The window should have the capability of inputting first name , last name, and id for a student+
    +in text fields. Once the id is entered open another dialog box with the student information."+
    I'm pretty much done, I'm just having issues getting the output from the first JFrame to appear in the second JFrame. When I create a new JFrame, the title I specify appears, but the normal syntax for a JLabel just isn't working and I'm not sure why.
    I suspect it has something to do with the general structure of my program rather than my syntax. ...I know I'm missing a lot of fundamentals that I should have developed, thanks to the way the course I'm in is structured.
    I'm posting two .java files. The first, called GUIFrame.java is the class that basically does everything, it calls JOptionPane, opens the first and second JFrames, and uses ActionEvent and ActionListener to read text from the text fields. The second .java file is called GUITest.java and all it does is instantiate GUIFrame and sets the JFrame parameters.
    If anyone has any suggestions, at all, about how to fix this, or especially how to structure these better... Any suggestion would be greatly appreciated.
    CODE:
    import javax.swing.JFrame; //provides basic window features
    import javax.swing.JOptionPane; //simple GUI input/output
    import javax.swing.JLabel; //displays text and images
    import javax.swing.Icon; //interface used to manipulate images
    import javax.swing.ImageIcon; //loads images
    import java.awt.FlowLayout; // specifies how components are arranged
    import javax.swing.SwingConstants; //common constants used with Swing
    import javax.swing.JTextField;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    public class GUIFrame extends JFrame
         private JLabel line1;
         private JLabel line2;
         private JLabel line3;
         private JLabel line4;
         private JTextField textField1;
         private JTextField textField2;
         private JTextField textField3;
         //This method prompts the user in a JOptionPane for the university's name.
         public static String obtainUniversityName()
              //Obtain user input from JOptionPane input dialog for universityName.
              String uName = JOptionPane.showInputDialog(null,"Enter the University's name","University Name",JOptionPane.QUESTION_MESSAGE);
              return uName;     
         //This method creates an image icon if possible, or it will print an error and return null
         protected ImageIcon createImageIcon(String path,String description)
              java.net.URL imgURL = getClass().getResource(path);
              if (imgURL != null)
                   return new ImageIcon(imgURL, description);
              } else {
                   System.err.println("Couldn't find file: " + path);
                   return null;
         public GUIFrame()
              //Create a new JFrame for the university info to be placed in
              //The title of the window is also declared here
              super(obtainUniversityName());
              //Sets way things are arranged
              setLayout(new FlowLayout());
              //Grabs logo and aligns it with "Welcome to the University"
              ImageIcon logo = createImageIcon("girl.gif","This is a logo");
              line1 = new JLabel("Welcome to the University", logo, JLabel.CENTER);
              add(line1);
              //"First Name" + Text Field
              line2 = new JLabel("First Name");
              add(line2);
              textField1 = new JTextField(10);
              add(textField1);
              //"Last Name" + Text Field
              line3 = new JLabel("Last Name");
              add(line3);
              textField2 = new JTextField(10);
              add(textField2);
              //"Student ID" + Text Field
              line4 = new JLabel("Student ID");
              add(line4);
              textField3 = new JTextField(10);
              add(textField3);
              //Register event handlers
              TextFieldHandler handler = new TextFieldHandler();
              textField1.addActionListener(handler);
              textField2.addActionListener(handler);
              textField3.addActionListener(handler);
         private class TextFieldHandler implements ActionListener
              public void actionPerformed(ActionEvent event)
                   String fname = "";
                   String lname = "";
                   String stuid = "";
                   //When user presses enter in any text field, these set values for input into text field
                   if(event.getSource()==textField1)
                        fname = String.format("First Name: %s", event.getActionCommand());
                             else if(event.getSource()==textField2)
                                  lname=String.format("Last Name: %s", event.getActionCommand());
                                       else if(event.getSource()==textField3)
                                            stuid=String.format("Student ID: %s", event.getActionCommand());
                                                 else
                                                      System.out.println("ERROR! You didn't fill in atleast one of the text boxes...");
                   //Creates a new JFrame with title "Student Info"          
                   JFrame frame2 = new JFrame("Student Info");
                   //Sets way things are arranged
                   setLayout(new FlowLayout());
                   //Temporary - Tests to see that processing of text field events occurs correctly
                   System.out.println(fname);
                   System.out.println(lname);
                   System.out.println(stuid);               
                   //Puts data into JLabels for display in new JFrame
                   JLabel label1=new JLabel(fname);
                   add(label1);
                   JLabel label2=new JLabel("Can you see this!?");
                   add(label2);          
                   JLabel label3=new JLabel(stuid);
                   add(label3);
                   //Sets parameters, size, close, visibility, etc, for new JFrame
                   frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   frame2.setSize(275,210);
                   frame2.setVisible(true);
              }//end void actionPerformed
         }//end TextFieldHandler
    }//end GUIFrame
    ==================================================================================
    import javax.swing.JFrame; //provides basic window features
    public class GUITest
         public static void main(String args[])
              //Calls on GUIFrame class. Instantiates.
              GUIFrame guiFrame = new GUIFrame();
              //Set the window to exit when closed
              guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              //Size the window
              guiFrame.setSize(275,210);
              //Center the window on the screen
              guiFrame.setLocationRelativeTo(null);
              //Make the window visible
              guiFrame.setVisible(true);
    }

    Thanks so much for the quick response. Yeah, I guess I'm a bit oblivious, I guess I missed that it was supposed to be another JOptionPane.
    I fixed that and got rid of all the second JFrame stuff. Thank you.
    And you're right, now that I can see my output, it's obvious I have serious issues in the actionPerformed() method with the ActionListener. I guess it's just a simple question of how to take what's in all three boxes and output to JOptionPane. Simple logic I guess.
    I don't completely understand the ActionListener. I've read my textbook about it and looked at a few online resources, but I don't have a complete understanding.
    How then, would I be able to use the ActionListener to get the text from all three text fields?
    The way it is now, as you correctly predicted, it waits for enter to be inputted from each text field and whichever text field you hit enter in, despite what's in the other text fields, is the only thing that is outputted to the string in the JOptionPane.
    Do you have a suggestion for that?
    Thanks again.
    CODE:
    import javax.swing.JFrame; //provides basic window features
    import javax.swing.JOptionPane; //simple GUI input/output
    import javax.swing.JLabel; //displays text and images
    import javax.swing.Icon; //interface used to manipulate images
    import javax.swing.ImageIcon; //loads images
    import java.awt.FlowLayout; // specifies how components are arranged
    import javax.swing.SwingConstants; //common constants used with Swing
    import javax.swing.JTextField;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    public class GUIFrame extends JFrame
         private JLabel line1;
         private JLabel line2;
         private JLabel line3;
         private JLabel line4;
         private JTextField textField1;
         private JTextField textField2;
         private JTextField textField3;
         //This method prompts the user in a JOptionPane for the university's name.
         public static String obtainUniversityName()
              //Obtain user input from JOptionPane input dialog for universityName.
              String uName = JOptionPane.showInputDialog(null,"Enter the University's name","University Name",JOptionPane.QUESTION_MESSAGE);
              return uName;     
         //This method creates an image icon if possible, or it will print an error and return null
         protected ImageIcon createImageIcon(String path,String description)
              java.net.URL imgURL = getClass().getResource(path);
              if (imgURL != null)
                   return new ImageIcon(imgURL, description);
              } else {
                   System.err.println("Couldn't find file: " + path);
                   return null;
         public GUIFrame()
              //Create a new JFrame for the university info to be placed in
              //The title of the window is also declared here
              super(obtainUniversityName());
              //Sets way things are arranged
              setLayout(new FlowLayout());
              //Grabs logo and aligns it with "Welcome to the University"
              ImageIcon logo = createImageIcon("girl.gif","This is a logo");
              line1 = new JLabel("Welcome to the University", logo, JLabel.CENTER);
              add(line1);
              //"First Name" + Text Field
              line2 = new JLabel("First Name");
              add(line2);
              textField1 = new JTextField(10);
              add(textField1);
              //"Last Name" + Text Field
              line3 = new JLabel("Last Name");
              add(line3);
              textField2 = new JTextField(10);
              add(textField2);
              //"Student ID" + Text Field
              line4 = new JLabel("Student ID");
              add(line4);
              textField3 = new JTextField(10);
              add(textField3);
              //Register event handlers
              TextFieldHandler handler = new TextFieldHandler();
              textField1.addActionListener(handler);
              textField2.addActionListener(handler);
              textField3.addActionListener(handler);
         private class TextFieldHandler implements ActionListener
              public void actionPerformed(ActionEvent event)
                   String fname = "";
                   String lname = "";
                   String stuid = "";
                   //When user presses enter in any text field, these set values for input into text field
                   if(event.getSource()==textField1)
                        fname = String.format("First Name: %s", event.getActionCommand());
                             else if(event.getSource()==textField2)
                                  lname=String.format("Last Name: %s", event.getActionCommand());
                                       else if(event.getSource()==textField3)
                                            stuid=String.format("Student ID: %s", event.getActionCommand());
                                                 else
                                                      System.out.println("ERROR! You didn't fill in atleast one of the text boxes...");
                   String out = fname + "\n" + lname + "\n" + stuid;
                   JOptionPane.showMessageDialog(null,out);
              }//end void actionPerformed
         }//end TextFieldHandler
    }//end GUIFrame
    import javax.swing.JFrame; //provides basic window features
    public class GUITest
         public static void main(String args[])
              //Calls on GUIFrame class. Instantiates.
              GUIFrame guiFrame = new GUIFrame();
              //Set the window to exit when closed
              guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              //Size the window
              guiFrame.setSize(275,210);
              //Center the window on the screen
              guiFrame.setLocationRelativeTo(null);
              //Make the window visible
              guiFrame.setVisible(true);
    }Edited by: heathercmiller on Apr 5, 2008 8:56 AM

  • Which course is better to learn??

    Hi,
    I am working as a ABAP developer since 1 year 6 months .
    i want to learn something related to ABAP.
    Please guide me
    which is having good future.
    i know java fundamentals..
    Regards,
    sri

    Hi Sri.
    Kindly, Do not ask these sort of questions here.
    I would like to suggest.
    Please read [Rules of Engagement|https://wiki.sdn.sap.com/wiki/display/HOME/RulesofEngagement] Before posting
    Hope you take this positively.
    I would like to suggest a better option,
    Go To SDN Search, SDN Wiki, SDN Weblogs, SDN Library.
    You will get the right Path.
    Good Luck & Regards.
    Harsh Dave

  • What should be?

    i got a part time job. which is to design and develop a site and create a content for a certain topic. the hosting and domain is provided by the employer.the common language that comes to mind when web development is PHP, but*, I'm learning java fundamentals as of this moment. as part of my part time job, I want to learn developing web applications in java at the same time. so is there anyone of you would like to tell on what are the things that I should request my employer to install in their server, in order for me to run java based pages?, in PHP, all you need is php parser and mysql, and its done..so how bout in java?..please state all the needed things to be installed in their server. thanks.

    nemo666 wrote:
    wpafbuser1 wrote:
    nemo666 wrote:
    Here is the job description
    We are looking for 100 Website Managers with the following qualifications:What is a website manager?
    1. Willing to work on a part-time basis (you can work on your own hours)
    2. Must know how to use the Internet &#150; doing research, sending emails, etc
    3. Average written English skills
    4. Be able to write fresh and original content
    5. Be able to provide website updates on a regular basisSounds like you need web developers, software engineers, and graphic designers.
    We will be offering qualified applicants with the following:
    1. Free website hosting
    2. A domain of your choice
    3. Onsite marketing assistance
    4. Website maintenance
    5. Content gathering technique seminars
    6. Revenue to be paid monthlyTechnically irrelevant here.
    so those are the requirements...i want to learn web based java or j2ee while doing this part time job
    so what are the best things should i request to them that should be install in their webserver so that I can run .jsp and etc. for as long as it is all about java. ???This depends on many, many factors. Hire a J2EE architect NOW, before you do anything you'll regret.well im planning to create a wordpress looking site. however, i wanna use .jsp and etc. as long as it has something to do with java... its only a part time job.. the employers purpose is to get a website manager that will right a content for a certain topic..well its a great advantage for me..while ill be doing this job..so whats irrelevant in there? almost everything
    im just asking to all of you on what are the required softwares that must be install in their webserver so that i can sail smooth with javahire a Java/J2EE programmer if you want to do this
    you have NO CLUE what you're doing here
    you're in way over your head and you're going to waste a lot of time and money
    i'm not trying to be rude, but you aren't getting the hint
    given what you know, there is no chance your project will succeed unless you get some help
    there's also no chance anyone here will reply to you unless you ask a specific question
    you can't say you want some site that looks like some other site and then ask what you should install
    it's vastly more complex than that
    the requirements you've provided ARE NOT TECHNICAL and are thus TECHNICALLY IRRELEVANT
    why don't you write a technical design doc then come back
    if you can write that document, i'll have more faith in you and your project

  • SQLException while trying to retrieve data from text file DB

    This was originally posted in the Java Fundamentals forum,
    http://forum.java.sun.com/thread.jspa?threadID=733857&tstart=10
    thought I might have a better chance of getting help here.
    I'm just beginning to learn JDBC stuff. I have a text file acting as my DB. So far I've been able to add rows to the table, but when I try and retrieve something from the table I get the following exception.
    java.sql.SQLException: [Microsoft][ODBC Text Driver] The Microsoft Jet database engine cannot open the file '(unknown)'.  It is already opened exclusively by another user, or you need permission to view its data.That '(unknown)' bit seems suspicious, but I don't how I would correct it. My file is set up similar to the sun tutorial I'm going through, and it doesn't specifiy the file name anywhere but the SQL statement.
    All the permissions seem to be correct from what I can tell. The file isn't opened or in use anywhere else that I can see.
    I've tried googling parts of the error message, but most of the reponses are dealing with MS Access or aren't java related and so far I haven't found anything helpful.
    Below is my sample code.
    * Created on May 4, 2006
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    public class DBProcessor {
         static Connection con;
         public static void main(String[] args) {
              HandiAppDBProcessor app = new HandiAppDBProcessor();
    //          insertNamesIntoDB("John", "Doe", "Good");
              retrieveNamesFromDB();
         public HandiAppDBProcessor() {
              super();
         public static void establishDBConnection() {
              try {
                   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                   String url ="jdbc:odbc:TextDB";
                   con = DriverManager.getConnection(url,"myLogin", "myPassword");
              } catch (ClassNotFoundException excptn) {
                   System.out.println("***** ClassNotFoundException thrown");
                   excptn.printStackTrace();
              } catch(SQLException excptn) {
                   System.out.println("***** SQLException - Connection Failed");
                   excptn.printStackTrace();
         public static void insertNamesIntoDB(String firstNameIn, String lastNameIn, String standingIn) {
              try {
                   establishDBConnection();
                   String firstName = firstNameIn;
                   String lastName = lastNameIn;
                   String standing = standingIn;
                   Statement stmt = con.createStatement();
                   String query = "insert into CONTACTS values ('" + firstName +
                                       "', '" + lastName +
                                       "', '" + standing + "');";
                   stmt.execute(query);
              } catch(SQLException excptn) {
                   System.out.println("***** SQLException - Connection Failed");
                   excptn.printStackTrace();
         public static void retrieveNamesFromDB() {
              try {
                   establishDBConnection();
                   Statement stmt = con.createStatement();
                   String courseQuery = "SELECT FIRST_NAME FROM CONTACTS";
                   ResultSet rs = stmt.executeQuery(courseQuery);
                   while (rs.next()) {
                        String courseName = rs.getString("FIRST_NAME");
                        System.out.println("firstName = " + firstName);
              } catch(SQLException excptn) {
                   System.out.println("***** SQLException - Connection Failed");
                   excptn.printStackTrace();
    }Of course you won't be able to run it unless you take the time to create a text file and set it up as a data source, which I don't expect anyone to do. I was just hoping someone more experienced than I had seen this before or could spot something in my code.
    Any help in any way would be appreciated.
    Thanks

    When you were setting up your ODBC data source for
    the Text driver, did you click on the "Options"
    button? There's a lot of options in there that I
    didn't understand at first glance.Yes I clicked on the options button, but the only thing there is dealing with file extensions. I left it set to the default.
    I have since tried closing my connection after I insert a record, I then try executeQuery, but still no luck. Seems strange that I can write to the file but not read from it. If any thing I'd expect the opposite problem.
    I have also tried using the class "JoltReport" from the sun tutorial instead of my own with the same result.
    Message was edited by:
    Hentay

  • Help with program plz (long code)

    anyone know how i can fix these 2 errors:
    Driver2.java:47: code is already defined in main(java.lang.String[])
    String code = JOptionPane.showInputDialog(
    ^
    Driver2.java:51: incompatible types
    found : java.lang.String
    required: int
    int val = bc.getCode();
    ^
    the case 2 in the driver is where it messes up, i believe..it works with just the case 1...any help/advice is appreciated(i am aware of spacing errors)
    import javax.swing.JOptionPane;
    import java.util.Scanner;
    public class Driver2
       public static void main(String[] args)
          String userChoice;
          int choice;
    Scanner keyboard = new Scanner(System.in);
    userChoice = JOptionPane.showInputDialog("Enter 1 to enter a numeric zip code:\n"
    + "Enter 2 to enter a bar code:\n"
    + "Enter 3 to exit program:\n");
    choice = Integer.parseInt(userChoice);
    while (choice != 3)
           switch (choice)
           case 1:
           String input = JOptionPane.showInputDialog( "Please enter a five-digit zip code: ");
    int num = Integer.parseInt(input);
    BarCode bc = new BarCode(num);
    String code = bc.getCode();
    JOptionPane.showMessageDialog(null, "The barcode of the zip is: " + code);
    System.exit(0);
    break;
    case 2:
    String code = JOptionPane.showInputDialog( "Please enter bar code: ");
    int val = bc.getCode();
    if (val >= 0)
    System.out.println("The zip code is: " + val);
    else
    System.out.println("Incorrect bar code data");
    System.exit(0);
    break;
    case 3:
    break;
    userChoice = JOptionPane.showInputDialog("Enter 1 to enter a numeric zip code:\n"
    + "Enter 2 to enter a bar code:\n"
    + "Enter 3 to exit program:\n");
       public BarCode(int n)
          zip = n;
       public String getCode()
          String barCode = "|";
          int sum = 0;
          int temp = 0;
          temp = zip / 10000;
          sum = sum + temp;
          Digit d1 = new Digit(temp);
          barCode = barCode + d1.getCode();
          zip = zip % 10000;
          temp = zip / 1000;
          sum = sum + temp;
          Digit d2 = new Digit(temp);
          barCode = barCode + d2.getCode();
          zip = zip % 1000;
          temp = zip / 100;
          sum = sum + temp;
          Digit d3 = new Digit(temp);
          barCode = barCode + d3.getCode();
          zip = zip % 100;
          temp = zip / 10;
          sum = sum + temp;
          Digit d4 = new Digit(temp);
          barCode = barCode + d4.getCode();
          zip = zip % 10;
          temp = zip;
          sum = sum + temp;
          Digit d5 = new Digit(temp);
          barCode = barCode + d5.getCode();
          temp = 10 - (sum % 10);
          Digit d6 = new Digit(temp);
          barCode = barCode + d6.getCode() + "|";
          return barCode;
       private int zip;
    public class BarCode1
       public BarCode1(int n)
          zip = n;
       public String getCode()
          String barCode = "|";
          int sum = 0;
          int temp = 0;
          temp = zip / 10000;
          sum = sum + temp;
          Digit d1 = new Digit(temp);
          barCode = barCode + d1.getCode();
          zip = zip % 10000;
          temp = zip / 1000;
          sum = sum + temp;
          Digit d2 = new Digit(temp);
          barCode = barCode + d2.getCode();
          zip = zip % 1000;
          temp = zip / 100;
          sum = sum + temp;
          Digit d3 = new Digit(temp);
          barCode = barCode + d3.getCode();
          zip = zip % 100;
          temp = zip / 10;
          sum = sum + temp;
          Digit d4 = new Digit(temp);
          barCode = barCode + d4.getCode();
          zip = zip % 10;
          temp = zip;
          sum = sum + temp;
          Digit d5 = new Digit(temp);
          barCode = barCode + d5.getCode();
          temp = 10 - (sum % 10);
          Digit d6 = new Digit(temp);
          barCode = barCode + d6.getCode() + "|";
          return barCode;
       private int zip;
    public class Digit
       public Digit(int n)
          zip = n;
       public String getCode()
          String bar = "";
          if (zip == 1)
             bar = ":::||";
          else if (zip == 2)
             bar = "::|:|";
          else if (zip == 3)
             bar = "::||:";
          else if (zip == 4)
             bar = ":|::|";
          else if (zip == 5)
             bar = ":|:|:";
          else if (zip == 6)
             bar = ":||::";
          else if (zip == 7)
             bar = "|:::|";
          else if (zip == 8)
             bar = "|::|:";
          else if (zip == 9)
             bar = "|:|::";
          else
             bar = "||:::";
          return bar;
       private int zip;
    public class Digit1
       public Digit1(int n)
          zip = n;
       public String getCode()
          String bar = "";
          if (zip == 1)
             bar = ":::||";
          else if (zip == 2)
             bar = "::|:|";
          else if (zip == 3)
             bar = "::||:";
          else if (zip == 4)
             bar = ":|::|";
          else if (zip == 5)
             bar = ":|:|:";
          else if (zip == 6)
             bar = ":||::";
          else if (zip == 7)
             bar = "|:::|";
          else if (zip == 8)
             bar = "|::|:";
          else if (zip == 9)
             bar = "|:|::";
          else
             bar = "||:::";
          return bar;
       private int zip;
    }

    > i got it to compile now...i can toy around w/
    it..thanks for the help
    Good.
    Stick with this handle, ok?I must say I am not thrilled with
    a) when I questioned the first post of WhiteSox asking if it was bugz or a classmate or what I was ignored by the OP
    b) I guess the OP is trying to distance himself from his very first thread where somebody did part of his homework for him with results that are now plainly evident. As I predicted at the end of the last thread.
    http://forum.java.sun.com/thread.jspa?threadID=703258 Reply 11
    I hope that matsabigman and others who help homework posters by doing it for them will take note of the results of this help thus far. Not much good has come of this.
    BigMan/WhiteSox I am still detecting a fundamental lack of basic concepts on your part. This is the underlying cause of your compile errors but those are only a symptom. You can continue treating the symptoms but it would be a better use of your time to treat the disease, which in this case means spending some time getting a better grasp of Java fundamentals.

  • What's happen?????????

    i wrote a program which is calculate the value of (e), but when i excute it the JOption dialoge doesnot apear.
    although the the process of compiling is completed
    my prog. is:
    import javax.swing.JOptionPane;
    public class ch32_b
    public static void main(String[] ss)
         int i,N=1;
         double k=1, f=1;
              while(N>0)
                   for(i=1;i<=N;i++)
                             k=k*i;
                             f+=1.0/k;
              N++;
    JOptionPane.showMessageDialog(null,"the value of e"+f);
         System.exit(0);     

    "...not too difficult to pick up..." - maybe for someone who already knows Java. What good does an IDE do someone who hasn't figured out CLASSPATH?
    Even for seasoned professionals, I'd say that if you're spending a lot of time in a debugger you're doing something very wrong. JMO, of course.
    There are few problems that a newbie is working on that a few well-placed println statements won't narrow the problem down pretty quickly. Being able to do that well is a skill that will serve you well for those times when an IDE isn't available to you.
    An IDE/debugger can't help much with Web apps, unless it has a servlet engine/EJB server running inside it. Most of the time when I put things in production I'm happy to have a good log file to look at. There isn't much choice about using a debugger to find out what's wrong. In those cases, the important thing is debugging where the app lives. Problems might be showing up because the environment isn't right. Moving everything back into an IDE could mask the problem.
    '...one might ponder if one should be in another line of work..." - perhaps you're right, but I wouldn't make that decision based on the fact that learning Java AND an IDE can be overwhelming.
    All I'm saying is that computer scientists solve complex problems by breaking them down into smaller, more manageable ones. I think the same thinking should be applied here. Don't complicate the learning of Java fundamentals by tossing an IDE into the mix. - MOD

  • Superclass Constructor calling overridable validation method

    I have the following class:
    public class SuperClass
       private int x;
       public SuperClass(int x)
          setX(x);
       protected void validateX(int x)
          if(x < 0)
             throw new IllegalArgumentException("x < 0");
       public int getX()
          return x;
       public void setX(int x)
          validateX(x);
          this.x = x;
    }My question is: How can I avoid calling setX(int) in the constructor besides simply dupicating validateX(int) in the constructor if I want to subclass SuperClass? [I read in a recent Java Fundamentals newsletter that calling overridable methods in superclass constructors is a bad idea int that it tends to destabilize the whole class hierarchy.  I don't want to make validateX(int) and setX(int) final.]

    Never call overrideable methods from constructors. No exceptions.
    You can use a factory method to validate your object after its created if you must.
    public class SuperClass
       private int x;
       public SuperClass()
       static SuperClass createSuperClass(int x){
             SuperClass sc = new SuperClass();
             sc.setX(x);
             return sc;
       protected void validateX(int x)
          if(x < 0)
             throw new IllegalArgumentException("x < 0");
       public int getX()
          return x;
       public void setX(int x)
          validateX(x);
          this.x = x;
    }Or you can use template method
    public class SuperClass
    private int x;
    public SuperClass(int x)
    setXImpl(x);
    final protected void validateX(int x)
    if(x < 0)
    throw new IllegalArgumentException("x < 0");
    public int getX()
    return x;
    final void setXImpl(int x){
    validateX(x);
    this.x = x;
    public void setX(int x)
    setXImpl(x);
    In general I don't like to call any overrideable methods from within my class. I try not to be anal about it though. My personal choice would be to duplicate the set method in the constructor. You should be constructing the object not using it. access instance variables not methods.

  • Hello, please introduce any resource for ACA and ACE exam (book and sample tests)?

     

    Have a look at the Oracle Press Books site http://bit.ly/wgk7gP. I don't think they have any books specific to this exam, but they have Java fundamentals books.
    Regards,
    Brandye Barrington
    Certification Forum Moderator

  • Why is my class Serializable?

    I'm very new to Java and I'm doing the examples from the Java Fundamentals - Volume I book. The IDE I'm using (Eclipse) reports the following warning for just about every Swing class I create:
    The serializable class MulticastPanel does not declare a static final serialVersionUID field of type long
    However, the class does not implement Serializable.
    JFrame, which MultiCastPanel extends, implements Serializable. But then shouldn't JFrame declare a static final serialVersionUID field of long?
    What am I doing wrong?
    Thanks,
    -Jeff

    I'm very new to Java and I'm doing the examples from
    the Java Fundamentals - Volume I book. The IDE I'm
    using (Eclipse) reports the following warning for
    just about every Swing class I create:
    The serializable class MulticastPanel does not
    declare a static final serialVersionUID field of type
    long
    However, the class does not implement Serializable.
    JFrame, which MultiCastPanel extends, implements
    Serializable. But then shouldn't JFrame declare a
    static final serialVersionUID field of long?
    What am I doing wrong?The previous explanation didn't seem to make it clear that this occurs because you are inheriting that whether you want it or not.
    You can ignore the warning.
    I suspect there is a way to turn off the warning in Eclipse.

  • Book and Site Recomendations?

    Hi,
    I'm fairly new to Java. I took a Java Fundamentals class back in Dec. and have been doing some light programming. I want to become a well rounded programmer in the language. My question is, What books and websites would you all recommend to someone who is looking to expand and is looking for good exercises to become a better programmer?
    Thanks for any help.
    -Michael

    I'm finding "Exam Cram, Java 2" by Bill Brogden of Certification Insider Press to be a good read that covers the fundimentals that you should know. I've been programming in Java for a few years and it's taught me a lot.
    Nick

  • Java Technology Fundamentals Chat Transcript Available

    The transcript of the September 30 online chat on Java Technology Fundamentals, with guest John Zukowski, is now available at http://java.sun.com/jdc/community/chat/JavaLive/2003/jl0930.html.
    John answered a range of questions about Java technology -- anywhere from "What does "typesafe" mean?" to "Where might I find clear information about whether and when the garbage collector returns memory to the OS?"

    The transcript of the September 30 online chat on Java Technology Fundamentals, with guest John Zukowski, is now available at http://java.sun.com/jdc/community/chat/JavaLive/2003/jl0930.html.
    John answered a range of questions about Java technology -- anywhere from "What does "typesafe" mean?" to "Where might I find clear information about whether and when the garbage collector returns memory to the OS?"

Maybe you are looking for

  • Playback of clips only plays between 4 and 12 frames

    Hi all, I am fairly new to Premiere, have used After Effects CS4 to produce some clips, but need something that handles editing better, and I thought I would give Premiere CS4 a try. Unfortunately, I can't get Source or Sequence preview working.  I c

  • FF logs in different location ( Not FF tables)

    Hi Can we have FF logs in different location other than the backend tables? My client wants to have the sensitive FI and HR data logs maybe in a share restricted network drive / folder. Is this worth it? If anyone has done this, please share your exp

  • Landing Charges

    Hi Gurus In imports po i want the landing charges 1% to be propsed automatically in the PO conditions . How do I do it? Regards

  • HT201252 How do I recover old imessage messages that have not been deleted?

    I have not deleted any messages, but older ones are not showing up. Is there a way to get these back? Working on a Macbook Pro

  • Someone's trying to break into server

    Hello, According to my directory service log, someone is trying to break into our server by trying to log in as 'root' and 'admin'. DirectoryServices senses this and delays the failed authentication return. Okay, how do we backtrace this fellow's IP