I have run into some issues. I am being required to build a calculator, and for some reason, when I try using my "while (answer == 'Y')" statement, when I do the rest of the calculator such as inputting the numbers and the operation, it tells me the answer, outputs the message asking to try again, and then automatically takes the fact that I gave the answer variable the 'y' char already, and just immediately ends the program without letting me input y or n...
Java:
package homework3calculator;
public class Homework3Calculator {
public static int readNumber() throws Exception {
int digitAsciiCode = 0;
int digitNumericValue = 0;
int number = 0;
while (digitAsciiCode != '\n') {
digitAsciiCode = System.in.read();
if ( digitAsciiCode != '\n') {
digitNumericValue = digitAsciiCode - '0';
number = number * 10 + digitNumericValue;
}
} return number;
}
public static void main(String[] args) {
int number1 = 0;
int number2 = 0;
char operation;
double result = 0.0;
char answer = 'Y';
try {
while (answer == 'Y') {
System.out.println("Enter the first number.");
number1 = readNumber();
System.out.println("Enter the second number.");
number2 = readNumber();
System.out.println("Please enter an operation.");
operation = (char)System.in.read();
if (operation == '+') {
result = number1 + number2;
} if (operation == '-') {
result = number1 - number2;
} if (operation == '*') {
result = number1 * number2;
} if (operation == '/') {
if (number2 == 0)
System.out.println("Cannot divide by 0.");
else {
result = number1 / number2;
}
}
System.out.println("The result is: " + result);
System.out.println("Would you like to try again? (Y/N)");
answer = (char)System.in.read();
}
}
catch (Exception e) {
System.out.println("Keyboard failed!");
}
}
}