I created a simple command line calculator, and then after some reading I made a few tweaks and then remade it with a friends idea to make it more simpler. I'm wondering if this can be more optimized or if any part of the code can be done "better"?
I recently started learning Java and wanted for this first project of mine to end up the "best possible" written, so I can start learning on what is a "good code".
One of the things that was changed over time was the use of the Scanner
.
- Firstly I had it create a new one on each iteration of
kalkulator();
but that was obviously a unnecessary waste. - Then I had a static scanner
static Scanner scanMe = new Scanner(System.in);
but somewhere I read It was better to pass it as an argument, because something that doesn't belong anywhere doesn't have place in a good code unless it is really necessary.
Here is what I ended up with so far:
"Main" Method:
public class SimpleCalculator {
public static void main(String[] args) {
Scanner scanMe = new Scanner(System.in);
kalkulator(scanMe);
}
"Helper" Methods:
static double scanDouble(Scanner scan){
while (!scan.hasNextDouble()){
System.out.println("Invalid number! Please try again.");
scan.nextLine();
}
return scan.nextDouble();
}
static String scanOperator(Scanner scan){
String In = scan.next();
while (!(In.equals("+") || In.equals("-") || In.equals("*") || In.equals("/") || In.equals("end"))) {
System.out.println("Invalid operator! Please select either: +,-,*,/");
In = scan.next();
}
return In;
}
The Main Method:
public static void kalkulator(Scanner scan) {
double prviB = 0, drugiB = 0, rezultat = 0;
String operator;
System.out.println("Enter the 1st number: ");
prviB = scanDouble(scan);
System.out.println("Enter the 2nd number: ");
drugiB = scanDouble(scan);
System.out.println("Select an operator: (+,-,*,/) , or type 'end' for termination: ");
operator = scanOperator(scan);
switch (operator) {
case "+":
rezultat = prviB + drugiB;
break;
case "-":
rezultat = prviB - drugiB;
break;
case "*":
rezultat = prviB * drugiB;
break;
case "/":
rezultat = prviB / drugiB;
break;
case "end":
System.out.println("Terminated.");
scan.close();
System.exit(0);
break;
default:
break;
}
System.out.println("Result: " + rezultat);
System.out.println("");
kalkulator(scan);
}