Saturday, August 30, 2014

Multiple if Statements?
































So I'm trying to make a simple calculator, just to see if I can:
















































Java Code:





































import java.util.Scanner;

class Calculator {

public static void main(String[] args) {
Scanner calculator = new Scanner(System.in);

System.out.println("Hello, and welcome to Calculator.");
System.out.println("Please type M for multiplication, D for division, S for addition, or A for subtraction.");
String firstAnswer = calculator.nextLine();

if (firstAnswer.equals("M")) {
System.out.println("You have selected multiplication. Please type the first number you wish to multiply.");

double multiplyOne = calculator.nextDouble();
System.out.println("Please enter your second number.");
double multiplyTwo = calculator.nextDouble();
double multiplyResult = multiplyOne * multiplyTwo;
System.out.print("Your result is ");
System.out.print(multiplyResult);

calculator.close();
System.exit(0);
} if (firstAnswer.equals("D")); {
System.out.println("You have selected division. Please type the first number you wish to divide.");

double divideOne = calculator.nextDouble();
System.out.println("Please enter your second number.");
double divideTwo = calculator.nextDouble();
double divideResult = divideOne / divideTwo;
System.out.print("Your result is ");
System.out.print(divideResult);

calculator.close();
System.exit(0);

} if (firstAnswer.equals("A")); {
System.out.println("You have selected addition. Please type the first number you wish to add.");

double addOne = calculator.nextDouble();
System.out.println("Please enter your second number.");
double addTwo = calculator.nextDouble();
double addResult = addOne + addTwo;
System.out.print("Your result is ");
System.out.print(addResult);

calculator.close();
System.exit(0);

} if (firstAnswer.equals("S")); {
System.out.println("You have selected subtraction. Please type the first number you wish to subtract.");

double subtractOne = calculator.nextDouble();
System.out.println("Please enter your second number.");
double subtractTwo = calculator.nextDouble();
double subtractResult = subtractOne - subtractTwo;
System.out.print("Your result is ");
System.out.print(subtractResult);

calculator.close();
System.exit(0);

}

}

}



































(I'm probably doing something really stupid) Anyway, for some reason whenever I type anything other than M, it still sends me to division, even though there's no else. What am I doing wrong here?














































No comments:

Post a Comment