Reading Integer using JOptionPane

I'm trying to write a Java program using JOptionPane dialog/display boxes that reads an integer and checks whether it is even using true/false statements. I also want the program must check if the number the user entered is between 1 and 1000.
I haven't found alot of help in the book I have, so I'm hoping somone has some example modules.
Thank you....
Scott

Hi,
Hope this helps you a bit. Just Uncomment the for your even number testing.
import javax.swing.JOptionPane;
public class OptionPaneTest {
     public static boolean isNumber(String args)
          if(args.length() > 3)
               throw new IllegalArgumentException("Invalid argument");
          else
          boolean isNumber = false;
          for(int i = 0; i < args.length(); i++)
               char c = args.charAt(i);
               if(Character.isDigit(c))
                    isNumber = true;
               else
                  isNumber = false;
          return isNumber;
     public static boolean isEven(int aNumber)
          int a = aNumber & 1;
          return (a == 0);          
      * @param args
     public static void main(String[] args) {          
          String s = JOptionPane.showInputDialog("Please enter number between 0 to 999");
          System.out.println("Is Number " + isNumber(s));
          if(isNumber(s))
          int number = Integer.valueOf(s);
          System.out.println("Number " + number + "is Even " + isEven(number));          
//          for(int i = 0; i < 999; i++)
//          System.out.println(i + " is " + isEven(i));
}

Similar Messages

  • Using JOptionPane.showInputDialog to return an integer

    I am currently using JOptionPane to return a string from the Object array i made with all possible choices.
         private static boolean determineService(){
              JLabel label;
              label=new JLabel("Please select which Service Model to use.",JLabel.CENTER);
              Object[] possibilities = {"AddressCleanse", "VIN", "PostalCode"};
              serviceModel = (String)JOptionPane.showInputDialog(
                                  null,
                                  label,
                                  "Select Service",
                                  JOptionPane.PLAIN_MESSAGE,null,
                                  possibilities,
                                  "AddressCleanse");
    //          If a string was returned, say so.
              if ((serviceModel != null) && (serviceModel.length() > 0)) {
                  System.out.println("You've selected " + serviceModel + "!");
                  setVariables();
                  return true;
              }else{
    //               If you're here, the return value was null/empty.
                   System.out.println("Null or Bad service selected!\n Exiting program.");
                   return false;
              }I would like to instead return the response as an integr so I can then use a switch, rather than recursive if, else if logic.
    Apparently java doesnt allow switches to use strings (like PHP does)
    any ideas?

    Just a question more than an answer: would using a hashmap ever work here? where the key is a string and the value is an (???) object that implements an interface that would allow you to call an appropriate method? Perhaps one could use the keySet() and toArray to build the Object array for the JOptionPane. I thought I read something about this somewhere, but am not sure....

  • Comple errors using JOptionPane

    I'm trying to write a Java program using JOptionPane dialog/display boxes that reads an integer and checks whether it is even using true/false statements. I also want the program must check if the number the user entered is between 1 and 1000.
    I haven't found alot of help in the book I have and i've found some help in another forum but it doesn't seem to compile well, I get the following errors:
    IntegerRead.java:39: cannot find symbol
    symbol : method valueOf(java.lang.String)
    location: class Integer
    int number = Integer.valueOf(s);
    ^
    Integer.java:13: cannot find symbol
    symbol : class Scanner
    location: class Integer
    Scanner input = new Scanner( System.in );
    ^
    Integer.java:13: cannot find symbol
    symbol : class Scanner
    location: class Integer
    Scanner input = new Scanner( System.in );
    Here is the code:
    // Assignment 2.1: IntegerRead.java
    // This program reads an integer, checks if it's even and is between 1 and 1000.
    import javax.swing.JOptionPane; // program uses class JOptionPane
    public class IntegerRead
    public static boolean isNumber(String args)
    if(args.length() > 3)
    throw new IllegalArgumentException("Invalid argument");
    else
    boolean isNumber = false;
    for(int i = 0; i < args.length(); i++)
    char c = args.charAt(i);
    if(Character.isDigit(c))
    isNumber = true;
    else
    isNumber = false;
    return isNumber;
    public static boolean isEven(int aNumber)
    int a = aNumber & 1;
    return (a == 0);
    public static void main(String args[])
    String s = JOptionPane.showInputDialog("Please enter number between 0 to 999");
    System.out.println("Is Number " + isNumber(s));
    if(isNumber(s))
    int number = Integer.valueOf(s);
    System.out.println("Number " + number + "is Even " + isEven(number));
    for(int i = 0; i < 999; i++)
    System.out.println(i + " is " + isEven(i));
    I know i'm missing very simple. I'm new and have tried to build upon what I have so far, but I can't figure it out.
    Thanks....
    Edited by: Scott.Dishman on Jul 9, 2008 4:07 PM

    You have a class named Integer somewhere on your class path. Get rid of it or rename it. If you've already renamed your Integer.java file, you still need to delete the Integer.class file. You should never create your own class that has the same name as a class in the standard java.lang package.

  • Using JOptionPane to exit program & Using toString method

    Hello,
    In my program I have to use a toString method below
    public String toString(Hw1NCBEmployee[] e)
            String returnMe = String.format(getStoreName() + "\n" + getStoreAddress() + "\n" + getCityState() +  "\nYou have " + getEmpCount() + "employee(s)");
            return returnMe;
    }Now, at first, when I initially tested my code, it was working just fine, printing out the right way
    Point is -- now that Im practically finished with my program, and am going back and running it - calling the toString method gives me the address rather than the information . . . Can anyone help me with this issue??
    Also, Im using JOptionPane to display everything, but -- at first, it worked fine, then (around the same time I started having the above problem) it stopped exiting the do-while loop:
    while(go)
                 int option = JOptionPane.showConfirmDialog(null, "Do you want to enter employee information?", "Welcome!", JOptionPane.YES_NO_OPTION);
                     if(option == JOptionPane.NO_OPTION)
                        go = false;  //exit loop
            

    ncjb wrote:
    well, for the toString - I have to print out the info inside the array -- am I right in thinking that the only way to do this is to pass in the array ??If the array is part of the class then there is no need to pass it as a parameter. If it is being passed in from outside the class then I have to question your design. Why should class X being formatting data that is not a representation of itself?
    and i have 2 other files that go with this program . . . I just want to know if there is a way to make sure that when the user presses the NO option, it will exit the loop -- the piece of code you see if apart of an entire method (not long) -- do you want me to include this??You read that link I provided REAL quick!

  • Using JOptionPane in a non-event dispatching thread

    I am currently working on a screen that will need to called and displayed from a non-event dispatching thread. This dialog will also capture a user's selection and then use that information for later processing. Therefore, the dialog will need to halt the current thread until the user responds.
    To start, I tried using the JOptionPane.showInputDialog() method and set the options to a couple of objects. JOptionPane worked as advertised. It placed the objects into a combobox and allowed the user to select one of them. However, it also gave me something unexpected. It actually paused the non-event handling thread until the user had made a selection. This was done without the JOptionPane code being wrapped in a SwingUtilities.invokeLater() or some other device that would force it to be launched from an Event Handling Thread.
    Encouraged, I proceeded to use JOptionPane.showInputDialog() substituting the "message" Object with a fairly complex panel (JRadioButtons, JLists, JTextFields, etc.) that would display all of the variety of choices for the user. Now, when the screen pops up, it doesn't paint correctly (like what commonly occurs when try to perform a GUI update from a non-event dispatching thread) and the original thread continues without waiting for a user selection (which could be made if the screen painted correctly).
    So, here come the questions:
    1) Is what I am trying to do possible? Is it possible to create a fairly complex GUI panel and use it in one of the static JOptionPane.showXXXDialog() methods?
    2) If I can't use JOptionPane for this, should I be able to use JDialog to perform the same type function?
    3) If I can use JDialog or JFrame and get the threading done properly, how do I get the original thread to wait for the user to make a selection before proceeding?
    I have been working with Java and Swing for about 7-8 years and have done some fairly complex GUIs, but for some reason, I am stumped here. Any help would be appreciated.
    Thanks.

    This seems wierd that it is functioning this way. Generally, this is what is supposed to happen. If you call a JOptionPane.show... from the Event Dispatch Thread, the JOptionPane will actually begin processing events that normally the Event Dispatch Thread would handle. It does this until the user selects on options.
    If you call it from another thread, it uses the standard wait and notify.
    It could be that you are using showInputDialog for this, try showMessageDialog and see if that works. I believe showInputDialog is generally used for a single JTextField and JLabel.

  • How to use JOptionPane in jsp, instead of javascript message alert box?

    HI,
    How to use JOptionPane in jsp,
    instead of javascript "message alert box"?
    I hate javascript,
    I'd like to only use java in jsp. don't use javascript.
    javascript is client side,
    jsp is server side. i know that.
    how to... instead of javascript box?
    how to use ... message box in webpage?
    don't use applet,,,, don't use javascript,,,
    hm...zzzZzz
    I hate javascript..T.T
    <SCRIPT language=JavaScript>
    alert("hate javascript");
    </SCRIPT>
    ===>>>>
    In this way,,
    JOptionPane.showOptionDialog(null,"I love java")
    I'd like to only use jsp and java and html...in webpage.
    don't use javascript....
    Why? don't sun provide message box in jsp, instead of javascrip box?
    Why?
    Edited by: seong-ki on Nov 4, 2007 8:38 PM

    Drugs are bad, m'kay?

  • Trying to print a list using JOptionPane

    I am very new to Java and programming, so please forgive me if this should be apparent. I wrote a program for school which was for ordering pizzas. I wrote it as a console program and after much frustration it finally worked. Now I am trying to change it to a GUI program using JOptionPane. I was hoping that since I already had the logic written and working, I could focus on the GUI aspect. I was wrong. I want to print a list of enums on a JOptionPane and cannot figure out how to do it My code in the console program was:
    System.out.println("The available crust styles are: ");
         for(Pizza.Style style : Pizza.Style.values())
              System.out.println(style+" ");
    So how can I iterate through the for loop to list all of the styles in the JOptionPane? Do I need to turn it into a method with a return and then cal the method like
    JOptionPane.showMessageDialog(null, crustMethod()); ??

    OP said:
    ... Now I am trying to change it to a GUI program using JOptionPane. I was hoping that since I already had the logic written and working, I could focus on the GUI aspect. I was wrong. ...I wouldn't use JOptionPane. You need JFrame and maybe, but I doubt it, a JDialog. OP, the GUI is more than likely to be nothing more than a form that allows users to set certain properties or fields in a Java class. For example let's say we have this class.
    public class Point
      public int x;
      public int y;
    }Then a GUI for this would be something like a JPanel with two (2) JLabels and two (2) JTextFields. Maybe something like so...
    import java.awt.*;
    import javax.swing.*;
    public class PointGUI extends JPanel
      public JLabel xLabel = new JLabel("Coordinate X:");
      public JLabel yLabel = new JLabel("Coordinate Y:");
      public JTextField xField = new JTextField(4);
      public JTextField yField = new JTextField(4);
      public PointGUI(){
        setLayout(new GridLayout(2, 2));
        add(xLabel);
        add(xField);
        add(yLabel);
        add(yField);
    }Then to run the program...
    import javax.swing.*;
    public class Test
      public static void main(String[] args){
        SwingUtitlities.invokeLater(new Runnable(){
          public void run(){
            PointGUI gui = new PointGUI();
            JFrame f = new JFrame("PointGUI");
            f.getContentPane().add(gui, "Center");
            f.pack();
            f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
            f.setVisible(true);
    }... actually all the program does is display the GUI. But, can you see that the GUI's JLabels and JTextFields describe all the public properties of the Point class? Can you see that the entire GUI can be placed anywhere in a JFrame, or maybe even in a JDialog? From this point on, you can add other functions and features to your classes, GUI's and the main apps that run them.
    A hint on your project, you may need to write a Pizza class that decribes all the things a single pizza can be - then come up with a GUI for that and an app that runs it.

  • Deleting a MS Access database table record using JOptionPane

    hi!
    just want some help here..
    is there a way to delete a MS Access database record through using JOptionPane?? i've gone through some, probably alot of examples on SELECT, INSERT, UPDATE, DELETE statements but none came up to the stuff i need.
    so far i've seen the DELETE statement like this and also this is a common DELETE statement..
    statement.executeUpdate("DELETE FROM tableName WHERE fieldName01 = 'blablabla' AND fieldName02 = 'etcetcetc'");like INSERT, there's a coding somewhat like this:
    String asd = JOptionPane.showInputDialog(null, "Enter blablabla stuff");
    statement.executeUpdate("INSERT INTO whatEverTableName (tableFieldName) VALUES('"+asd.getText()+"')");so, is it possible using the same method for DELETE??
    help and advices are appreciated in advanced..

    Here's how I did it. Research does help, but sometimes looking at others code does too... You do have to have a dummy file that you made with access though. You can't just make a file file.mdb (it will be corrupt)
         public void createDatabase(String database) throws SQLException{
              try{
                   // This file needs to have been created with MS Access
                   File dbfile = new File(this.dataBaseDir + "dummy.mdb");
                   // This is the new database file being made
                   File newFile = new File(this.dataBaseDir + database + ".mdb");
                   // Copy all bytes from dummy file to new DB file.
                   FileInputStream instream = new FileInputStream(dbfile);
                   FileOutputStream ostream = new FileOutputStream(newFile);
                   int numBytes = instream.available();
                   byte inBytes[] = new byte[numBytes];
                   instream.read(inBytes, 0, numBytes);
                   ostream.write(inBytes, 0, numBytes);
              catch(FileNotFoundException e) { e.printStackTrace();}
              catch(IOException e) { e.printStackTrace();}
              if(DEBUG) System.out.println("creating the " + database + " database");
         }

  • Help using JOptionPane

    please tell me how can i do following:
    I want to add strings using JOptionPane.showInputDialog( ) method. in an ArrayList() of strings only.
    I want to show input dialog box to user continously till user presses "enter" from keyboard.
    please tell me the way to stop the loop when user presses "Enter" from keyboard.
    //what i have done:
    //created new ArrayList()
    myStrings = new ArrayList();
    while(1)
        String theString = JOptionPane.showInputDialog("Enter string ");
        myStrings.add(theString);
    }

    I want to show input dialog box to user continously
    till user presses "enter" from keyboard.
    please tell me the way to stop the loop when user
    presses "Enter" from keyboard.You probably want to end the loop when the user clicks the cancel button on the dialog. Clicking the enter button invokes the button that has focus.

  • Using JoptionPane.ShowInternalDialog

    I'm using the following code to open an JInternalFrame as model from another JinternalFrame.
    partNumberMaintenanceFrame = new PartNumberMaintenance_4_1 (this,null,data);
    JPanel glass = new JPanel();
    glass.setOpaque(false);
    glass.setLayout(null);
    glass.add(partNumberMaintenanceFrame);
    mainDesktopFrame.setGlassPane(glass);
    glass.setVisible(true);
    partNumberMaintenanceFrame.setVisible(true);
    Now, the problem is , When i try to use JoptionPane.ShowInternalDialog from the partNumberMaintenanceFrame the messagedialog goes behind the frame.
    I guess this is bcoz i use glasspane. What shoup i do to make the dialog to show on the frame?
    Thanks

    You might need to post a little more code for people to help you.

  • I have huge lag with Safari's Reading List using a rMBP. I have probably 80 articles saved, which is likely the cause of the lag. Is there any way to export that list of articles so as to be able to delete them from Reading List but still have a record?

    I have huge lag with Safari's Reading List using a rMBP. I have probably 80 articles saved, which is likely the cause of the lag. Is there any way to export that list of articles so as to be able to delete them from Reading List but still have a record of the articles I intend to read?

    I'm currently dealing with this issue myself, except that my rMBP has NO articles in the reading list.  It's a brand new rMBP too, purchased just this week, with the 2.6 Ghz Processor & 16GB of RAM.
    Let's see what we can find.  I may just take it back to the Apple Store.

  • Open several PDFs in the same Reader window using tabs for each document

    How do I open several PDFs in the same Reader window using tabs for each document?  I'm using Reader 11.0.03 and Windows 7.  

    That would be a nice feature!  Suggest it at https://www.adobe.com/cfusion/mmform/index.cfm?name=wishform - hopefully it will make it into Reader XII.

  • Can't read email using my primary apple email account

    Ok, I'm new to this forum but here is my problem
    Usually I can read Email using my primary Apple E-mail account BEFORE I updated my Ipad into IOS 8.
    After I updated my Ipad into IOS 8 (non-jailbreak and from IOS 5 jailbreak), My Ipad says that I need to sign up an Icloud email to use the Mail App.
    Then I can't use my Primary Apple Account as an E-mail anymore. When people send a mail to my primary apple account, I cant read it because I cant read emails using my Primary Apple Account anymore.
    When I signed in with my primary apple Email account and opened my Mail App, It used my Icloud email instead my primary apple email.
    I tried everything Include making an email aliases but my primary apple email uses @Yahoo.com and I can only use aliases of @Icloud.com
    Can someone please help me so I can read E-mails when people send an Email to my primary apple account? Because I need to see those subcription mails and change my password of my online game account(<- This one is URGENT).
    And sorry for my bad English because I'm Indonesian.

    Welcome to discussions,
    go to settings/mail, contacts.../your mail account/outgoing mail server settings/ and see if you put in the needed password to access your mail server.
    Also check out this help article about your issue for more tips: http://support.apple.com/kb/TS2770

  • I have a Windows 8.1 machine.  I used a projecteor a while back in a Power Point presentation.  Now my menus for Adobe are very small and hard to read.  The print command is so compressed that I cannot read or use it.  How do I fix this problem?

    I used a projecteor a while back in a Power Point presentation.  Now my menus for Adobe are very small and hard to read.  The print command is so compressed that I cannot read or use it.  How do I fix this problem?

    There is no application called "Adobe" - you are either working with Adobe Acrobat or the free Adobe Reader. Open up the preferences for the application (Edit>Preferences), then go to the "General" category and modify the settings for "Scale for screen resolution". You will have to restart the application after you do that. Does that fix your problems?

  • How can I script Adobe Reader updates using vbScript, PowerShell or C#?

    I would like to script Adobe Reader updates using vbScript, PowerShell or C#, are there any Adobe API calls I use to do this.  There are several different version that I support and auto update is not an option. I do updates at a specific time of the month. I would like to write a script that would download and install the update for the currently installed version of Adobe Reader (32 or 64 bit) for the version of the OS (32 or 64bit). I can detect the OS version and the Adobe version.  I can download updates but I do not want to hard code anything

    Sabian is correct.
    Most admins download the updates from the ftp site and push via AIP, GPO, SCCM, or some other method whenever it makes sense for them.
    Ben

Maybe you are looking for

  • Purchase order form: external send (mail)

    Hi experts when creating a purchase order, if the medium used is external  send, the system generates a mail with the purchase order form. What I would like to know if it is possible to customize the system in order to specify the subject of the mail

  • Where is my editable PDF content?

    I have created editable business card PDF which saves perfectly. When I upload to an online printing company my editable content does not show.

  • Event Forwarding Subscription Parameters

    Hello, You provided a good installation guide to create a source initiated subscription here: http://msdn.microsoft.com/en-us/library/windows/desktop/bb870973%28v=vs.85%29.aspx However, I'd like to know how it really works. Here are a few questions:

  • Java Application + Flash / Win Media Player.

    Hey Guys, I am developing a video streaming application and wanted to integrate the Flash player in my code. I am not able to do it. I could load and open the player but couldnt play .swf file. Please advice / suggest / guide... Bye, Salil.Siddhaye

  • Suddenly java.language.ClassLoader errors

    after successfully compiling and running a program I wrote another one and got the following errors when I tried to execute - compilation was ok java.lang.NoClassDefFoundError: SourceCode/BookPrograms/ASCII/ch05/OracleDemo (wrong name: OracleDemo) at