0

Not sure what I'm doing wrong here but the output comes out as

Enter 2 numbers 15 25 (for example) Select whether you'd like to add, subtract, multiply or divide.

The user selects add. Then nothing happens?

import java.util.Scanner;

public class Lab1 {

    public static void main(String[] args) {

        @SuppressWarnings("resource")
        Scanner input = new Scanner(System.in);

        System.out.println("Enter 2 numbers ");
        int numb1 = input.nextInt();
        int numb2 = input.nextInt();
        System.out.println("Would you like to add, multiply, subtract or divide");
        String add = input.next();
        String multiply = input.next();
        String divide = input.next();
        String subtract = input.next();

        if (input.equals(add)) {

            System.out.println(numb1 + " + " + numb2 + " is: " + (numb1 + numb2));

        }

        else if (input.equals(multiply)) {
            System.out.println(numb1 + " * " + numb2 + " is: " + (numb1 * numb2));
        }

        else if (input.equals(divide)) {
            System.out.println(numb1 + " / " + numb2 + " is: " + (numb1 / numb2));
        }

        else if (input.equals(subtract)) {
            System.out.println(numb1 + " - " + numb2 + " is: " + (numb1 - numb2));
        }

        else {
            System.out.println("Try again");
        }
    }
}
Nathaniel Ford
  • 16,853
  • 18
  • 74
  • 88
Nooberistic
  • 11
  • 2
  • 4

5 Answers5

1

Your problem is here:

String add = input.next();
String multiply = input.next();
String divide = input.next();
String subtract = input.next();

Each of these lines will ask the Scanner for input and assign it to separate strings. You can show what is actually happening here by using a debugger or adding a System.out.println(add); statement after the block above. Then you do this:

if (input.equals(add)) {

You're now checking to see if the Scanner object is equal to the add object. Since these are different types they will never be equal.

What you should do is first set up your options as constants:

static final String ADD = "add";

Then you will need to get the input:

String choice = input.nextLine();

Then you can check to see if the choice is equal to one of your constants.

if (choice.equals(ADD))

Note that next() will return the next 'token', determined by the delimiter set up in the Scanner. What you probably want is nextLine(), which will get a whole line of input. In this case it probably doesn't matter, but if you're looking for a whole input it might. That said, there are some pitfalls you should learn about.

How to use Enumerations

Since it was asked in the comments, here is how you would implement this using an enumeration. As you can see, this becomes very extensible as you need to add operators: you no longer need to worry about modifying your main function, and can simply add new operators and their behavior. You would do this only if Commands never need to carry state, but only behavior, as they do here. This sort of setup is particularly useful with command-line programs that have to understand a variety of tokens (you can implement equals or other methods to allow + and Add and add to all be equivalent, for instance).

import java.util.Scanner;

public class Calculator {

  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.println("Enter 2 numbers ");
    int numb1 = input.nextInt();
    int numb2 = input.nextInt();
    System.out.println("What would you like to do to these two numbers? Commands available are:");
    for (Command command : Command.values()) {
      System.out.println(command);
    }
    System.out.println("");
    String operator = input.next();
    for (Command command : Command.values()) {
      if (command.toString().equals(operator)) {
        command.printResult(numb1, numb2);
      }
    }
  }

  public interface CommandInterface {
    public void printResult(int x, int y);
  }

  public enum Command implements CommandInterface {
    ADD {
      public void printResult(int x, int y) {
        System.out.println(x + " + " + y + " is: " + (x + y));
      }
    },
    SUBTRACT {
      public void printResult(int x, int y) {
        System.out.println(x + " + " + y + " is: " + (x + y));
      }
    },
    MULTIPLY {
      public void printResult(int x, int y) {
        System.out.println(x + " + " + y + " is: " + (x + y));
      }
    },
    DIVIDE {
      public void printResult(int x, int y) {
        System.out.println(x + " + " + y + " is: " + (x + y));
      }
    };
  }
}

A run-time example:

Enter 2 numbers 
1 2
What would you like to do to these two numbers? Commands available are:
ADD
SUBTRACT
MULTIPLY
DIVIDE

ADD
1 + 2 is: 3

Process finished with exit code 0

Community
  • 1
  • 1
Nathaniel Ford
  • 16,853
  • 18
  • 74
  • 88
  • What is the point of a constant? if anything it makes the code harder to understand here. – Natecat Apr 14 '16 at 23:53
  • Constants are good practice. I would actually use an [Enumeration](https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html) here, but it's easier to explain as a constant. – Nathaniel Ford Apr 14 '16 at 23:54
  • They're good practice when they represent something that isn't obvious on the value. This would only be used once, and since the variable name and it's value both represent essentially the same thing, it would be better practice to simply use a string literal in the if statements. I honestly don't even see how you would use an enum here. – Natecat Apr 15 '16 at 00:16
  • Because Java is strongly typed, it is good to leverage that wherever possible. I've included in the answer how you would use enumerations. While the point is correct that constants aren't strictly needed here, good practices are good to practice everywhere. Note, for instance, that if you want to list what commands are available, it is easier to keep that in sync if you have the available commands as constants. – Nathaniel Ford Apr 15 '16 at 00:35
0

You're doing a few things wrong here.

First, you are taking the values of add, subtract, and so on from input. Instead, create static final String constants for those.

For example: static final String ADD = "Add";

You're also checking for equality of a Scanner to a String; that's not what you're wanting. When you ask them what operation they want to perform you would get that through input and compare it to the strings you defined earlier (e.g. ADD).

If you were sure the input would match exactly it would look like:

input.nextLine().equals(ADD);

Of course, you could just switch over the input like:

switch(input.nextLine()) {
    case ADD:
    ...
}

...

ChiefTwoPencils
  • 11,778
  • 8
  • 39
  • 65
0

It's because of these lines:

String add = input.next();
String multiply = input.next();
String divide = input.next();
String subtract = input.next();

You're telling it to wait for the user to enter four strings, but the user has entered only one string. What you want is to wait for one string, then check the string to see what operation the user wants to perform.

NRitH
  • 11,597
  • 4
  • 36
  • 40
0

There are many ways to do what you need such as: using if/else, switch. But I'm going to do it with what you have so far. One thing I want to mention is that if you are entering multiple numbers in one single line you can always use a for loop and then convert them to integers.

Here's m solution. Hope it helps!

import java.util.Scanner;

public class Lab1 {

public static void main(String[] args) {

    @SuppressWarnings("resource")
    Scanner input = new Scanner(System.in);
    double result = 0;
    String add = "add";
    String multiply = "multiply";
    String subtract = "subtract";
    String divide = "divide";

    System.out.println("Enter 2 numbers");

    String str = input.nextLine(); 
    String[] numbers = str.split(" ");

    int[] myNumbers = new int[numbers.length];
    for (int j = 0; j < numbers.length; j++) {
        myNumbers[j] = Integer.parseInt(numbers[j]);
    }

    System.out
            .println("Would you like to add, multiply, subtract or divide");
    String choice = input.nextLine();

    if (choice.equals(add)) {
        for (int i = 0; i < myNumbers.length; i++) {
            result =  myNumbers[0] + myNumbers[myNumbers.length - 1];
        }
        System.out.println("The sum is: " + result);

    }
    else if (choice.equals(multiply)) {
        for (int i = 0; i < myNumbers.length; i++) {
            result = myNumbers[0] * myNumbers[myNumbers.length - 1];
        }
        System.out.println("numb1 *  numb2 is: " + result);

    }

    else if (choice.equals(subtract)) {
        for (int i = 0; i < myNumbers.length; i++) {
            result = myNumbers[0] - myNumbers[myNumbers.length - 1] ;
        }
        System.out.println("numb1 - numb2 is: " + result);

    }

    else if (choice.equals(divide)) {
        for (int i = 0; i < myNumbers.length; i++) {
            result = (double)(myNumbers[0])/(double)myNumbers[myNumbers.length - 1] ;
        }
        System.out.println("numb1 / numb2 is: " + result);

    }

    else {
        System.out.println("Try again");
    }

 }
}
HenryDev
  • 4,228
  • 5
  • 18
  • 50
0

I couldn't figure it out with the Strings I kept getting an error when trying to do static final String ADD = "add"; for the operators, once I removed the static it went away, but still wouldn't work. After changing it to String String choice = input.nextLine(); and then doing the if (choice.equals (add)){ it would just automatically skip down to the else statement to try again. I just used int instead since I understood that. Thanks for all the help on this. This is just intro to java programming and I'm completely lost, not looking so good.

import java.util.Scanner;

public class Lab1 {

    public static void main(String[] args) {


        Scanner input = new Scanner(System.in);




        System.out.println("Enter 2 numbers ");
        int numb1 = input.nextInt();
        int numb2 = input.nextInt();
        System.out.println("Select 1 for addition.");
        System.out.println("Select 2 for subtraction.");
        System.out.println("Select 3 for division.");
        System.out.println("Select 4 for multiplication.");
        int choice = input.nextInt();


        if (choice == 1) {

            System.out.println(numb1 + " + " + numb2 + " is: " + (numb1 + numb2));

        }

        if (choice == 2) {
            System.out.println(numb1 + " - " + numb2 + " is: " + (numb1 - numb2));
        }

        if (choice == 3) {
            System.out.println(numb1 + " / " + numb2 + " is: " + (numb1 / numb2));
        }

        if (choice == 4) {
            System.out.println(numb1 + " * " + numb2 + " is: " + (numb1 * numb2));
        }

    }
}
Nooberistic
  • 11
  • 2
  • 4
  • you realize that you code doesn't work for your division right? What if I enter 3 and 6 it throws 0 do you know why? if you don't know please take a look at my code right below which handles the division situation correctly :) – HenryDev Apr 15 '16 at 01:32
  • I think I got it, your code was kind of over my head :) but it was because I needed to change it from an int to a double right? – Nooberistic Apr 15 '16 at 01:40
  • @Nooberictic Yes you need to cast the value to double to solve the division part. – HenryDev Apr 15 '16 at 02:30
  • @HenryDev Thanks, fixed it, and it's working correctly now. Wouldn't have caught that if not for your comment. Thanks again. – Nooberistic Apr 15 '16 at 04:55