patternjavaMinor
Beginners Java calculator
Viewed 0 times
beginnerscalculatorjava
Problem
I am a beginner in Java programming, and I created a calculator as my first Java project. Therefore, can you review my code and provide feedbacks/ tips?
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
double firstnum, secondnum, answer1, answer2, answer3, answer4, answer5, answer6;
String text;
int loop = 0;
Scanner input = new Scanner (System.in);
while (loop == 0) {
System.out.println("Enter your first number: ");
firstnum = input. nextDouble();
System.out.println("Please enter the operation you would like to execute: ");
text = input.next();
System.out.println("Enter your second number: ");
secondnum = input.nextDouble();
answer1= firstnum+secondnum;
answer2= firstnum-secondnum;
answer3= firstnum*secondnum;
answer4= firstnum/secondnum;
answer5= (100*(firstnum/secondnum));
answer6= Math.pow(firstnum,secondnum);
switch (text) {
case "+" :
System.out.println(answer1);
break;
case "-" :
System.out.println(answer2);
break;
case "*" :
System.out.println(answer3);
break;
case "x" :
System.out.println(answer3);
break;
case "/" :
System.out.println(answer4);
break;
case "%" :
System.out.println(answer5);
break;
case "^" :
System.out.println(answer6);
break;
default :
System.out.println("Your operation was not recongized.");
}
}
}
}Solution
I'm learning Java too!
Looking at this the only thing I might suggest is that you only do the calculations that you need to. You could then remove all answer variables and print the result of the calculations directly, saving time and memory, albeit not much.
In terms of presentation, I personally would use lowerCamelCase for variable naming, e.g. firstNum, and I would also indent all of the cases as they are within the switch block. Finally, for
Despite what I say for the presentation, that part of it is totally up to you, so do what you prefer, as long as it looks clear!
Looking at this the only thing I might suggest is that you only do the calculations that you need to. You could then remove all answer variables and print the result of the calculations directly, saving time and memory, albeit not much.
In terms of presentation, I personally would use lowerCamelCase for variable naming, e.g. firstNum, and I would also indent all of the cases as they are within the switch block. Finally, for
input. nextDouble(); I'd make sure there was no space there.Despite what I say for the presentation, that part of it is totally up to you, so do what you prefer, as long as it looks clear!
Context
StackExchange Code Review Q#135729, answer score: 4
Revisions (0)
No revisions yet.