+ 1
Can this code be made smaller ?
//simple calculator import java.util.Scanner; public class mycalculator{ public static void main(String[] args) {//user input Scanner inp = new Scanner(System.in); int x = inp.nextInt(); String y = inp.next(); int z = inp.nextInt(); if (y.equals("+")){ System.out.println(x+z);} else if (y.equals("-")){ System.out.println(x-z);} else if (y.equals("*")){ System.out.println(x*z);} else if (y.equals("/")){ System.out.println(x/z);} }}
1 Respuesta
+ 3
Use switch statement
int sum=0;
switch(y) {
case "+":sum=x+z;
break;
case "-":sum=x-z;
break;
case "/":sum=x/z;
break;
//last case
}
System.out.print(sum) ;
your above code will execute fast as compared to navie if else
Because if one condition is matched it stop matching following statements
You can use switch here also.
use bufferreader while taking input it will increase the speed of execution..