validation - Java - validate operator -
i written below program, confused on part b of question. question is- write program evaluate simple expressions such 17 + 3 , 3.14159 * 4.7. expressions typed in user. input consists of number, followed operator, followed number. operators allowed +, -, *, , /. not required perform data validation here done in part (b) below. program output must show expression entered result (e.g. 17 + 3 = 20).
part b: modify program in part (a) above validate operator entered. program repeats input until valid operator entered. required make use of method validation.
here's 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 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 java, please bear me or ignorance here in question. on line should started on part b validate operator?
here have rewritten code. hope fulfill expectation.
public static void main(string[] args) { scanner console = new scanner(system.in); double digit1; double digit2; double total; string operator = ""; boolean repeatflag = true; while(repeatflag) { system.out.print("enter valid operator(+, -, /, *): "); operator = console.next(); if(!(operator.equals("+") || operator.equals("-") || operator.equals("/") || operator.equals("*"))) { repeatflag=true; continue; } repeatflag = false; } system.out.print("enter 1st number: "); digit1 = console.nextdouble(); system.out.print("enter 2nd number: "); digit2 = console.nextdouble(); if (operator.equals("-")) { total = digit1-digit2; system.out.println(+digit1+ "-" +digit2+ "=" +total); } else if (operator.equals("+")) { total = digit1+digit2; system.out.println(+digit1+ "+" +digit2+ "=" +total); } else if (operator.equals("*")) { total = digit1*digit2; system.out.println(+digit1+ "*" +digit2+ "=" +total); } else if (operator.equals("/")) { total = digit1/digit2; system.out.println(+digit1+ "/" +digit2+ "=" +total); } }
Comments
Post a Comment