Need help with starting a simple calculator

I have this simple calculator I just started on, and I'm having just a few problems. First of all, I don't know how to append text to a textfield. Maybe I would have to create a string buffere or something. Then, when the user clicks one of the buttons, the compiler goes crazy, and nothing is displayed.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JFrame implements ActionListener
     JButton[] btnNums;
     JButton btnBack;
     JButton btnClear;
     JButton btnCalculate;
     String[] strNames;
     JTextField txtDisplay;
     public Calculator()
          Container content = getContentPane();
          setSize(210,250);
          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          /*  construct a JPanel and the textfield that
           *  will show the inputed values and outputed
           *  results
          JPanel jpDisplay = new JPanel();
          jpDisplay.setLayout(new BorderLayout());
          txtDisplay = new JTextField(15);
          txtDisplay.setHorizontalAlignment(JTextField.RIGHT);
          jpDisplay.add(txtDisplay);
          /*  contstruct a JPanel that will contain a back
           *  button and a clear button.
          JPanel jpRow2 = new JPanel();
          btnBack = new JButton("Backspace");
          btnClear = new JButton("Clear");
          btnClear.addActionListener(this);
          jpRow2.add(btnBack);
          jpRow2.add(btnClear);
          /*  construct a string array with all the names of the
           *  buttons, then in a for loop create the new buttons
           *  and add their name and an actionListener to them.
          String[] strNames = {"7","8", "9","/", "4", "5", "6","*", "1", "2", "3","+", "0", "+/-", ".", "-"};
          btnNums = new JButton[16];
          JPanel jpButtons = new JPanel();
          jpButtons.setLayout(new GridLayout(4,4));
            for (int i = 0; i < 16; i++)
                 btnNums[i] = new JButton(strNames);
               btnNums[i].addActionListener(this);
               jpButtons.add(btnNums[i]);
          /* construct the final JPanel and add a
          * calculate button to it.
          JPanel jpLastRow = new JPanel();
          btnCalculate = new JButton("Calculate");
          btnCalculate.addActionListener(this);
          jpLastRow.add(btnCalculate);
          /* set the contentPane and create the layout
          * add the panels to the container
          setContentPane(content);
          setLayout(new FlowLayout());
          setResizable(false);
          content.add(jpDisplay, BorderLayout.NORTH);
          content.add(jpRow2);
          content.add(jpButtons);
          content.add(jpLastRow);
          setTitle("Mini Calculator");
          setVisible(true);
     public void actionPerformed(ActionEvent ae)
          for (int i =0; i < 16; i++)
               if (ae.getSource() == btnNums[i])
                    txtDisplay.setText(strNames[i]);
     public static void main(String[] args)
          Calculator calc = new Calculator();

First of all, I don't
know how to append text to a textfield.
textField.setText( textField.getText() + TEXT_YOU_WANT_TO_APPEND );
Then,
when the user clicks one of the buttons, the compiler
goes crazy, and nothing is displayed.No, the compiler doesn't go crazy, the compiler has done it's job by then. However, you do get a NullPointerException, and the stacktrace tells you that the problem is on the following line:
txtDisplay.setText(strNames);
It turns out that strNames is null. I leave it to you to find out why. ;-)

Similar Messages

  • Need Help with Average of a calculated field

    Good Morning ,
    In the cube that i built i have a calculated field "AvgAbandonTime"=round(([Measures].[C8]/[Measures].[C9]),0). C8 and C9 in the calculation are calculated fields in the DSV based off the fields from the Database.
    In the browser i'm having a problem. In the below sample data set , if you look i'm calculating the "AvgAbandonTime" per each location and this value is in seconds. C8 and C9 are the fields used in the calculation. For example C8/C9=11588/126=92
    (ROUNDED).Similarly for the other two rows. The problem is when it comes to the Grand Total , i'm expecting average of AvgAbandonTime over the 3 locations and that should be (92+16+73)/3=60, but where as what its doing is Summing all the C8 and all
    the C9 values and giving me the SUM(C8)/SUM(C9)=74. Please need help or advice.
    Thanks

    Thanks David,
    But no its not giving those values instead its giving
    C8
    C9
    Avg
    AvgAbandonTime11
    newcalc
    sum
    11588
    126
    92
    8191
    8191
    24753
    157
    10
    16
    157
    157
    24753
    62160
    857
    73
    16405
    16405
    24753
    GrandTotal
    73905
    993
    74
    99
    1.#INF
    24753

  • Need help with date and time calculations please

    Hello there.. Im stuck, and im hoping someone can help..
    Working on a list to manage and track PTO.  User completes PTO request form,
    Fields
    Name
    Start Date (with time)
    End Date (with time)
    Total Number of Days/hours requested: (calculation)
    Full Day: (Yes/No)
    ok business need
    user has the ability to request a certain number of hours as opposed to a full day.
    After searching around on google. I found this calculation to help me figure out how many BUSINESS days being requested.
    =IF(ISERROR(DATEDIF([Start Date],[End Date],"d")),"",(DATEDIF([Start Date],[End Date],"d"))+1-INT(DATEDIF([Start Date],[End Date],"d")/7)*2-IF((WEEKDAY([End Date])-WEEKDAY([Start Date]))<0,2,0)-IF(OR(AND(WEEKDAY([End
    Date])=7,WEEKDAY([Start Date])=7),AND(WEEKDAY([End Date])=1,WEEKDAY([Start Date])=1)),1,0)-IF(AND(WEEKDAY([Start Date])=1,(WEEKDAY([End Date])-WEEKDAY([Start Date]))>0),1,0)-IF(AND(NOT(WEEKDAY([Start Date])=7),WEEKDAY([End Date])=7),1,0))
    This works great as long as its a [Full Day]="YES", displays results in column labeled Number of days
    now if [Full Day]="No", displays results in column labeled Number of Hours
    BUT this is my issue (well part of it) it calcuate the correct number of hours.. but puts a "1" in "Number of Days" why.. dates have not changed.. I think Its something with the above calculation but I could be way off.
    the end result is I need number of days to concat with number of hours 
    i.e 1 full day 4 hours  1.4
        0 full day 5 hours  0.5
        1 full day 0 hours  1.0
    so that the total can be deducted via workflow.. from the remaining balance in a tracker. (seperate list) 
    Any angels out there??

    Posnera-
    Try changing time zones and see if the travel itinerary times change.
    Fred

  • Need Help with a very simple view transition scenario

    Hello All,
    I am trying to learn how view transitions work and I am having a very hard time with the sample apps (like transition view app etc)...I need something much more simple at first. Can you please provide me a little guidelines on how to set up this following scenario:
    App loads up and shows a title screen with a button that says go. When you click on the go button the title screen fades out and a new view fades in (or slides in, or anything at all).
    Right now I have 3 nib files. There is the main one that is called on application start (tied with MainViewController, a subclass of IUViewcontroller just like in the hello world app. After the app loads the app delegate object tells the MainViewController object to load in another view controller object (via addSubview) which is tied with the second nib file; my title screen with the button. When I press the button I was thinking in the IBAction function to tell the MainViewController object to remove (or transition out somehow) the title screen view controller object then add the other view (third nib file in). This is the part I can't get working. Am I on the right track or have a gone hideously astray? Thank you!

    hi,
    i managed to do this for my app. (think i referred to viewTransitions sample code and modified quite a bit)
    i can't remember this well cos i did this quite a while back, but i will try to help as much as possible
    1) from the appdelegate i initialize a root controller (view controller class)
    2) this root controller actually contains two other view controllers, let's call it viewAController and viewBController, for the screens which u are going to toggle in between. and there's also a function, let's call it toggleMenu, which will set the menus to and fro. i copied this whole chunk from the sample code. it actually defines the code on what to do, i.e. if current view is A switch to B and vice versa.
    3) inside the controller files, you need to implement the toggleMenu function too, which basically calls the rootController's toggleMenu
    4) we also need viewA and viewB files(view class)
    5) need to add the .xib files for the respective views and link them up to the controller class. i did not use the .xib files for ui layout though, because of my app's needs. however, it will not work properly without the .xib files.
    5) inside the view class of both views, i.e. viewA.m and viewB.m, you need to create a button, that will call the toggleMenu function inside the respective controller class.
    it will look something like this:
    [Button addTarget:ViewAController action:@selector(toggleMenu:) forControlEvents:UIControlEventTouchUpInside];
    so the flow is really button (in view)-> toggleMenu(viewController) -> toggleMenu(rootController)
    i'm sorry it sounds pretty hazy, i did this part weeks before and can't really remember. i hope it helps.

  • Need help with something VERY SIMPLE

    I'm brand new to Motion - as if today - but I'm only trying to do some VERY simple motions with photos - a simultaneous zoom in and reposition. What I've been doing is setting the starting key frame at one position (adjusting the x, y) and setting the scale. Then I create a second key frame and adjust the postion and scale. It will do the zoom, but then it re adjusts the starting position. If I readjust the starting key frame, it automatically readjusts the second key frame. I don't get it! Applying the various 'behaviors' doesn't seen to help. Certainly there's something obvious here that I'm missing - as I was able to do this in FCP. For some reason the key frames are not fixed when it comes to position.

    hi,
    a couple of thoughts?
    did you actually set a keyframe for position at the first frame?
    Also unless you are parked right on a keyframe or have the record button on, if you adjust a value, all the values for all keyframes adjust accordingly. I often mess something up because I wasnt parked on a keyframe.
    hth
    adam

  • New User needs help with starting SDK

    I downloaded the J2EEsdk-1_4 files and completed the installation. I have looked at all the tutorials and quick-start documentation, but cannot find how to begin building an application. All I needed was very minimal Java parts to write a "Hello World" program for a class, but it prompted me to get the whole package.
    How do I get to a prompt window to write some code, then compile it, then run it? I tested the local server as it suggested and it is working, and I ran their sample program and it worked.
    I just need a pointer to get me started. I don't need all the web deployemnt stuff, etc....
    Sorry for the silly questions but you gotta start somewhere.
    Thanks

    Brent In Iowa, you're on the Air.
    Thanks for taking my call, Larry.
    Umm, yes, I'd like to ask Mr. McNealy a question.
    Go ahead.
    umm, yes, Mr. McNealy. I like your language
    Thanks, Brent. We hope with developers like you, to make it the most widely used language in the world. It's people like you that will helps us squash that bastard Gates and make me...umm, I mean Sun Microsystems the richest company known to man-kind.
    Yeah but that's my problem Mr. McNealy. How do I write Hello World?
    First, Brent, ya gotta download the right SDK. Not the J2EE but the J2SE. Then ya gotta follow the links on the let for the tutorials.
    Thanks for your question. Our next caller, George is in Boise, Idaho. Hello, Boise.

  • Need help with starting over in LR

    I realized that my importing process is creating an image folder structure in LR that does not mirror my HD image folder structure, so I need to begin again. Thankfully I just started and only imported a couple hundred photos w/o many edits and have created 6 folders.
    My question: what's the best way to clean out LR for a new start? Should I simply delete the LR catalog then reimport? Or should I delete the images from LR (leaving them on my HD, of course) then reimport? Does it even matter which route I choose?
    Finally, to get the folder structures to match (LR folders and HD folders to mirror each other), what do I need to do? I have thousands of photos I will be eventually importing, and I want the file structure in LR to match my HD. The top images folder on my HD is simply called "PHOTOS." Beneath that is "FAMILY" "STUDENTS" and "PHOTO SHOOT" and then there are subs below those.
    If I bring in the top  "Photos" folder, all the others will follow and then I will have thousands to process in one import, and I know this would not be the way to go.
    So, how can I match the folder structures while only importing a handful at a time? Do I somehow create a folder in LR called "Photos" or do I import the actual "photos" folder from my HD. Just a little unclear about all this and appreciate any advice.
    Thanks.

    I realized that my importing process is creating an image folder structure in LR that does not mirror my HD image folder structure, so I need to begin again.
    When you do an import, the LR folder structure automatically matches your HD structure. You only get this problem if you move or rename the folders/photos in Windows Explorer or Mac Finder. For a beginner, you probably shouldn't be moving/renaming photos/folders outside of Lightroom; you should move photos/folders inside of Lightroom.
    My question: what's the best way to clean out LR for a new start? Should I simply delete the LR catalog then reimport? Or should I delete the images from LR (leaving them on my HD, of course) then reimport? Does it even matter which route I choose?
    If you delete the photos from Lightroom and reimport, you lose a lot of information. This is not recommended and should definitely be a last resort, only if you can't fix the Lightroom catalog. It is relatively easy, since you don't have a lot of photos, to fix this in Lightroom ... for each folder that has a question mark indicating it doesn't know where the photos are, right-click on it and select Update Folder Location. Then, stop moving your folders/photos in the operating system.
    Finally, to get the folder structures to match (LR folders and HD folders to mirror each other), what do I need to do? I have thousands of photos I will be eventually importing, and I want the file structure in LR to match my HD. The top images folder on my HD is simply called "PHOTOS." Beneath that is "FAMILY" "STUDENTS" and "PHOTO SHOOT" and then there are subs below those.
    As I said, you stop using Windows or Mac to move or rename your photos and folders. Problem solved.
    However, I believe you have adopted a fundamentally flawed and inefficient approach in your use of folders. In Lightroom, folders are no longer organizing tools; they are simply storage locations. Lightroom gives you much more efficient and superior organizing tools (keywords, metadata, collections), and it is best if you abandon these thoughts of organizing via folders. Instead, you make these descriptions into Keywords in Lightroom, and you leave your photos in whatever folder they happen to be in, with whatever name the folders currently have. Keywords are not limited the way folder hierarchies are ... a photo can be in only one folder and one hierarchy; whereas a photo can have many keywords and exist in many hierarchies. This gives you the ability to search on many many different criteria in Lightroom, which is much more flexible.
    So to sum up ... fix your catalog, as described above. Then, do not think about folders; do not rename or move folders; just leave them exactly as they exist. From this point on, you organize with Lightroom tools.

  • Need help with a very simple example.  Trying to reference a value

    Im very new to Sql Load and have created this very simple example of what I need to do.
    I just want to reference the ID column from one table to be inserted into another table as DEV_ID.
    Below are my: 1) Control File, 2) Datafile, 3) Table Description, 4) Table Description
    1) CONTROL FILE:
    LOAD DATA
    INFILE 'test.dat'
    APPEND
    INTO TABLE p_ports
    FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
    DEV_id REF(CONSTANT 'P_DEVICES',NAME),
    NAME FILLER ,
    PORT_NO
    2) DATAFILE:
    COMM881-0326ES09,6
    3) TABLE DESCRIPTION:
    SQL> describe p_ports
    Name Null? Type
    ID NOT NULL NUMBER(10)
    DEV_ID NOT NULL NUMBER(10)
    PORT_NO     NUMBER(3)

    hi,
    i managed to do this for my app. (think i referred to viewTransitions sample code and modified quite a bit)
    i can't remember this well cos i did this quite a while back, but i will try to help as much as possible
    1) from the appdelegate i initialize a root controller (view controller class)
    2) this root controller actually contains two other view controllers, let's call it viewAController and viewBController, for the screens which u are going to toggle in between. and there's also a function, let's call it toggleMenu, which will set the menus to and fro. i copied this whole chunk from the sample code. it actually defines the code on what to do, i.e. if current view is A switch to B and vice versa.
    3) inside the controller files, you need to implement the toggleMenu function too, which basically calls the rootController's toggleMenu
    4) we also need viewA and viewB files(view class)
    5) need to add the .xib files for the respective views and link them up to the controller class. i did not use the .xib files for ui layout though, because of my app's needs. however, it will not work properly without the .xib files.
    5) inside the view class of both views, i.e. viewA.m and viewB.m, you need to create a button, that will call the toggleMenu function inside the respective controller class.
    it will look something like this:
    [Button addTarget:ViewAController action:@selector(toggleMenu:) forControlEvents:UIControlEventTouchUpInside];
    so the flow is really button (in view)-> toggleMenu(viewController) -> toggleMenu(rootController)
    i'm sorry it sounds pretty hazy, i did this part weeks before and can't really remember. i hope it helps.

  • New timecapsule need help with start up

    I recently switched to an iMac from a Dell and now am trying to add a timecapsule primarily for automated back up although if I can use the print feature that would be a nice added benefit. I have a modem/router from Consolidated Communications which is located in a different room than my computer. My preference would be to have the timecapsule located with the computer so that I can back up more quickly over ethernet and have my printer plugged into the timecapsule so that my iPad and other laptops can access it. Is this possible? I have tried setting the timecapsule up wireless as well as plugged directly into the router, in both cases I cannot get a valid ip address and then have trouble with my iMac accessing my existing network as it tries to connect through the timecapsule rather than to my current network via the built in airport. Thanks in advance for your help.

    Can I join that network wirelessly so that I can have the TC in the rom with the computer (far from the router/wireles modem) and still use ethernet connection and USB for printer?
    Yes, with two caveats: 1) It will really depend on the distance and what obstructions are between the other wireless router and the TC to determine how well the TC can connect to its wireless network, and 2) Configured to join, the TC's Ethernet ports will not be enabled. However, its USB port will.
    These two items may preclude it being the desired end state that you are looking for. Typically to enable the TC to also provide network connectivity (either by wire or wireless), it would have to be configured for a WDS. Unfortunately, most non-Apple routers are not WDS-compatible.
    This leaves you with at least two choices: 1) Connect the two routers by Ethernet or if that is not practical or desirable, consider Powerline adapters, or 2) Configure the TC as a standalone wireless router. With the second option, you would have to switch wireless networks to print or perform Time Machine backups ... again, not a viable solution.
    I would suggest considering the Powerline adapter approach for your situation.

  • Java Newbie needs help with multi method dialog calculator

    Our example for the unit was the example below... we now must create a 5 method program for a calculator... 1 main method and 4 for the standard operations(+ - * /). It is supposed to utilize Swing for graphics/dialog boxes that ask you for the operation you would like to use(if statements based on which operation they enter), and a prompt that asks you separately for the 2 numbers used.... anyone feel like drawing this skeleton out? I am in class right now and none of my neighbors can figure it out either....
    import javax.swing.JOptionPane;
    public class Payroll
         public static void main(String[] args)
         String name;         //the user's name
         String inputString;  //holds input
         int hours;           //hours worked
         double payRate;      //hourly pay wage
         double grossPay;     //total pay
         //getUser
         name = JOptionPane.showInputDialog("What is your name?");
         //getHours
         inputString = JOptionPane.showInputDialog("How many hours did you work?");
         hours = Integer.parseInt(inputString);
         //getRate
         inputString = JOptionPane.showInputDialog("What is your hourly pay rate?");
         payRate = Double.parseDouble(inputString);
         //setGross
         grossPay = payRate * hours;
         //showGross
         JOptionPane.showMessageDialog(null, "Hello " + name + ". Your gross pay is: " + grossPay); 
         //End
         System.exit(0);
    }

    import javax.swing.JOptionPane;
    public class CalcDiag
         public static void main(String[] args)
         String operation;
         String inputString;
         double num1, num2, total=0;
         inputString = JOptionPane.showInputDialog("What is your first number?");
         num1 = Double.parseDouble(inputString);
         inputString = JOptionPane.showInputDialog("What is your second number?");
         num2 = Double.parseDouble(inputString);
         inputString = JOptionPane.showInputDialog("Please indicate which operation you would like to use: A,S,M,D ?");
         operation = inputString;
         if (operation.equals("A"))
              total = getAdd(num1, num2);
         if (operation.equals("S"))
              total = getSub(num1, num2);
         if (operation.equals("M"))
              total = getMult(num1, num2);
         if (operation.equals("D"))
              total = getDiv(num1, num2);
         JOptionPane.showMessageDialog(null,"Total = "+total);
         System.exit(0);
    public static double getAdd(double x, double y)
              return x+y;
    public static double getSub(double x,double y)
              return x-y;
    public static double getMult(double x, double y)
              return x*y;
    public static double getDiv(double x, double y)
              return x/y;
    }your welcome

  • Need help with start up.

    I let my my uncle use the internet on my macbook and he shut it down. But now when i go to turn it on, it takes forever on the first loading screen with the apple symbol. And after that is done it goes to the blue screen and just sits there. What should i do, this is my first mac so i really dont know how to work on this.
    THanks
    Andy

    Insert disc that came with macbook - hold c while it boots then do disk utility from disc. Then boot into safe mode to have the file system checked automatically (or do the file system check yourself in Single User Mode).

  • Hi, I need help with starting off my iphone 3GS

    I tried to register my iphone. Can't do it . I have these IMEI  and ICCID numbers but wasn't asked for them yet. Am I doing something wrong?
    Please, help.

    All you should have to do is plug it into iTunes and activate it.
    Where are you? Where did you get the phone, and who is your carrier?

  • Need help to start with some file and text manipulation

    Hello script mavens,
    I need help with starting a script that does the following:
    -within a base folder it takes an inventory (list?) of all the files (which happen to be image files).
    -creates a new folder inside the base folder and calls it imagesX where X increases by one every time the script is run
    -moves all the files into the images folder
    -within the base folder it creates a new text file and calls it imagesX.js
    -writes a "//-" into imagesX.js
    -then writes the list of filenames into the imagesX.js twice, separated by an empty line, and adds a semicolon to the end of each filename and saves imagesX.js
    -from a folder a level above the base folder it copies a file called index.html into the base folder and renames in indexX.html
    -in indexX.html it replaces a string "replaceThis" with "imagesX.js"
    The task is more complex but this would help me tremendously do the rest.
    If I am asking for too much on this forum please let me know

    This should get you started.
    The description of how you want to write the data isn't clear, but the rest should work (untested):
    property imageNum : 0 -- last used ImageNumber
    -- within a base folder it takes an inventory (list?) of all the files (which happen to be image files).
    -- get the folder:
    set baseFolder to (choose folder)
    -- now get the files within it:
    tell application "Finder"
    set fileList to every file of folder baseFolder as alias list
    end tell
    --creates a new folder inside the base folder and calls it imagesX where X increases by one every time the script is run
    tell application "Finder"
    set imageNum to imageNum + 1
    set newImageFolder to make new folder at baseFolder with properties {name:"images" & imageNum}
    -- moves all the files into the images folder
    move every file of folder baseFolder to newImageFolder
    --within the base folder it creates a new text file and calls it imagesX.js
    set textFile to (open for access file (baseFolder as text) & "images" & imageNum & ".js" with write permission)
    --writes a "//-" into imagesX.js
    write "//-" to textFile
    -- then writes the list of filenames into the imagesX.js twice, separated by an empty line, and adds a semicolon to the end of each filename and saves imagesX.js
    -- need more info here
    -- a blank line between each instance of the file name? or all file names, blank line, all file names again?
    -- an example, please
    close access textFile
    --from a folder a level above the base folder it copies a file called index.html into the base folder
    --and renames in indexX.html
    --in indexX.html it replaces a string "replaceThis" with "imagesX.js"
    -- the easiest way of doing this is to read the file and write a new copy with the changes - that's easier than changing it in situ:
    set indexHTML to (read file "index.html" of folder (container of baseFolder))
    set {oldTIDs, my text item delimiters} to {my text item delimiters, "replaceThis"}
    set indexHTML to text items of indexHTML
    set my text item delimiters to "imagesX.js"
    set indexHTML to indexHTML as text
    set my text item delimiters to oldTIDs
    set indexFile to (open for access file ("index" & imageNum & ".html") with write permission)
    write indexHTML to indexFile
    close access indexFile
    end tell

  • Need help with a simple basketball game.

    Hi im new here and I need help with making this simple basketball game.
    Im trying to recreate this game from this video. Im not sure if he is using as2 or as3
    Or if anyone could help me make a game like this or direct me to a link on how to do it It would be greatly appreciated.

    If you couldn't tell whether it is AS2 or AS3, it is doubtful you can turn it from AS2 into AS3, at least not until you learn both languages.  There is no tool made that does it for you.

  • Need help with calculator project for an assignment...

    Hi all, I please need help with my calculator project that I have to do for an assignment.
    Here is the project's specifications that I need to do"
    """Create a console calculator applicaion that:
    * Takes one command line argument: your name and surname. When the
    program starts, display the date and time with a welcome message for the
    user.
    * Display all the available options to the user. Your calculator must include
    the arithmetic operations as well as at least five scientific operations of the
    Math class.
    -Your program must also have the ability to round a number and
    truncate it.
    -When you multiply by 2, you should not use the '*' operator to perform the
    operation.
    -Your program must also be able to reverse the sign of a number.
    * Include sufficient error checking in your program to ensure that the user
    only enters valid input. Make use of the String; Character, and other
    wrapper classes to help you.
    * Your program must be able to do conversions between decimal, octal and
    hex numbers.
    * Make use of a menu. You should give the user the option to end the
    program when entering a certain option.
    * When the program exits, display a message for the user, stating the
    current time, and calculate and display how long the user used your
    program.
    * Make use of helper classes where possible.
    * Use the SDK to run your program."""
    When the program starts, it asks the user for his/her name and surname. I got the program to ask the user again and again for his/her name and surname
    when he/she doesn't insert anything or just press 'enter', but if the user enters a number for the name and surname part, the program continues.
    Now my question is this: How can I restrict the user to only enter 'letters' (and spaces of course) but allow NO numbers for his/her surname??
    Here is the programs code that I've written so far:
    {code}
    import java.io.*;
    import java.util.*;
    import java.text.*;
    public class Project {
         private static String nameSurname = "";     
         private static String num1 = null;
         private static String num2 = null;
         private static String choice1 = null;
         private static double answer = 0;
         private static String more;
         public double Add() {
              answer = (Double.parseDouble(num1) + Double.parseDouble(num2));
              return answer;
         public double Subtract() {
              answer = (Double.parseDouble(num1) - Double.parseDouble(num2));
              return answer;
         public double Multiply() {
              answer = (Double.parseDouble(num1) * Double.parseDouble(num2));
              return answer;
         public double Divide() {
              answer = (Double.parseDouble(num1) / Double.parseDouble(num2));
              return answer;
         public double Modulus() {
              answer = (Double.parseDouble(num1) % Double.parseDouble(num2));
              return answer;
         public double maximumValue() {
              answer = (Math.max(Double.parseDouble(num1), Double.parseDouble(num2)));
              return answer;
         public double minimumValue() {
              answer = (Math.min(Double.parseDouble(num1), Double.parseDouble(num2)));
              return answer;
         public double absoluteNumber1() {
              answer = (Math.abs(Double.parseDouble(num1)));
              return answer;
         public double absoluteNumber2() {
              answer = (Math.abs(Double.parseDouble(num2)));
              return answer;
         public double Squareroot1() {
              answer = (Math.sqrt(Double.parseDouble(num1)));
              return answer;
         public double Squareroot2() {
              answer = (Math.sqrt(Double.parseDouble(num2)));
              return answer;
         public static String octalEquivalent1() {
              int iNum1 = Integer.parseInt(num1);
    String octal1 = Integer.toOctalString(iNum1);
    return octal1;
         public static String octalEquivalent2() {
              int iNum2 = Integer.parseInt(num2);
              String octal2 = Integer.toOctalString(iNum2);
              return octal2;
         public static String hexadecimalEquivalent1() {
              int iNum1 = Integer.parseInt(num1);
              String hex1 = Integer.toHexString(iNum1);
              return hex1;
         public static String hexadecimalEquivalent2() {
              int iNum2 = Integer.parseInt(num2);
              String hex2 = Integer.toHexString(iNum2);
              return hex2;
         public double Round1() {
              answer = Math.round(Double.parseDouble(num1));
              return answer;
         public double Round2() {
              answer = Math.round(Double.parseDouble(num2));
              return answer;
              SimpleDateFormat format1 = new SimpleDateFormat("EEEE, dd MMMM yyyy");
         Date now = new Date();
         SimpleDateFormat format2 = new SimpleDateFormat("hh:mm a");
         static Date timeIn = new Date();
         public static long programRuntime() {
              Date timeInD = timeIn;
              long timeOutD = System.currentTimeMillis();
              long msec = timeOutD - timeInD.getTime();
              float timeHours = msec / 1000;
                   return (long) timeHours;
         DecimalFormat decimals = new DecimalFormat("#0.00");
         public String insertNameAndSurname() throws IOException{
              boolean inputCorrect = false;
                   while (inputCorrect == false) {
                        while (nameSurname == null || nameSurname.length() == 0) {
                             for (int i = 0; i < nameSurname.length(); i++) {
                             if ((nameSurname.charAt(i) > 'a') && (nameSurname.charAt(i) < 'Z')){
                                       inputCorrect = true;
                        else{
                        inputCorrect = false;
                        break;
                        try {
                             BufferedReader inStream = new BufferedReader (new InputStreamReader(System.in));
                             System.out.print("Please enter your name and surname: ");
                             nameSurname = inStream.readLine();
                             inputCorrect = true;
                        }catch (IOException ex) {
                             System.out.println("You did not enter your name and surname, " + nameSurname + " is not a name, please enter your name and surname :");
                             inputCorrect = false;
                        System.out.println("\nA warm welcome " + nameSurname + " ,todays date is: " + format1.format(now));
                        System.out.println("and the time is now exactly " + format2.format(timeIn) + ".");
                        return nameSurname;
              public String inputNumber1() throws IOException {
              boolean inputCorrect = false;
                   while (inputCorrect == false) {
                        try {
                             BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
                             System.out.print("\nPlease enter a number you want to do a calculation with and hit <ENTER>: ");
                             num1 = br.readLine();
                             double number1 = Double.parseDouble(num1);
                             System.out.println("\nThe number you have entered is: " + number1);
                             inputCorrect = true;
                        } catch (NumberFormatException nfe) {
                             System.out.println("\nYou did not enter a valid number: " + "\""+ num1 + "\" is not a number!!");
                             inputCorrect = false;
                        return num1;
         public String calculatorChoice() throws IOException {
              System.out.println("Please select an option of what you would like to do with this number from the menu below and hit <ENTER>: ");
              System.out.println("\n*********************************************");
              System.out.println("---------------------------------------------");
              System.out.println("Please select an option from the list below: ");
              System.out.println("---------------------------------------------");
              System.out.println("1 - Add");
              System.out.println("2 - Subtract");
              System.out.println("3 - Multiply");
              System.out.println("4 - Divide (remainder included)");
              System.out.println("5 - Maximum and minimum value of two numbers");
              System.out.println("6 - Squareroot");
              System.out.println("7 - Absolute value of numbers");
              System.out.println("8 - Octal and Hexadecimal equivalent of numbers");
              System.out.println("9 - Round numbers");
              System.out.println("0 - Exit program");
              System.out.println("**********************************************");
              boolean inputCorrect = false;
                   while (inputCorrect == false) {
                        try {
                             BufferedReader inStream = new BufferedReader (new InputStreamReader(System.in));
                             System.out.print("Please enter your option and hit <ENTER>: ");
                             choice1 = inStream.readLine();
                             int c1 = Integer.parseInt(choice1);
                             System.out.println("\nYou have entered choice number: " + c1);
                             inputCorrect = true;
                        } catch (NumberFormatException nfe) {
                             System.out.println("You did not enter a valid choice number: " + "\""+ choice1 + "\" is not in the list!!");
                             inputCorrect = false;
                        return choice1;
         public String inputNumber2() throws IOException {
              boolean inputCorrect = false;
                   while (inputCorrect == false) {
                        try {
                             BufferedReader br2 = new BufferedReader (new InputStreamReader(System.in));
                             System.out.print("\nPlease enter another number you want to do the calculation with and hit <ENTER>: ");
                             num2 = br2.readLine();
                             double n2 = Double.parseDouble(num2);
                             System.out.println("\nThe second number you have entered is: " + n2);
                             System.out.println("\nYour numbers are: " + num1 + " and " + num2);
                             inputCorrect = true;
                        } catch (NumberFormatException nfe) {
                             System.out.println("You did not enter a valid number: " + "\""+ num2 + "\" is not a number!!");
                             inputCorrect = false;
                        return num2;
         public int Calculator() {
              int choice2 = (int) Double.parseDouble(choice1);
              switch (choice2) {
                        case 1 :
                             Add();
                             System.out.print("The answer of " + num1 + " + " + num2 + " is: " + decimals.format(answer));
                             break;
                        case 2 :
                             Subtract();
                             System.out.print("The answer of " + num1 + " - " + num2 + " is: " + decimals.format(answer));
                             break;
                        case 3 :
                             Multiply();
                             System.out.print("The answer of " + num1 + " * " + num2 + " is: " + decimals.format(answer));
                             break;
                        case 4 :
                             Divide();
                             System.out.print("The answer of " + num1 + " / " + num2 + " is: " + decimals.format(answer));
                             Modulus();
                             System.out.print(" and the remainder is " + decimals.format(answer));
                             break;
                        case 5 :
                             maximumValue();
                             System.out.println("The maximum number between the numbers " + num1 + " and " + num2 + " is: " + decimals.format(answer));
                             minimumValue();
                             System.out.println("The minimum number between the numbers " + num1 + " and " + num2 + " is: " + decimals.format(answer));
                             break;
                        case 6 :
                             Squareroot1();
                             System.out.println("The squareroot of value " + num1 + " is: " + decimals.format(answer));
                             Squareroot2();
                             System.out.println("The squareroot of value " + num2 + " is: " + decimals.format(answer));
                             break;
                        case 7 :
                             absoluteNumber1();
                             System.out.println("The absolute number of " + num1 + " is: " + decimals.format(answer));
                             absoluteNumber2();
                             System.out.println("The absolute number of " + num2 + " is: " + decimals.format(answer));
                             break;
                        case 8 :
                             octalEquivalent1();
                             System.out.println("The octal equivalent of " + num1 + " is: " + octalEquivalent1());
                             octalEquivalent2();
                             System.out.println("The octal equivalent of " + num2 + " is: " + octalEquivalent2());
                             hexadecimalEquivalent1();
                             System.out.println("\nThe hexadecimal equivalent of " + num1 + " is: " + hexadecimalEquivalent1());
                             hexadecimalEquivalent2();
                             System.out.println("The hexadecimal equivalent of " + num2 + " is: " + hexadecimalEquivalent2());
                             break;
                        case 9 :
                             Round1();
                             System.out.println("The rounded number of " + num1 + " is: " + decimals.format(answer));
                             Round2();
                             System.out.println("The rounded number of " + num2 + " is: " + decimals.format(answer));
                             break;
                        case 0 :
                             if (choice2 == 0) {
                                  System.exit(1);
                             break;
                   return choice2;
              public String anotherCalculation() throws IOException {
                   boolean inputCorrect = false;
                   while (inputCorrect == false) {
                             try {                              
                                  BufferedReader br3 = new BufferedReader (new InputStreamReader(System.in));
                                  System.out.print("\nWould you like to do another calculation? Y/N ");
                                  more = br3.readLine();
                                  String s1 = "y";
                                  String s2 = "Y";
                                  if (more.equals(s1) || more.equals(s2)) {
                                       inputCorrect = true;
                                       while (inputCorrect = true){
                                            inputNumber1();
                                            System.out.println("");
                                            calculatorChoice();
                                            System.out.println("");
                                            inputNumber2();
                                            System.out.println("");
                                            Calculator();
                                            System.out.println("");
                                            anotherCalculation();
                                            System.out.println("");
                                            inputCorrect = true;
                                  } else {
                                       System.out.println("\n" + nameSurname + " thank you for using this program, you have used this program for: " + decimals.format(programRuntime()) + " seconds");
                                       System.out.println("the program will now exit, Goodbye.");
                                       System.exit(0);
                             } catch (IOException ex){
                                  System.out.println("You did not enter a valid answer: " + "\""+ more + "\" is not in the list!!");
                                  inputCorrect = false;
              return more;
         public static void main(String[] args) throws IOException {
              Project p1 = new Project();
              p1.insertNameAndSurname();
              System.out.println("");
              p1.inputNumber1();
              System.out.println("");
              p1.calculatorChoice();
              System.out.println("");
              p1.inputNumber2();
              System.out.println("");
              p1.Calculator();
                   System.out.println("");
                   p1.anotherCalculation();
                   System.out.println("");
    {code}
    *Can you please run my code for yourself and have a look at how this program is constructed*
    *and give me ANY feedback on how I can better this code(program) or if I've done anything wrong from your point of view.*
    Your help will be much appreciated.
    Thanks in advance

    Smirre wrote:
    Now my question is this: How can I restrict the user to only enter 'letters' (and spaces of course) but allow NO numbers for his/her surname??You cannot restrict the user. It is a sad fact in programming that the worst bug always sits in front of the Computer.
    What you could do is checking the input string for numbers. If it contains numbers, just reprompt for the Name.
    AND you might want to ask yourself why the heck a calculator needs to know the users Name.

Maybe you are looking for

  • Oracle Workflow 2.6.3 Installation

    Hi, On a Redhat Linux server 3, I have installed Oracle 10g Infrastructure and Middle Tier. I have also a 10g Databse installed on this machine. I want to install Oracle Workflow 2.6.3. I used the Contnet Management SDK 10g(9.0.4.0) CD and run the in

  • Account 6311010 requires an assignment to a CO object Account 6311010 requ

    Hi All, I assigned different cost center in asset class. Then i removed default cost center in OKB9 for below GL account. While running the AFAB i am getting below error. Account 6311010 requires an assignment to a CO object I checked below configura

  • Split records in message

    Hello! I have some message type: <mt> <record> </record> </mt> where occurence of "record" is 1000, for example. And I need to split it to the same message type but with "record" occurence 10. So, if I have one big XML-file with 1000 records, I need

  • Need the classes for fm REUSE_ALV_HIERSEQ_LIST_DISPLAY  does.

    I have a requirement where  I need to display header and item using alv classes..  (the same functionality that REUSE_ALV_HIERSEQ_LIST_DISPLAY function module does).  If any one worked on this please guide.

  • CS3 and CS5 on same computer

    I am currently using CS3 on a Mac with Leopard and I am about to upgrade to CS5.  I've read discussions about compatibility issues between the two versions, so I would like to keep CS3 on my computer even after adding CS5.  Would this be a problem? A