Drukowanie na dwa razy
Napisałem prosty program do celów dydaktycznych i wszystko działa z wyjątkiem części, w której wypisuje nazwę i odpowiedź na wybrane obliczenia. Instrukcja if wydaje się wykonywać dwa razy, tak jakby robiła krok wstecz przed przejściem dalej.
Wydrukuje „Czy chcesz kontynuować”, ale zamiast monitować użytkownika o T / N, wydrukuje odpowiedź na obliczenia PONOWNIE, a następnie pytanie, czy chcieliby kontynuować z wyjątkiem drugiego czasu zaczeka na wejście.
Z góry dziękuję.
Oto mój kod:
import java.util.Scanner;
public class Numbers
{
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
boolean cont;
String name, yorn;
double num1, num2, answer;
int choice, iterator = 0;
System.out.print("What is your name? ");
name = reader.nextLine();
System.out.print("Please enter a number: ");
num1 = reader.nextDouble();
if(num1%2 != 0)
{
System.out.println(name + ", the number uou entered, " + num1 + ", is odd");
}
else
{
System.out.println(name + ", the number uou entered, " + num1 + ", is even");
}
System.out.print("Please enter a second number: ");
num2 = reader.nextDouble();
if(num2%2 != 0)
{
System.out.println(name + ", the second number you entered, " + num2 + ", is odd");
}
else
{
System.out.println(name + ", the second number you entered, " + num2 + ", is even");
}
System.out.println("1. Add");
System.out.println("2. Subtract");
System.out.println("3. Multiply");
System.out.println("4. Divide");
System.out.print("Please enter the number for the operation you would like to perform on your numbers: ");
choice = reader.nextInt();
cont = true;
while(cont)
{
while(choice != 1 && choice != 2 && choice != 3 && choice != 4)
{
System.out.print("The number entered is not one of the options. Please choose one of the operations: ");
choice = reader.nextInt();
}
if(choice == 1)
{
answer = num1 + num2;
System.out.println(name +" the sum of " + num1 + " and " + num2 + " is: " + answer);
}
else if(choice == 2)
{
answer = num1 - num2;
System.out.println(name +" the difference between " + num1 + " and " + num2 + " is: " + answer);
}
else if(choice == 3)
{
answer = num1 * num2;
System.out.println(name +" the product of " + num1 + " and " + num2 + " is: " + answer);
}
else //if(choice == 4)
{
answer = num1/num2;
System.out.println(name +" the quotient of " + num1 + " and " + num2 + " is: " + answer);
}
System.out.print("Would you like to do anything else (Y/N)? ");
yorn = reader.nextLine();
if(yorn.equals("Y"))
{
System.out.println("1. Add");
System.out.println("2. Subtract");
System.out.println("3. Multiply");
System.out.println("4. Divide");
System.out.print("Please enter the number for the operation you would like to perform on your numbers: ");
choice = reader.nextInt();
}
else if (yorn.equals("N"))
{
System.out.println("Thank you for using this prgram. Have a good day");
cont = false;
}
}
}
}