+ 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);} }}

31st Jul 2020, 11:31 AM
Mons Joseph
Mons Joseph - avatar
1 ответ
+ 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..
31st Jul 2020, 11:48 AM
Aayush $aini
Aayush $aini - avatar