2015-04-07 4 views
1

Для школьного задания мне поручено разделить каждую часть работы на отдельную функцию. Функция, с которой у меня возникают проблемы с doAgain(), - это то, что с учетом выбора, которое я бы включил в main().Функция, застрявшая в петле

Мне сложно работать, как мне нужно. Цель состоит в том, чтобы взять пользовательский ввод, выполнить ops на нем, а затем попросить пользователя проверить, хотите ли они снова запустить задание.

Когда функция doAgain() срабатывает, она завершает программу, если введено «0», но не выполняется повторная запуск основной программной логики, если введена «1».

Я уверен, что мне не хватает чего-то простого, но я немного ударил головой. Любые случайные люди могли бы любезно дать некоторые намеки?

Вот мой код:

import java.util.Scanner; 

public class numbersAssignment { 

    static int numberOne = 0; 
    static int numberTwo = 0; 
    static int numberThree = 0; 
    static int largest = 0; 
    static int smallest = 0; 
    static int product1 = 0; 
    static int sum = 0; 
    static int average = 0; 
    static boolean numbersDiffer = false; 
    static int doItAgain = 1; 

    public static void main(String[] args) { 

     while (doItAgain != 0) { 
      while (numbersDiffer != true) { 
       numberOne = getNumber(); 
       numberTwo = getNumber(); 
       numberThree = getNumber(); 
       if (verifyDiff(numberOne, numberTwo, numberThree)) { 
        calcPrintNumbers(numberOne, numberTwo, numberThree); 
        numbersDiffer = true; 
       } 
      } 
      //where it all goes wrong - doAgain() stuck... 
      doItAgain = (doAgain()); 
     } 
    }//main 

    /* 
    ****************************************************************************** 
    * getNumber:                 * 
    * This method will ask the user for the number that is to be used in the * 
    * program. All numbers MUST BE INTEGERS, and must use DIFFERENT values. *         * 
    ******************************************************************************/  
    public static int getNumber() { 
       int number = 0; 

       Scanner input = new Scanner(System.in); 
       boolean done = false; 
       while (done != true) { 
        try { 
         System.out.println("Please enter a UNIQUE integer for the program ===> "); 
         number = input.nextInt(); 
         if (number <= 0){ 
          throw new NumberFormatException(); 
         } 
         done = true; 
        }//try 
        catch (Exception message) { 
         input.nextLine(); 
         System.out.println("Bad input, retry"); 
        }//catch 

       }//while 
       return number; 

     }//getNumber 

    /* 
    ****************************************************************************** 
    * calcPrintNumbers:               * 
    *  This method will recieve the three user input variables. The program * 
    *  will then calculate and print, the SUM,AVERAGE,PRODUCT,LARGEST, as well* 
    *  as the SMALLEST of the three numbers. It will then print the results, * 
    *  AS WELL AS THE VALUES STORED IN THE THREE VARIABLES.     *   
    ******************************************************************************/   
    public static void calcPrintNumbers(int numberOne, int numberTwo, int numberThree) 
     { 
       System.out.println("The smallest number is: " + Math.min(numberOne, Math.min(numberTwo, numberThree))); 
       System.out.println("The largest number is: " + Math.max(numberOne, Math.max(numberTwo, numberThree))); 
       System.out.println("The average is: " + ((numberOne + numberTwo + numberThree) /3)); 
       System.out.println("The product is: " + Math.multiplyExact(numberOne, Math.multiplyExact(numberTwo, numberThree))); 
       System.out.println("The sum is: " + (numberOne + numberTwo + numberThree)); 

     }//End of the calcSumPrint method   

    /* 
    ******************************************************************************* 
    * doAgain:                 * 
    * This method will NOT receive incoming data, but it will it will   * 
    * ask for, verify, and return the users choice of whether to continue the * 
    * program or not. The code looks for a choice of 1 to end the program,  * 
    * ANY OTHER INTEGER will continue to run the program.      * 
     ******************************************************************************/ 
    public static int doAgain() 
     { 
       int usersChoice = 0; 
       System.out.println("Enter '0' to quit, or '1' to run again: "); 
       Scanner input = new Scanner(System.in);  
       usersChoice = input.nextInt(); 
       return usersChoice; 
     }//End of the getChoice method   

    /* 
    ******************************************************************************* 
    * verifyDiff:                 * 
    * This method accepts the three variable as arguments. It then compares all*      * 
    * three to see if any values are the same. If they ARE, the method returns * 
    * a false, if all three variable are NOT the same, the method returns true.* 
    *******************************************************************************/ 
    public static boolean verifyDiff(int numberOne, int numberTwo, int numberThree) 
     { 
      boolean allDiff = false;    
      if(numberOne != numberTwo && numberOne != numberThree && numberTwo != numberThree) 
       allDiff = true;  
      else { 
       System.out.println("You tried to use a duplicate number, try again: "); 
      } 
      return allDiff; 
     }//End of the getChoice method   
} 

Большое спасибо!

ответ

2

вам необходимо сбросить значение numbersDiffer для false

добавить эту строку numbersDiffer = false после вы спросите для ввода, или вне внутреннего цикла.

как этот

doItAgain = (doAgain()); 
numbersDiffer = false; 

Причиной того, что ваша программа не выполнить вашу основную логику, потому что вы не сбросить значение numbersDiffer которое всегда true, так что вам нужно сбросить его false в для удовлетворения условий

+0

D'oh! Большое спасибо! – user132791

2

Когда пользователи просят сделать это снова, необходимо сбросить значение numbersDiffer к false, или внутреннему, а петля будет пропущена и выполнение продолжится путем вызова метода doAgain (навсегда ...).

Как это:

while (doItAgain != 0) { 
     numbersDiffer = false; 
     while (numbersDiffer != true) { 
     [...] 

или потому, что doItAgain переменная является статическим, в doAgain методе непосредственно. Кстати, тип boolean подойдет лучше.

демо: http://ideone.com/HGGbkU

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