2013-12-18 4 views
0

Я написал простую программу для учебных целей, и все работает, за исключением той части, где она печатает имя и ответ на выбранный вами расчет. Кажется, что оператор if выполняет два раза, как если бы он делал шаг назад, прежде чем идти вперед.Печать Дважды

Он будет распечатывать «Хотели бы вы продолжить», но вместо того, чтобы запрашивать пользователя для Y/N, он распечатает ответ на вычисление AGAIN, а затем вопрос о том, хотят ли они продолжать, кроме во второй раз он действительно будет ждать ввода.

Заранее спасибо.

Вот мой код:

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; 

      } 
     } 
    } 
} 
+1

который 'if' плз быть конкретными – exexzian

+1

Что, если блок и который в то время как цикл? Какую строку текста вы видите дважды? – clay

+0

проверить изменения. Мне жаль, что я недостаточно ясна. Спасибо за ваш ответ – PracticeFirst

ответ

3

Вопрос является nextDouble() функция. Да, это читает двойной, но также читает символ новой строки (\n) в буфер. Так что в следующий раз, когда вы вызовете nextLine(), он сразу же разберет новую линию, вместо того, чтобы ждать ввода. Просто позвоните еще reader.nextLine(), прежде чем вы снова попросите ввести свой ввод, чтобы очистить буфер символа новой строки.

+0

Это исправлено. Огромное спасибо. :) – PracticeFirst

0

As @ adback03 сказал Сканер (obj). nextDouble() буферы «\ n» и в течение nextLine() он считывает из буфера; следовательно, в то время как цикл продолжается

[Off Тема] Я suggesst использовать включение случае

switch(choice) { 
    case 1: System.out.println(num1 + num2); break; 
    case 2: System.out.println(num1 - num2); break; 
    case 3: System.out.println(num1 * num2); break; 
    case 4: System.out.println(num1/num2); break; 
    default: System.out.println("Invalid choice"); 
} 

Гораздо легче читать :)

Смежные вопросы