Search code examples
javatermination

New To Java (Program Keeps Terminating)


Need help with this: Here is my code: http://pastebin.com/7aG0xbhJ Couldn't figure out how to post it here. Just keeps saying terminated. Trying to create a calculator.

import java.util.Scanner;
public class Calculator {
    public static void main(String args[]) {
            Scanner input=new Scanner(System.in);
            System.out.println("Welcome to My Multi Calculator");
            System.out.println("Here are the choices:");
            System.out.println("(1) Convert Pounds to Kilograms");
            System.out.println("(2) Convert USD to Euro");
            System.out.println("(3) Convert Degrees F to C");
            System.out.println("(4) Calculate 20% gratuity on a bill");
            System.out.println("(5) Calculate if a number is prime");
            System.out.println("(6) Calulate the absolute difference of two numbers");
           System.out.println("(7) Quit");

        if (input.equals("1")) {
            //System.out.println("1");
            System.out.println("Input amount:");
            double size = input.nextInt();
            System.out.println("Answer: "+ size*0.453592);
        }
        if (input.equals("2")) {
            System.out.println("2");
        }
        if (input.equals("3")) {
            System.out.println("3");
        }
        if (input.equals("4")) {
            System.out.println("4");
        }
        if (input.equals("5")) {
            System.out.println("5");
        }
        if (input.equals("6")) {
            System.out.println("6");
        }
        if (input.equals("7")) {
            System.out.println("7");
        }
    }
}

Solution

  • Like said, you are testing if Scanner object equals to String instance, which is never true, as they are completely different kinds of objects.

    You'd want to replace this:

    Scanner input=new Scanner(System.in);
    // printing here
    if (input.equals(...
    

    with this:

    Scanner scanner = new Scanner(System.in);
    // printing here
    String input = scanner.nextLine();
    if (input.equals(...
    

    Addition: of course when you do that, you also need to change other references like

    double size = input.nextInt();
    

    to use your scanner instance:

    double size = scanner.nextInt();