如何在while循环中实现for循环?

时间:2014-01-24 14:17:45

标签: java for-loop while-loop nested-loops

很抱歉提出这么深入的问题,但我很失落。我正在解决一个问题而且我被困住了。我应该制作一个基本的菜单驱动计算器,在上限和下限之间加,减,乘,除,或生成一个随机数。我没有太大的困难,但现在我需要更改它,以便在执行操作后重新开始并显示菜单。此外,如果我输入无效的回复,则需要让他们再次尝试,直到他们输入有效的回复,除非他们在一行中输入三次无效的回复;然后它需要显示有关稍后再次尝试并退出程序的消息。这就是我被困住了。我已经在下面的代码中尝试了for和while的每个组合,但我无法使其工作。我真的很感激任何指针。

以下是要求:

  • 重复显示菜单,直到输入有效选项
  • 如果用户连续输入三个无效选项,则程序结束
  • 如果用户输入两个无效的选项,那么一个有效的选择,然后另一个无效的选择,程序不会结束
  • 程序计算每个菜单选项的正确答案
  • 通过重新显示菜单
  • ,程序在有效操作后继续
  • 当用户从菜单中选择退出选项时,程序结束 •程序不会以除零结束 - 只显示错误消息并允许用户重试

这就是我迄今为止的目标。

import java.util.Scanner;

public class BasicCalculator {

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    double numONE = 0.0;
    double numTWO = 0.0;
    double upperLimit = 0.0;
    double lowerLimit = 0.0;

    System.out.println("MENU");
    System.out.println("1. +");
    System.out.println("2. -");
    System.out.println("3. *");
    System.out.println("4. /");
    System.out.println("5. Generate a random number.");
    System.out.println("6. Quit");

    System.out.println("What would you like to do?");
    int menuSelect = input.nextInt();
    //Selects an item from the menu

    if(menuSelect == 1 || menuSelect == 2 || menuSelect == 3 || menuSelect == 4){
        System.out.println("Enter first number.");
        numONE = input.nextDouble();
        //Stores input as numONE

        System.out.println("Enter second number.");
        numTWO = input.nextDouble();
        //Stores input as numTWO
    }
    if(menuSelect == 1){
        System.out.println(numONE + numTWO);
        //Adds two numbers
    }
    else if(menuSelect == 2){
        System.out.println(numONE - numTWO);
        //Subtracts second number from first number
    }
    else if(menuSelect == 3){
        System.out.println(numONE * numTWO);
        //Multiplies two numbers
    }
    else if(menuSelect == 4){
        if(numTWO != 0){
            System.out.println(numONE / numTWO);
            //Divides first number by second number
        }
        else if(numTWO == 0){
            System.out.println("I'm sorry, you cannot divide by zero.");
        }
    }
    else if(menuSelect == 5){
        System.out.println("Enter upper limit.");
        upperLimit = input.nextDouble();
        System.out.println("Enter lower limit.");
        lowerLimit = input.nextDouble();
        double randomVal = (lowerLimit + (int)(Math.random() * ((upperLimit - lowerLimit)+1)));
        System.out.println(randomVal);
        //Displays a random integer between an upper and a lower limit
    }
    else if(menuSelect==6){
        System.out.println("Goodbye");
        System.exit(0);
    }
    else{
        System.out.println("Sorry, "+menuSelect+" is not an option.");
    }
}
}

5 个答案:

答案 0 :(得分:2)

这不是关于'while循环中的for循环',你甚至不需要它。

想象一下以下伪代码:

int invalidOptions = 0;
while ( invalidOptions < 3 ) {

    // show menu
    displayMenu();

    // read option
    int input = readInput();

    // validate input
    if ( isInputValid(input) ) {
        // check whether the user wants to exit or not
        if (input == EXIT_INPUT) {
            break;
        }

        // handle other commands
        handleInput(input);
    } else {
        // input is invalid
        invalidOptions++;
    }
}

这就是你所需要的,最好将你的程序分成更小的部分,这将更容易维护和理解。

答案 1 :(得分:2)

查看我添加的行(// <- new code

import java.util.Scanner;

public class BasicCalculator {

public static void main(String[] args) {

    int counter_WrongAttempts = 0;    // <- new code
    boolean flag_Quit = false;        // <- new code
    while (!flag_Quit) {              // <- new code
        boolean wrongAttempt = false; // <- new code


        Scanner input = new Scanner(System.in);

        double numONE = 0.0;
        double numTWO = 0.0;
        double upperLimit = 0.0;
        double lowerLimit = 0.0;

        System.out.println("MENU");
        System.out.println("1. +");
        System.out.println("2. -");
        System.out.println("3. *");
        System.out.println("4. /");
        System.out.println("5. Generate a random number.");
        System.out.println("6. Quit");

        System.out.println("What would you like to do?");
        int menuSelect = input.nextInt();
        //Selects an item from the menu

        if(menuSelect == 1 || menuSelect == 2 || menuSelect == 3 || menuSelect == 4){
            System.out.println("Enter first number.");
            numONE = input.nextDouble();
            //Stores input as numONE

            System.out.println("Enter second number.");
            numTWO = input.nextDouble();
            //Stores input as numTWO
        }
        if(menuSelect == 1){
            System.out.println(numONE + numTWO);
            //Adds two numbers
        }
        else if(menuSelect == 2){
            System.out.println(numONE - numTWO);
            //Subtracts second number from first number
        }
        else if(menuSelect == 3){
            System.out.println(numONE * numTWO);
            //Multiplies two numbers
        }
        else if(menuSelect == 4){
            if(numTWO != 0){
                System.out.println(numONE / numTWO);
                //Divides first number by second number
            }
            else if(numTWO == 0){
                System.out.println("I'm sorry, you cannot divide by zero.");
            }
        }
        else if(menuSelect == 5){
            System.out.println("Enter upper limit.");
            upperLimit = input.nextDouble();
            System.out.println("Enter lower limit.");
            lowerLimit = input.nextDouble();
            double randomVal = (lowerLimit + (int)(Math.random() * ((upperLimit - lowerLimit)+1)));
            System.out.println(randomVal);
            //Displays a random integer between an upper and a lower limit
        }
        else if(menuSelect==6){
            System.out.println("Goodbye");
            System.exit(0);
            flag_Quit = true;                                  // <- new code
        }
        else{
            System.out.println("Sorry, "+menuSelect+" is not an option.");
            wrongAttempt = true;                               // <- new code
        }


        if (wrongAttempt)                                      // <- new code
            counter_WrongAttempts++;                           // <- new code
        else                                                   // <- new code
            counter_WrongAttempts = 0;                         // <- new code
        flag_Quit = flag_Quit || (counter_WrongAttempts >= 3); // <- new code

    }
}
}

答案 2 :(得分:1)

首先,您不需要为此程序提供四个变量。由于您始终将两个数字作为输入,因此可以轻松地将它们存储在两个变量中,而不是为每个案例设置不同的变量名称。 如上所述,您不需要这种复杂的循环嵌套。检查错误数量小于3的简单时间就可以了。此外,您似乎可以使用System.out.println()命令,但对于某些应用程序(如输入),使用System.out.print()可能更好,它基本相同但不会启动新行。请尝试以下代码查看结果。 您可能考虑的另一件事是使用switch句子而不是if,else if,else if语句。

import java.util.Scanner;

public class BasicCalculator {

  public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    double firstNumber = 0.0;
    double secondNumber = 0.0;

    //New variable
    int errors = 0;

    while (errors < 3) {
        System.out.println("MENU");
        System.out.println("1. +");
        System.out.println("2. -");
        System.out.println("3. *");
        System.out.println("4. /");
        System.out.println("5. Generate a random number.");
        System.out.println("6. Quit");

        System.out.println("What would you like to do?");
        System.out.print("> ");
        int menuSelect = input.nextInt();
        //Selects an item from the menu

        if(menuSelect == 1 || menuSelect == 2 || menuSelect == 3 || menuSelect == 4) {
            errors = 0;
            System.out.print("Enter first number: ");
            firstNumber = input.nextDouble();
            //Stores input as the firstNumber

            System.out.print("Enter second number: ");
            secondNumber = input.nextDouble();
            //Stores input as the secondNumber
        }
        if(menuSelect == 1){
            System.out.println(firstNumber + secondNumber);
            //Adds two numbers
        }
        else if(menuSelect == 2){
            System.out.println(firstNumber - secondNumber);
            //Subtracts second number from first number
        }
        else if(menuSelect == 3){
            System.out.println(firstNumber * secondNumber);
            //Multiplies two numbers
        }
        else if(menuSelect == 4){
            if(secondNumber != 0){
                System.out.println(firstNumber / secondNumber);
                //Divides first number by second number
            }
            else if(secondNumber == 0){
                System.out.println("I'm sorry, you cannot divide by zero.");
            }
        }
        else if(menuSelect == 5){
            errors = 0;
            System.out.print("Enter upper limit: ");
            firstNumber = input.nextDouble();
            System.out.print("Enter lower limit: ");
            secondNumber = input.nextDouble();
            double randomVal = (firstNumber + (int)(Math.random() * ((firstNumber - secondNumber)+1)));
            System.out.println(randomVal);
            //Displays a random integer between an upper and a lower limit
        }
        else if (menuSelect==6){
            System.out.println("Goodbye");
            System.exit(0);
        }
        else{
            errors++;
            System.out.println("Sorry, "+ menuSelect + " is not an option.");
        }
    }       
    input.close();
    System.out.println("Program will exit now");
  }
}

答案 3 :(得分:0)

你可能不希望在while循环中使用for循环来处理这个问题。我只需要一个变量来跟踪你收到的无效输入数量,当它们输入无效输入时递增它,如果它们输入有效信息则将其重置为零,如果它变得过高则将它们踢出去。

例如:

import java.util.Scanner;

public class BasicCalculator {

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    double numONE = 0.0;
    double numTWO = 0.0;
    double upperLimit = 0.0;
    double lowerLimit = 0.0;
    int invalid = 0;

    System.out.println("MENU");
    System.out.println("1. +");
    System.out.println("2. -");
    System.out.println("3. *");
    System.out.println("4. /");
    System.out.println("5. Generate a random number.");
    System.out.println("6. Quit");

    System.out.println("What would you like to do?");
    int menuSelect = input.nextInt();
    //Selects an item from the menu

    while(invalid < 3){
    if(menuSelect == 1 || menuSelect == 2 || menuSelect == 3 || menuSelect == 4){
        System.out.println("Enter first number.");
        numONE = input.nextDouble();
        //Stores input as numONE

        System.out.println("Enter second number.");
        numTWO = input.nextDouble();
        //Stores input as numTWO
        invalid = 0;
    }
    if(menuSelect == 1){
        System.out.println(numONE + numTWO);
        //Adds two numbers
    }
    else if(menuSelect == 2){
        System.out.println(numONE - numTWO);
        //Subtracts second number from first number
    }
    else if(menuSelect == 3){
        System.out.println(numONE * numTWO);
        //Multiplies two numbers
    }
    else if(menuSelect == 4){
        if(numTWO != 0){
            System.out.println(numONE / numTWO);
            //Divides first number by second number
        }
        else if(numTWO == 0){
            System.out.println("I'm sorry, you cannot divide by zero.");
        }
    }
    else if(menuSelect == 5){
        System.out.println("Enter upper limit.");
        upperLimit = input.nextDouble();
        System.out.println("Enter lower limit.");
        lowerLimit = input.nextDouble();
        double randomVal = (lowerLimit + (int)(Math.random() * ((upperLimit - lowerLimit)+1)));
        System.out.println(randomVal);
        //Displays a random integer between an upper and a lower limit
        invalid = 0;
    }
    else if(menuSelect==6){
        System.out.println("Goodbye");
        System.exit(0);
    }
    else{
        System.out.println("Sorry, "+menuSelect+" is not an option.");
        invalid++;
    }
    }
    System.out.println("Too many invalid inputs. Try again later");
}
}

答案 4 :(得分:0)

int unvalid = 0;
while (unvalid < 3)
{
  //read stuff
  if ([stuff is valid])
  {
    unvalid = 0;
  }
  else
  {
    unvalid++;
  }
}