Thursday, May 1, 2014

snagged on 'if' statement


I'm trying to draft an if statement so that if there is an error with the inital intput the program will skip the following input prompts and go straight to the default in the switch statement. Any ideas?



Java Code:



import java.util.Scanner;
public class MeddleThursday {
public static void main(String args[]) {
double n1,n2, answer;
boolean check = true;

while(true) {
System.out.print("Enter your operation: add, subtract, divide, multiply, or exit: ");
Scanner myScan = new Scanner(System.in);
String op = myScan.nextLine();

if(op.equals("exit")) {
System.out.println("Goodbye! ");
System.exit(0);
}



System.out.print("Enter your 1st number: ");
n1 = myScan.nextDouble();

System.out.print("Enter your 2nd number: ");
n2 = myScan.nextDouble();

switch (op) {
case"add":
answer = add(n1, n2);
System.out.println("The result of: "+ n1 +" plus "+ n2 +" is "+ (answer) +"\n");
break;

case"subtract":
answer = subtract(n1, n2);
System.out.println("The result of: "+ n1 +" minus "+ n2 +" is "+ (answer) +"\n");
break;

case"divide":
answer = divide(n1,n2);
System.out.println("The result of: "+ n1 +" divided "+ n2 +" is "+ (answer) +"\n");
break;

case"multiply":
answer = multiply(n1,n2);
System.out.println("The result of: "+ n1 +" times "+ n2 +" is "+ (answer) +"\n") ;
break;

default:
System.out.println("Error!"+"\n");
}
}
}
public static double add (double n1, double n2) {
return n1 + n2;
}
public static double subtract (double n1, double n2) {
return n1 - n2;
}
public static double multiply (double n1, double n2) {
return n1 * n2;
}
public static double divide (double n1, double n2) {
return n1 / n2;
}
}


No comments:

Post a Comment