Monday, 26 August 2013

Java - validate operator

Java - validate operator

I written the below program, but confused on part b of the question.
Question is- Write a program that will evaluate simple expressions such as
17 + 3 and 3.14159 * 4.7. The expressions are to be typed in by the user.
The input always consists of a number, followed by an operator, followed
by another number. The operators that are allowed are +, -, *, and /. You
are not required to perform data validation here as it is to be done in
part (b) below. Your program output must show the expression entered
together with the result (e.g. 17 + 3 = 20).
Part B: Modify your program in part (a) above to validate the operator
entered. The program repeats for the input until a valid operator is
entered. You are required to make use of method for the validation.
Here's what i wrote
import java.util.Scanner;
public class JavaCalculator
{
public static void main(String[] args)
{
Scanner console = new Scanner(System.in);
double digit1;
double digit2;
double total;
String operator1;
System.out.print("Enter 1st number: ");
digit1 = console.nextDouble();
System.out.print("Enter the operator: ");
operator1=console.next();
System.out.print("Enter 2nd number: ");
digit2 = console.nextDouble();
if (operator1.equals("-"))
{
total = digit1-digit2;
System.out.println(+digit1+ "-" +digit2+ "=" +total);
}
else if (operator1.equals("+"))
{
total = digit1+digit2;
System.out.println(+digit1+ "+" +digit2+ "=" +total);
}
else if (operator1.equals("*"))
{
total = digit1*digit2;
System.out.println(+digit1+ "*" +digit2+ "=" +total);
}
else if (operator1.equals("+"))
{
total = digit1/digit2;
System.out.println(+digit1+ "/" +digit2+ "=" +total);
}
}
}
Just got started out with Java, please bear with me or ignorance here in
this question. On which line should I get started on Part B to validate
the operator?

No comments:

Post a Comment