You created a working calculator. Let me suggest some improvements for the next program version.
First some formal aspects:
- Read and follow the Java code conventions: e.g. variables and fields should begin lower-case, closing braces should be placed on their own line. We Java programmers are REALLY used to these conventions, so programs that don't follow them confuse us and lead to mis-interpretations.
- Use an IDE that can automatically maintain a proper code indentation (the "switch" line is out of alignment).
- Use spacing consistently (insert a space after an opening parenthesis or not?).
- You can omit comments like
//Close
if the next line does exactly this, explicitly. Every reader of your program will see that you are closing your resource, even without your comment.
- Use variable names like "operation" (good example), and avoid names like "xe", "xo", or "eo". A variable name should clearly tell what its content means.
- Don't declare variables some lines before you use them (like you did with
xe
and xo
). To me, that looks like old-fashioned C language from the 1970s.
So, a formally-improved version might be:
import java.util.Scanner;
public class Java101 {
public static void main(String[] args) {
System.out.println(" Welcome to Java Calculator v0.1 \n");
Scanner scanner = new Scanner(System.in);
System.out.println("\n Please enter two numbers");
System.out.print("\n First number: ");
int firstNumber = scanner.nextInt();
System.out.print("\n Second number: ");
int secondNumber = scanner.nextInt();
System.out.println("\n Select between (*,/,+,-)\n Type out the character in a single letter: ");
String operation = scanner.next();
String eo = "You have selected ";
switch (operation) {
case "*":
System.out.println(eo + "* \n Your Result: "+ ( firstNumber * secondNumber ));
break;
case "/":
System.out.println(eo + "/ \n Your Result: "+ ( firstNumber / secondNumber ));
break;
case "+":
System.out.println(eo + "+ \n Your Result: "+ ( firstNumber + secondNumber ));
break;
case "-":
System.out.println(eo + "- \n Your Result: "+ ( firstNumber - secondNumber ));
break;
default: System.out.println("\n Please select a valid character");
}
scanner.close();
System.out.println(" Closing Application ");
}
}
Then regarding structure:
- Don't do everything in the main() method. At least separate user interface and algorithmic tasks.
- Run your program and have a critical look at the inputs and outputs. Some outputs are unnecessary, some info could be added. E.g. of the three input elements (two numbers and operation), why do you just repeat the operation in the result output?
- Your program is procedural. Your next step should be to learn about object orientation. Then your application might get structured into a Calculator and a CalculationTask class with methods like readTask(), compute() and printResult().