I'm learning Java and at this moment I try simple tasks to get used to with Java synthax.
Today I wrote a simple calculator and one of task goal was to finish program when user press enter key. So this is my problem, my code solution work with other keys, for example 'y'
code with 'y' key(works properly):
import java.util.Scanner;
public class SimpleCalculator {
public static void main(String[] args) {
System.out.println("Program 'Simple Calculator'");
boolean log = true;
Scanner in = new Scanner(System.in);
while (log == true) {
double result = 0;
double a, b = 0;
System.out.println("Enter the first number");
a = in.nextDouble();
char sign;
String temp;
boolean log2 = true;
while (log2 == true) {
System.out.println("Enter the algebraic operation sign ('+' ,'-' ,'*' or '/' )");
temp = in.next();
sign = temp.charAt(0);
if (sign == '+' || sign == '-' || sign == '*' || sign == '/') {
log2 = false;
switch (sign) {
case '+':
System.out.println("Enter the 2nd number ");
b = in.nextDouble();
result = a + b;
break;
case '-':
System.out.println("Enter the 2nd number ");
b = in.nextDouble();
result = a - b;
break;
case '*':
System.out.println("Enter the 2nd number ");
b = in.nextDouble();
result = a * b;
break;
case '/':
while (b == 0) {
System.out.println("Enter the 2nd number ");
b = in.nextDouble();
if (b != 0)
result = a / b;
else
System.out.println("Division by 0 is undefined for real nubers, enter 2nd number again");
}
break;
}
} else {
System.out.println("wrong operation sign, enter it once again");
}
if (log2 == false)
System.out.println("Result: " + result);
}
System.out.println("Press y for exit the program(or any other to use it once again)");
temp = in.next();
if (temp.equals("y")) {
System.out.println("y Key pressed.");
log = false;
}
}
in.close();
System.out.println("End of work");
}
}
I tried two variations of last if to end work, when Enter is pressed
temp = in.next();
if (temp.equals("")) {
System.out.println("Enter Key pressed.");
log = false;}
and the second
temp =in.next();
sign = temp.charAt(0);
if (sign == 13 ) //carriage return character code
log = false;
but both are not good in case of enter key. It would be great if somebody tell me why this two variations of if don't work properly with enter key and what is the best way to end program with end key.
Thank You :)