0

The code below is for a simple calculator with the four basic mathematical operators. It is a working program, it works as expected. However, I have a few questions to understand and improve both my program as well as my understanding of Java. (I have used google but the amount of redundant info confuses me and haven't found any perfect answers on StackOverflow too, though there are dozens of related questions. Believe me, I did tried before posting here).

  1. How can I make sure that the user input is exactly and strictly one char? here in my program, it accepts more than one character (+-*) but operates on the first char (+) only. I want to make sure more than one character is not accepted as input.

  2. After successful execution of the program, how can I somehow let the user repeat the main method? I mean, a user adds two numbers, gets his answer and he wants to do another calculation, maybe multiply two numbers this time. I can ask the user for yes or no to continue but how do I take him/her back to the beginning? (will a loop work? how?)

  3. A the end of the program I used two methods to output a message. The system.out.print works fine but the JOptionPane method doesn't display the message and the program doesn't terminate (I have commented it out). I would like to understand why?

  4. Is the default case required in the switch? And Am I following the correct code structure? (the arrangements and uses of curly braces)

NB: As I said this calculator works fine and can be used by newbies like myself to better understand the concept as I have commented on every detail. Please understand that I couldn't add everything in the question title due to limits...

package mycalculator;

import javax.swing.JOptionPane;
import java.util.*;
public class MyCalculator{
public static void main (String [] args){
        // Let us code a simple calculator//

// Variable type declarations//          
  char OP;
  int firstNum; 
  int secNum;         

// Display an explanation of what this program does//
    System.out.println("This is a simple calculator that will do basic 
    calculations such as :"
     + "\nAddition, Multiplication, Substraction and Division.");

// Create a scanner object to Read user Input.//
    Scanner input = new Scanner(System.in);

// Ask user to input any positive number and read it//
    System.out.println("Enter Any positive number followed by pressing 
    ENTER.");
    firstNum = input.nextInt();

// Ask user to input/decide his choice operator and read it //
    System.out.println("Enter a valid OPERATOR sign followed by pressing 
    ENTER.");
    OP = input.next().charAt(0);  

// Loop the below statement till one of the four (+,-,*,/) is entered.// 
    while(OP != '+' && OP != '-' && OP != '*' && OP != '/'){
        System.out.println("Please Re-enter a valid Operator (+,-*,/)");
        OP = input.next().charAt(0);}

// Ask user for any second number and read it//
   System.out.println("Enter your Second number followed by an ENTER 
   stroke.");
   secNum = input.nextInt();

// Various possible Resolution based on OP value.//
   int RSum = firstNum+secNum;
   int RSubs= firstNum-secNum;
   int RPro = firstNum*secNum;
   double DPro = firstNum/secNum;

// Conditional statements for Processing Results based on OP and display.//
    switch(OP){ 
   case '+': System.out.println("The Resulting sum is "+ RSum);
   break;
   case '-': System.out.println("The Resulting sum is "+ RSubs);
   break;
   case '*': System.out.println("The Resulting Product is "+ RPro);
   break;
   case '/': System.out.println("The Resulting Divisional product is "+ 
   DPro);
   break;
//Maybe the default case is actually not needed but is added for totality//
  default : System.out.println("Try Again");
    break;
    }

// The following code maybe deleted, it is for experimental purpose//
// Just checking if additional statements executes after a program 
   completes//
    System.out.println("Test Message ");
//  JOptionPane.showMessageDialog(null, "The Process Ends Here!");
//The test message works fine//    
//The JOptionPane statement don't work and program doesn't end. WHY?//         
   }           
 }
Aga Rengma
  • 44
  • 7
  • While edits may be necessary to remove some unnecessary comments, please keep in mind that some questions are based on the comments section too. – Aga Rengma Nov 11 '18 at 20:45

2 Answers2

0

1) you can check size of string input.next() .If it is one then continue else again prompt for operator choice .

2)I would suggest better create a different method and put all logic in it and call it the number of time you want or call infinite number of times.

4)Should switch statements always contain a default clause?

Mr Nobody
  • 388
  • 4
  • 11
0

How can I make sure that the user input is exactly and strictly one char? here in my program, it accepts more than one character (+-*) but operates on the first char (+) only. I want to make sure more than one character is not accepted as input.

If you use console application and Scanner, only thing that you can do is read a String and check its length. In case you use Swing, you could implement KeyPressListener and proceed exactly after user press a button (but not for console application).

After successful execution of the program, how can I somehow let the user repeat the main method? I mean, a user adds two numbers, gets his answer and he wants to do another calculation, maybe multiply two numbers this time. I can ask the user for yes or no to continue but how do I take him/her back to the beginning? (will a loop work? how?)

You can't repeat main method. In Java main method is been executing only once. To repeate your code, you could wrap whole main method content to the infinite loop or move the content to the separate method and call it from the loop in the main method.

A the end of the program I used two methods to output a message. The system.out.print works fine but the JOptionPane method doesn't display the message and the program doesn't terminate (I have commented it out). I would like to understand why?

JOptionPane works only for graphic application (Swing/AWT). This is not available in console. You have only standard input and output there.

Is the default case required in the switch? And Am I following the correct code structure? (the arrangements and uses of curly braces)

No, default case is optional by JVM syntax. I remember, that e.g. in C++ there was reccomendation to place it (event empty), to exclude side effects of compilators. I do not know, is there such reccomendation in Java, but when I use switch, I prefer to always add it to exclude logical problem (but this is definetly optional according to syntax case). You use switch correctly.

public static void main(String[] args) {
    System.out.println("This is a simple calculator that will do basic calculations such as :"
            + "\nAddition (+)"
            + "\nMultiplication (*)"
            + "\nSubtraction (-)"
            + "\nDivision (/)");

    System.out.println();

    try (Scanner scan = new Scanner(System.in)) {
        while (true) {
            System.out.println("Enter Any positive number followed by pressing ENTER.");
            int first = scan.nextInt();

            System.out.println("Enter a valid OPERATOR (+,*,-,/) sign followed by pressing ENTER.");
            String operator = scan.next();

            while (operator.length() != 1 || !"+*-/".contains(operator)) {
                System.out.println("Please Re-enter a valid Operator (+,-*,/)");
                operator = scan.next();
            }

            scan.nextLine();
            System.out.println("Enter your Second number followed by an ENTER stroke.");
            int second = scan.nextInt();

            if ("+".equals(operator))
                System.out.println("The Resulting sum is " + (first + second));
            else if ("*".equals(operator))
                System.out.println("The Resulting mul is " + (first * second));
            else if ("-".equals(operator))
                System.out.println("The Resulting sub is " + (first - second));
            else if ("/".equals(operator))
                System.out.println("The Resulting div is " + ((double)first / second));

            System.out.println();
            System.out.println("Do you want to exit ('y' to exit)?");

            if ("y".equals(scan.next()))
                return;

            System.out.println();
        }
    }
}
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35
  • thanks alot... Not the exact solutions but helps me understand the "how to" portion. Your code taught me a lot! Best of all your method doesn't require me to parse or hit my head to understand getting that char... – Aga Rengma Nov 11 '18 at 21:33