[java] Read input from a JOptionPane.showInputDialog box

I am almost done with this project. It's my very first one and I need to read a little better the inputs from the JOption box. For example, I want to go back to the previous page if the user clicks on "cancel" or close the program. So far, every time I click on "cancel" my program crashes. help me out! I just started learning Java about a month ago. I think I am doing pretty alright. Thanks so very much!

Here is the code,

import java.util.Scanner; import javax.swing.JOptionPane;  /**  * Write a description of class Operation here.  *  * @author Charles Kossivi  * @version 1.0  */ public class Operation {      static String firstNumber; //first number or coefficient     static String secondNumber; //second number or coefficient     static String thirdNumber; //third number or coefficient     static String operationType = ""; //Operation type     static boolean anotherOperation = false;     static boolean goodType = true; //true=run program false=stop program     static boolean numberTypeA = true; // another operation?     static boolean numberTypeB = true; // another operation?      static boolean numberTypeC = true; // another operation?      static Scanner keyInput = new Scanner(System.in);     static String inputType; // temperature type     static double a; // first number     static double b; // second number     static double c; // third number     static double s; // sum of a and b     static double d; // difference of a and b     static double p; // product of a and b     static double r; // ratio of a and b     static double D; // discriminant     static double numType;      public static void main(String[] args) {         while (goodType) {             operationType = JOptionPane.showInputDialog("Welcome! \nPlease, Select the Desired Operation Type"                     + "(\nA=Addition, \nD=Division, \nE=Quadratic Equation, "                     + "\nM=Multiplication, \nS=Subtraction, \nQ=Quit");             if (operationType.equalsIgnoreCase("A")) {                 newAddition();             }             if (operationType.equalsIgnoreCase("S")) {                 newSubtraction();             }             if (operationType.equalsIgnoreCase("M")) {                 newMultiplication();             }             if (operationType.equalsIgnoreCase("D")) {                 newDivision();             }             if (operationType.equalsIgnoreCase("E")) {                 newQuadratic();             }             if (operationType.equalsIgnoreCase("Q")) {                 // quit                    JOptionPane.showMessageDialog(null, "\nProgram ended. \nThank You!");                 goodType = false;             }         }         goodType = false;     }      //Start Addition class here     private static void newAddition() {         //read in first coefficient from user as a string         firstNumber = JOptionPane.showInputDialog("Please, Enter First Number");         if (firstNumber.equalsIgnoreCase("Q")) {             // quit                JOptionPane.showMessageDialog(null, "\nProgram ended. \nThank You!");             goodType = false;         } else {             a = Double.parseDouble(firstNumber);             //read in second coefficient from user as a string             secondNumber = JOptionPane.showInputDialog("Please, Enter Second Number");             if (secondNumber.equalsIgnoreCase("Q")) {                 // quit                    JOptionPane.showMessageDialog(null, "\nProgram ended. \nThank You!");                 goodType = false;             } else {                 b = Double.parseDouble(secondNumber);                 //Adding the numbers                 s = a + b;                 //Display results                 JOptionPane.showMessageDialog(null, "The sum is " + s);             }         }     }      //End Addition class     //Start Addition class here     private static void newSubtraction() {         //read in first coefficient from user as a string         firstNumber = JOptionPane.showInputDialog("Please, Enter First Number");         if (firstNumber.equalsIgnoreCase("Q")) {             // quit                JOptionPane.showMessageDialog(null, "\nProgram ended. \nThank You!");             goodType = false;         } else {             a = Double.parseDouble(firstNumber);             //read in second coefficient from user as a string             secondNumber = JOptionPane.showInputDialog("Please, Enter Second Number");             if (secondNumber.equalsIgnoreCase("Q")) {                 // quit                    JOptionPane.showMessageDialog(null, "\nProgram ended. \nThank You!");                 goodType = false;             } else {                 b = Double.parseDouble(secondNumber);                 //Subtraction the numbers                 d = a - b;                 //Display results                 JOptionPane.showMessageDialog(null, "The sum is " + d);             }         }     }//End Subtraction class      // Begin Multiplication class     private static void newMultiplication() {         //read in first coefficient from user as a string         firstNumber = JOptionPane.showInputDialog("Please, Enter First Number");         if (firstNumber.equalsIgnoreCase("Q")) {             // quit                JOptionPane.showMessageDialog(null, "\nProgram ended. \nThank You!");             goodType = false;         } else {             a = Double.parseDouble(firstNumber);             //read in second coefficient from user as a string             secondNumber = JOptionPane.showInputDialog("Please, Enter Second Number");             if (secondNumber.equalsIgnoreCase("Q")) {                 // quit                    JOptionPane.showMessageDialog(null, "\nProgram ended. \nThank You!");                 goodType = false;             } else {                 b = Double.parseDouble(secondNumber);                 //multiplying the numbers                 p = a * b;                 //Display results                 JOptionPane.showMessageDialog(null, "The product is " + p);             }         }     } // End Multiplication class      //Start Division class     private static void newDivision() {         //read in first coefficient from user as a string         firstNumber = JOptionPane.showInputDialog("Please, Enter First Number");         if (firstNumber.equalsIgnoreCase("Q")) {             // quit                JOptionPane.showMessageDialog(null, "\nProgram ended. \nThank You!");             goodType = false;         } else {             a = Double.parseDouble(firstNumber);             //read in second coefficient from user as a string             secondNumber = JOptionPane.showInputDialog("Please, Enter Second Number");             if (secondNumber.equalsIgnoreCase("Q")) {                 // quit                    JOptionPane.showMessageDialog(null, "\nProgram ended. \nThank You!");                 goodType = false;             } else {                 b = Double.parseDouble(secondNumber);                 //Dividing the numbers                 r = a / b;                 //Display results                 JOptionPane.showMessageDialog(null, "The ratio is " + r);             }         }     } //End Division class      //Start Quadratic class     private static void newQuadratic() {         //read in first coefficient from user as a string         firstNumber = JOptionPane.showInputDialog("Please, Enter First Number");         if (firstNumber.equalsIgnoreCase("Q")) {             // quit                JOptionPane.showMessageDialog(null, "\nProgram ended. \nThank You!");             goodType = false;         } else {             a = Double.parseDouble(firstNumber);             //read in second coefficient from user as a string             secondNumber = JOptionPane.showInputDialog("Please, Enter Second Number");             if (secondNumber.equalsIgnoreCase("Q")) {                 // quit                    JOptionPane.showMessageDialog(null, "\nProgram ended. \nThank You!");                 goodType = false;             } else {                 b = Double.parseDouble(secondNumber);                 //read in third coefficient from user as a string                 thirdNumber = JOptionPane.showInputDialog("Please, Enter Third coefficient");                 if (thirdNumber.equalsIgnoreCase("Q")) {                     // quit                        JOptionPane.showMessageDialog(null, "\nProgram ended. \nThank You!");                     goodType = false;                 } else {                     c = Double.parseDouble(thirdNumber);                     //Quadratic formula                     D = (Math.sqrt(b * b - 4 * a * c)) / (2 * a);                     //Display results                     if (D >= 0) {                         JOptionPane.showMessageDialog(                                 null, "The equation's first real root is " + ((-b + D) / (2 * a)) + "\n"                                 + "The equation's second real root is " + ((-b - D) / (2 * a)) + "\n");                     } else {                         JOptionPane.showMessageDialog(                                 null, "The equation has no real solution");                     }                 }             }         }     }// end class quadratics } 

This question is related to java swing modal-dialog joptionpane cancel-button

The answer is


Your problem is that, if the user clicks cancel, operationType is null and thus throws a NullPointerException. I would suggest that you move

if (operationType.equalsIgnoreCase("Q")) 

to the beginning of the group of if statements, and then change it to

if(operationType==null||operationType.equalsIgnoreCase("Q")). 

This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.

Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.


Questions with java tag:

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error Instantiating a generic type When to create variables (memory management) java doesn't run if structure inside of onclick listener String method cannot be found in a main class method Are all Spring Framework Java Configuration injection examples buggy? Calling another method java GUI I need to know how to get my program to output the word i typed in and also the new rearranged word using a 2D array Java and unlimited decimal places? Read input from a JOptionPane.showInputDialog box Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable Two Page Login with Spring Security 3.2.x Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java) Got a NumberFormatException while trying to parse a text file for objects Best way for storing Java application name and version properties Call japplet from jframe FragmentActivity to Fragment Comparing two joda DateTime instances Maven dependencies are failing with a 501 error IntelliJ: Error:java: error: release version 5 not supported Has been compiled by a more recent version of the Java Runtime (class file version 57.0) Why am I getting Unknown error in line 1 of pom.xml? Gradle: Could not determine java version from '11.0.2' Error: Java: invalid target release: 11 - IntelliJ IDEA Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util Why is 2 * (i * i) faster than 2 * i * i in Java? must declare a named package eclipse because this compilation unit is associated to the named module How do I install Java on Mac OSX allowing version switching? How to install JDK 11 under Ubuntu? Java 11 package javax.xml.bind does not exist IntelliJ can't recognize JavaFX 11 with OpenJDK 11 Difference between OpenJDK and Adoptium/AdoptOpenJDK OpenJDK8 for windows How to allow all Network connection types HTTP and HTTPS in Android (9) Pie? Find the smallest positive integer that does not occur in a given sequence Error: JavaFX runtime components are missing, and are required to run this application with JDK 11 How to uninstall Eclipse? Failed to resolve: com.google.firebase:firebase-core:16.0.1 How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

Questions with swing tag:

Calling another method java GUI Read input from a JOptionPane.showInputDialog box Call japplet from jframe Java JTable getting the data of the selected row What does .pack() do? How to add row of data to Jtable from values received from jtextfield and comboboxes How can I check that JButton is pressed? If the isEnable() is not work? Load arrayList data into JTable How to draw a circle with given X and Y coordinates as the middle spot of the circle? Simplest way to set image as JPanel background JFrame background image JFrame: How to disable window resizing? Adding image to JFrame Adding items to a JComboBox How to make a JFrame button open another JFrame class in Netbeans? Set Icon Image in Java Java - Check if JTextField is empty or not Swing vs JavaFx for desktop applications Resize a picture to fit a JLabel Save file/open file dialog box, using Swing & Netbeans GUI editor How to layout multiple panels on a jFrame? (java) How does paintComponent work? Execute an action when an item on the combobox is selected How to set the height and the width of a textfield in Java? DTO and DAO concepts and MVC getting integer values from textfield Allowing the "Enter" key to press the submit button, as opposed to only using MouseClick How to add text to JFrame? add controls vertically instead of horizontally using flow layout JFrame.dispose() vs System.exit() JPanel vs JFrame in Java JOptionPane - input dialog box program Get combobox value in Java swing Triangle Draw Method Display calendar to pick a date in java JFrame in full screen Java Restricting JTextField input to Integers Open a link in browser with java button? Most simple code to populate JTable from ResultSet Adding JPanel to JFrame Java :Add scroll into text area JPanel setBackground(Color.BLACK) does nothing Limiting the number of characters in a JTextField JTable - Selected Row click event JCheckbox - ActionListener and ItemListener? "Could not find the main class" error when running jar exported by Eclipse Drawing in Java using Canvas Java swing application, close one window and open another when button is clicked The Use of Multiple JFrames: Good or Bad Practice? How to position the form in the center screen? Read input from a JOptionPane.showInputDialog box Disable click outside of angular material dialog area to close the dialog (With Angular Version 4.0+) How can I display a modal dialog in Redux that performs asynchronous actions? Angular 2.0 and Modal Dialog How to use Bootstrap modal using the anchor tag for Register? Bootstrap modal opening on page load Trying to make bootstrap modal wider How to present a modal atop the current view in Swift Send parameter to Bootstrap modal window? Set bootstrap modal body height by percentage Bootstrap Modal before form Submit Disable click outside of bootstrap modal area to close modal Bootstrap Modal sitting behind backdrop Display Bootstrap Modal using javascript onClick Bootstrap 3 - How to load content in modal body via AJAX? Closing Bootstrap modal onclick Bootstrap: Open Another Modal in Modal How to check if bootstrap modal is open, so I can use jquery validate? Multiple modals overlay bootstrap jquery show.bs.modal event won't fire How to prevent background scrolling when Bootstrap 3 modal open on mobile browsers? Auto-click button element on page load using jQuery Bootstrap 3 modal vertical position center Bootstrap 3 with remote Modal Calling a function on bootstrap modal open Close Bootstrap Modal Invoking modal window in AngularJS Bootstrap UI using JavaScript Twitter Bootstrap Modal Form Submit Prevent Bootstrap Modal from disappearing when clicking outside or pressing escape? Bootstrap modal not displaying Open Bootstrap Modal from code-behind Load content with ajax in bootstrap modal How to add an event after close the modal window? How to deal with ModalDialog using selenium webdriver? Bootstrap Modal immediately disappearing how to destroy bootstrap modal window completely? make bootstrap twitter dialog modal draggable How to hide Bootstrap previous modal when you opening new one? How to handle the modal closing event in Twitter Bootstrap? Twitter bootstrap remote modal shows same content every time How to set the focus for a particular field in a Bootstrap modal, once it appears Twitter Bootstrap: Print content of modal window Twitter bootstrap modal-backdrop doesn't disappear Using Bootstrap Modal window as PartialView jQuery dialog popup Bootstrap modal appearing under background Can not get a simple bootstrap modal to work How to get twitter bootstrap modal to close (after initial launch) How to hide Bootstrap modal with javascript? How to pass values arguments to modal.show() function in Bootstrap

Questions with joptionpane tag:

Read input from a JOptionPane.showInputDialog box Convert timestamp to string Return string Input with parse.string How to present a simple alert message in java? JOptionPane Yes or No window Multiple input in JOptionPane.showInputDialog JOptionPane Input to int Java - How to create a custom dialog box?

Questions with cancel-button tag:

Read input from a JOptionPane.showInputDialog box