0

This is a simple calculator that I need to get functioning with basic commands. The goal of this project is to program exceptions (very easy) but, I for the life of me, can not figure this out. I have looked everywhere.

Whether it's an if/else statement or a Switch/Case statement, the thrid statement always get skipped. When a user inputs "m" it is supposed to save the value of the calculation to a placeholder variable to be able to be recalled (Again, super simple). I added a default case statement to the addition section and added my save method to the default statement and it works perfectly. Every other command (r for recall, c for clear, and e for exit) also work great. m for save does not at all.....

import java.util.Scanner;

public class Calculator {
public static Scanner input = new Scanner(System.in);
public static double placeHolder;

public static void clear() {
    System.out.println("Save has been deleted, Screen has been cleared.");
}

public static void end() {
    System.out.println("Program ended..");
    input.close();
    System.exit(0);
}

public static void save(double initValue) {
    System.out.println("Number saved!");
    placeHolder = initValue;
}

public static void recall() {
    if (placeHolder != 0){
        System.out.println("Memory Place Holder Set To: " + placeHolder);
    }
    else {
        System.out.println("There is no data saved.");
    }
}

public static void commands() {
    System.out.println("e = end | c = clear | m = save | r = recall | o = continue");
    String command = input.nextLine();
    if (command.equals("e")){
        end();
    }
    else if (command.equals("c")){
        clear();
    }
    else if (command.equals("r")){
        recall();
    }

}




public static void main(String[] args) {
    boolean loop = true;
    while (loop == true){
        commands();
        System.out.println("Please enter what you would like to do: (+,-,*,/,%)");
        String function = input.nextLine();
        System.out.println("Enter the first number to be calucalted (If dividing, this is the numerator):");
        double n1 = input.nextDouble();
        System.out.println("Enter the second number to be calucalted (If dividing, this is the denominator):");
        double n2 = input.nextDouble();

        //=======================
        // Addition
        //=======================
        if (function.equals("+")){
            double sum = n1+n2;
            System.out.println(n1+"+"+ n2 +" = " + sum);
            System.out.println("e = end | c = clear | m = save | r = recall");
            String command = input.nextLine();
            input.nextLine();
            switch (command){
            case "e":
                end();
                break;
            case "c":
                clear();
                break;
            case "m":
                save(sum);
                break;
            case "r":
                recall();
                break;
            default: 
                System.out.println("Default");
                save(sum);
                break;
            }

        }
        //=======================
        // Subtraction
        //=======================
        else if (function.equals("-")){
            double sum = n1-n2;
            System.out.println(n1 + "-" + n2 +" = " + sum);
            System.out.println("e = end | c = clear | m = save | r = recall");
            String command = input.nextLine();
            input.nextLine();
            switch (command){
            case "e":
                end();
            case "c":
                clear();
            case "m":
                save(sum);
            case "r":
                recall();
            }
        }
        //=======================
        // Multiplication
        //=======================
        else if (function.equals("*")){
            double sum = n1*n2;
            System.out.println(n1 + "*" + n2 +" = " + sum);
            System.out.println("e = end | c = clear | m = save | r = recall");
            String command = input.nextLine();
            input.nextLine();
            switch (command){
            case "e":
                end();
            case "c":
                clear();
            case "m":
                save(sum);
            case "r":
                recall();
            }
        }
        //=======================
        // Division
        //=======================
        else if (function.equals("/")){
            double sum = n1/n2;
            System.out.println(n1 + "/" + n2 +" = " + sum);
            System.out.println("e = end | c = clear | m = save | r = recall");
            String command = input.nextLine();
            input.nextLine();
            switch (command){
            case "e":
                end();
            case "c":
                clear();
            case "m":
                save(sum);
            case "r":
                recall();
            }
        }
        //=======================
        // Mod
        //=======================
        else if (function.equals("%")){
            double sum = n1%n2;
            System.out.println(n1 + "%" + n2 +" = " + sum);
            System.out.println("e = end | c = clear | m = save | r = recall");
            String command = input.nextLine();
            input.nextLine();
            switch (command){
            case "e":
                end();
            case "c":
                clear();
            case "m":
                save(sum);
            case "r":
                recall();
            }
        }
    }   

        //=======================
        // Dictate loop duration:
        //=======================
        System.out.println("Would you like to continue? (Y|N): ");
        String ans = input.nextLine();
        if (ans.equals("N") || ans.equals("n")){
            System.out.println("Closing Program");
            loop = false;
            end();
        }
    }

}

The main code in question is this: I know the rest don't have a default or break statement. This one does and I am debugging and trying to figure out why the m fails. Right now if you him m, it just goes to the default case statement which, does not solve the issue.

 switch (command){
        case "e":
            end();
            break;
        case "c":
            clear();
            break;
        case "m":
            save(sum);
            break;
        case "r":
            recall();
            break;
        default: 
            System.out.println("Default");
            save(sum);
            break;

========================================================================= Here is the Fix for anyone looking at this post after the fact:

public static void main(String[] args) {
    boolean loop = true;
    while (loop == true){
        commands();
        System.out.println("Please enter what you would like to do: (+,-,*,/,%)");
        String function = input.nextLine();
        System.out.println("Enter the first number to be calucalted (If dividing, this is the numerator):");
        double n1 = input.nextDouble();
        input.nextLine();
        System.out.println("Enter the second number to be calucalted (If dividing, this is the denominator):");
        double n2 = input.nextDouble();
        input.nextLine();

        //=======================
        // Addition
        //=======================
        if (function.equals("+")){
            double sum = n1+n2;
            System.out.println(n1+"+"+ n2 +" = " + sum);
            System.out.println("e = end | c = clear | m = save | r = recall");
            String command = input.nextLine();
            switch (command){
            case "e":
                end();
                break;
            case "c":
                clear();
                break;
            case "m":
                save(sum);
                break;
            case "r":
                recall();
                break;
            }

        }
Joshua Faust
  • 256
  • 2
  • 13
  • 1
    Can you narrow the focus? Where are you seeing the problem? That's a lot of code, with a 3-part if-else in commands() and several multi-part switch statements in main(), some with breaks, some without, some with defaults, some without. – sjgp Apr 04 '17 at 21:22
  • All your `switch` statements, except the first, is **missing `break` statements**. – Andreas Apr 04 '17 at 21:23
  • I copied and pasted your code and it worked, when I added numbers for sum it gives result, and if i press m it says number saved! ? – Eduardo Dennis Apr 04 '17 at 21:24
  • Not sure what is your problem, I copied code and all works properly(apart from those missing break statements but even then sum should have worked always) – FilipRistic Apr 04 '17 at 21:25
  • you should probably extract all the different operations into one method also so you dont have so much duplicate code. – Eduardo Dennis Apr 04 '17 at 21:25
  • @EduardoDennis Yes, I had thought about that as well and was about to go that route but, I want to get this working first. Also, the reason it worked the first time is because it used the default case statement. Or atleast that is how it was working for me. But it still skips the third statement if you hit m. – Joshua Faust Apr 04 '17 at 21:27
  • @sjgp I edited the main thread - sorry for all the code. – Joshua Faust Apr 04 '17 at 21:28
  • @JoshuaFaust, kindly have a look at my solution having the complete code link and let me know if it solved your problem. I would appreciate having your upvote :) – Devendra Lattu Apr 04 '17 at 21:44
  • @JoshuaFaust also people troubleshoot issues here and go through code to try and get points, so if you find answers helpful be free handed with your upvotes if you want to continue to get help :) – Eduardo Dennis Apr 04 '17 at 21:48

4 Answers4

1
  1. after every input.nextDouble(); you need to call input.nextLine(); to consume the new line, see Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
  2. remove the unnecessary input.nextLine(); after every String command = input.nextLine();
Community
  • 1
  • 1
Loris Securo
  • 7,178
  • 2
  • 15
  • 25
  • Yup, that did it. Why does the nextDouble(); do that? Or what exactally is happening to make that happen? That's super annoying! – Joshua Faust Apr 04 '17 at 21:33
  • @JoshuaFaust as explained in the provided link, `nextDouble` does not consume the newline character (when you press `Enter`), so when you were trying to read `m` it was actually reading the leftover newline that wasn't consumed before. – Loris Securo Apr 04 '17 at 21:36
1

The nextDouble() does not consume the new line. You can fix this by parsing the full line and then use Double.parseDouble() to get the double value from the line like this

....
    System.out.println("Enter the first number to be"+ 
          "calculated (If dividing, this is the numerator):");

    double n1 = Double.parseDouble(input.nextLine());

    System.out.println("Enter the second number to be" + 
          "calculated (If dividing, this is the denominator):");

    double n2 = Double.parseDouble(input.nextLine());

    if (function.equals("+")) {
     double sum = n1 + n2;
     System.out.println(n1 + "+" + n2 + " = " + sum);
     System.out.println("e = end | c = clear | m = save | r = recall");
     String command = input.nextLine();

     switch (command) {
     case "e":
      end();
      break;
      case "c":
      clear();
      break;
     case "m":
      save(sum);
      break;
     case "r":
      recall();
      break;
     }
....

Note

You do not have to check while(loop == true) with boolean variables you can just do check by doing while(loop).

Eduardo Dennis
  • 12,511
  • 11
  • 72
  • 102
0

Check this Complete code link

There are few things you need to take care of.

  1. Have a good exception handling.
  2. Validate the user inputs

Changes I made to your code-

  1. clear the placeHolder value in clear() method
  2. using input.next() inplace of input.nextLine() and removing extra input.newLine() methods
  3. added break statements to all switch statements

enter image description here

You need to modularize a lot of things in your code. Have a look at Best Coding practice

Devendra Lattu
  • 2,532
  • 2
  • 15
  • 25
0

input.nextDouble() reads the numbers, but does nothing with the end-of-line. So when you do this later in the code:

String command = input.nextLine();

it handles the left-over end of line, not the "m" you type next.

To fix, do something to handle the end of line on your input, such as adding input.nextLine() after calling nextDouble():

double n1 = input.nextDouble();
input.nextLine();
double n2 = input.nextDouble();
input.nextLine();
sjgp
  • 250
  • 7
  • 17