循环语句逻辑

时间:2012-03-08 09:33:16

标签: java for-loop java.util.scanner do-while

我一直在尝试将这个程序编写好几个小时,所以请光临我。我甚至分别打破了循环,但是一旦我将所有东西放在一起,它就无法正常工作。

所以,让我分解我需要每个循环做什么,然后我得到什么输出:

1)我需要使用的第一个循环是do / while。在此循环中,提示用户键入单词。如果用户键入错误的单词,则会收到错误消息:

无效!再试一次!剩下2次尝试!

无效!再试一次!剩下1次尝试!

抱歉!你再也没有尝试了!

只要每次输入错误的单词,此输出就会起作用,但如果在尝试失败后输入了正确的单词,则仍会应用错误消息

2)在我的第二个循环(for循环)中,要求用户输入“3 * 8 =”如果输入错误的数字全部3次或者任何尝试都会输入24。

问题在于输入24后的循环。输出如下:

谢谢你等等。如果您是赢家,我们会致电5555555555。 3 * 8 = 不应显示3 * 8的情况。我意识到我可以休息一下;在此声明之后,但是说明具体说我不能使用break命令。

正确的输出应为:谢谢等等等等。如果您是胜利者,我们会致电5555555555。

public static void main(String[] args)
{
    Scanner input = new Scanner(System.in);

    int attempt = 2;
    int answer = 24;
    long phoneNumber = 0;
    String firstName = "";
    String lastName = "";
    String wordOfTheDay = "";

    System.out.printf("Enter the word of the day:  ");
    wordOfTheDay = input.nextLine();

    if(wordOfTheDay.equals("tired"))
    {
        for( attempt = 2; attempt >= 0; --attempt)
        {
            System.out.print(" 3 * 8 = ");
            answer = input.nextInt();
            input.nextLine();

            if( answer == 24)
            {
                System.out.printf( "Please enter your first name, last name, and phone number (no dashes or spaces)\n"                              +"in a drawing for an all-expenses-paid vacation in the Bahamas: " );

                firstName = input.next();
                lastName = input.next();
                phoneNumber = input.nextLong();

                System.out.printf(
                    "Thank you %s %s. We'll call you at %d if you're a winner.",
                    firstName,
                    lastName,
                    + phoneNumber);
            }

            else if( answer != 24)
            {
                if(attempt!=0)
                {
                    System.out.printf( "Invalid! Try Again! %d attempt(s) left!\n ", attempt);
                    continue;
                }
                else
                {
                    System.out.print( "Sorry!  You have no more attempts left!" );
                }
            }
        }
    }
    else
    {
        do
        {
            System.out.printf( "Invalid! Try Again! %d attempt(s) left!\n ", attempt);
            --attempt;
            System.out.printf("Enter the word of the day:  ");
            wordOfTheDay = input.nextLine();
        } while (attempt >= 1);

        if( attempt == 0)
        {
            System.out.print( "Sorry!  You have no more attempts left!" );
        }
    }
}

我希望我说得够清楚。

总结一下,我需要用我的do /解决问题,而不是让我在尝试失败后输入正确的单词。

另外,我需要在用户输入正确的输入后摆脱3 * 8 =显示。

谢谢!

8 个答案:

答案 0 :(得分:2)

我想你正试图这样做。!

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        int answer = 0;
        long phoneNumber = 0;
        String firstName = "";
        String lastName = "";
        String wordOfTheDay = "";

        int mainMenuAttempt = 3;
        do {
            System.out.printf("Enter the word of the day:  ");
            wordOfTheDay = input.nextLine();

            if (wordOfTheDay.equals("tired")) {

                int answerAttempt = 3;
                do {
                    System.out.print(" 3 * 8 = ");
                    answer = input.nextInt();
                    input.nextLine();
                    answerAttempt--;

                    if (answer != 24 && answerAttempt >0)
                        System.out.printf(
                                "Invalid! Try Again! %d attempt(s) left!\n ",
                                answerAttempt);

                } while (answerAttempt >0 && answerAttempt < 3 && answer != 24);

                if (answer == 24) {
                    System.out
                            .printf("Please enter your first name, last name, and phone number (no dashes or spaces)\n"
                                    + "in a drawing for an all-expenses-paid vacation in the Bahamas: ");

                    firstName = input.next();
                    lastName = input.next();
                    phoneNumber = input.nextLong();

                    System.out
                            .printf("Thank you %s %s. We'll call you at %d if you're a winner.",
                                    firstName, lastName, +phoneNumber);
                }

            }

            mainMenuAttempt--;

        } while (mainMenuAttempt >0 && mainMenuAttempt < 3 && !wordOfTheDay.equals("tired") && answer!=24);
        System.exit(0);
    }
}

答案 1 :(得分:2)

尝试将整个事情分解为非常小的函数,每个函数执行一个特定的事情。例如,您可能只有一个函数来检查单词是否正确,如果是,则返回0,如果不是则返回尝试次数。

private int checkWord(String correctWord, String wordToCheck, int attempts)
{
    if(wordToCheck.equals(correctWord))
    {
        return 0;
    }
    return attempts;
}

然后您可以创建一个接受用户输入的函数,并调用此函数来检查所述输入。然后它可以输出一个错误消息,该消息取决于前一个函数的返回码。然后该函数将返回一个代码,告诉它上面的函数情况。

public int checkWordVerbose(String question, String correctWord, int attempts)
{
    if(attempts <= 3)
    {
        Scanner scan = new Scanner(System.in);
        System.out.print(question);
        String input = scan.nextLine();
        int failureCode = checkWord(correctWord, input, attempts);

        if(failureCode == 0)
        {
            return 0;
        } 
        else
        {
            System.out.println("Invalid! Attempts left: " + (3 - failureCode));
            return 1;
        }
    }
    else
    {
        System.out.println("Sorry! You have no more attempts left!\n");
        return 2;
    }
}

最后,你可以创建一个只包含循环的函数,并保存用于维护该循环的逻辑:

public int checkWord(String correctWord)
{
    int failureCode = 1;
    int attempts = 1;
    do
    {
        failureCode = checkWordVerbose("Enter the word of the day: ", correctWord, attempts);
        attempts++;
    } while(failureCode == 1);
    return failureCode;
}

然后在main中,您需要做的就是检查checkWord(String correctWord)是否返回0.重复相同的事情进行其他检查(或者您甚至可以使用一些相同的功能),执行另一个在第一个内部,例如:

if(checkWord("tired") == 0)
{
    if(checkMath("24") == 0)
    {
        // Success!
    }
}

答案 2 :(得分:1)

除非我遗漏了某些东西,否则你正在等待第一次输入,如果它是错误的,你将进入一个do-while循环,然后再也不会检查输入是否正确。

你必须在do-while循环中移动if:

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    int attempt = 2;
    int answer = 24;
    long phoneNumber = 0;
    String firstName = "";
    String lastName = "";
    String wordOfTheDay = "";

    System.out.printf("Enter the word of the day:  ");
    wordOfTheDay = input.nextLine();
    do {
        if (wordOfTheDay.equals("tired")) {

            for (attempt = 2; attempt >= 0; --attempt) {
                System.out.print(" 3 * 8 = ");
                answer = input.nextInt();
                input.nextLine();

                if (answer == 24) {
                    System.out
                            .printf("Please enter your first name, last name, and phone number (no dashes or spaces)\n"
                                    + "in a drawing for an all-expenses-paid vacation in the Bahamas: ");

                    firstName = input.next();
                    lastName = input.next();
                    phoneNumber = input.nextLong();

                    System.out
                            .printf("Thank you %s %s. We'll call you at %d if you're a winner.",
                                    firstName, lastName, +phoneNumber);
                }

                else if (answer != 24) {

                    if (attempt != 0) {

                        System.out
                                .printf("Invalid! Try Again! %d attempt(s) left!\n ",
                                        attempt);
                        continue;
                    } else {

                        System.out
                                .print("Sorry!  You have no more attempts left!");
                    }
                }

            }

        } else {

            System.out.printf("Invalid! Try Again! %d attempt(s) left!\n ",
                    attempt);
            System.out.printf("Enter the word of the day:  ");
            wordOfTheDay = input.nextLine();
            if (!wordOfTheDay.equals("tired")) --attempt;

        }

    } while (attempt >= 1);

    if (attempt == 0) {

        System.out.print("Sorry!  You have no more attempts left!");
    }

    System.exit(0);

}

答案 3 :(得分:1)

通常情况下,您会使用break语句,但由于您不允许设置attempt = -1会产生相同的效果:

if( answer == 24)
{
    ...
    attempt = -1; // An ugly 'break'
}

编辑:

do { } while();移至if检查之前:

    // These two lines of code are no longer required.
    //System.out.printf("Enter the word of the day:  ");
    //wordOfTheDay = input.nextLine();

    do
    {
        System.out.printf("Enter the word of the day:  ");
        wordOfTheDay = input.nextLine();

        if(!wordOfTheDay.equals("tired"))
        {
            System.out.printf(
                "Invalid! Try Again! %d attempt(s) left!\n ", --attempt);
        }
        else
        {
            attempt = 0; // Another ugly 'break'
        }
    } while (attempt >= 1);


    if(wordOfTheDay.equals("tired"))
    {
    }
    // Remove else branch as not required.

答案 4 :(得分:0)

当你得到正确的结果时,你需要离开循环。这是使用break语句完成的:

if( answer == 24)
{
    System.out.printf( "Please enter your first name, last name, and phone number (no dashes or spaces)\n" +"in a drawing for an all-expenses-paid vacation in the Bahamas: " );
    firstName = input.next();
    lastName = input.next();
    phoneNumber = input.nextLong();
    System.out.printf( "Thank you %s %s. We'll call you at %d if you're a winner.", firstName, lastName,                                + phoneNumber);
    break;
    // that's the break statement
}

答案 5 :(得分:0)

嗯,显然你必须打破外环。

当你在if块中有正确答案(即'answer == 24')时,将一些布尔变量'haveAnswer'设置为'true'(初始化为'false'并检查'系统'之前的外循环.out.print(“3 * 8 =”);'for'if(haveAnswer){break;}'

 enter code here`public static void main(String[] args)
 {

 Scanner input = new Scanner(System.in);

int attempt = 2;
int answer = 24;
long phoneNumber = 0;
String firstName = "";
String lastName = "";
String wordOfTheDay = "";


System.out.printf("Enter the word of the day:  ");
wordOfTheDay = input.nextLine();

if(wordOfTheDay.equals("tired"))
{
    boolean haveAnswer = false;
    for( attempt = 2; attempt >= 0; --attempt)
      {
        if (haveAnswer)
            break;
        System.out.print(" 3 * 8 = ");
        answer = input.nextInt();
        input.nextLine();

      if( answer == 24)
         {
            System.out.printf( "Please enter your first name, last name, and phone number (no dashes or spaces)\n"                              +"in a drawing for an all-expenses-paid vacation in the Bahamas: " );

        firstName = input.next();
        lastName = input.next();
        phoneNumber = input.nextLong();

        System.out.printf( "Thank you %s %s. We'll call you at %d if you're a winner.", firstName, lastName,                                + phoneNumber);

          haveAnswer = true;
          break;
         }

        else if( answer != 24)
        {

            if(attempt!=0)
            {

                System.out.printf( "Invalid! Try Again! %d attempt(s) left!\n ", attempt);
                    continue;
            }
            else
            {

                System.out.print( "Sorry!  You have no more attempts left!" );
            }
       }

     }

}
else
{
do
{

    System.out.printf( "Invalid! Try Again! %d attempt(s) left!\n ", attempt);
    --attempt;
    System.out.printf("Enter the word of the day:  ");
    wordOfTheDay = input.nextLine();
} while (attempt >= 1);


  if( attempt == 0)
  {

     System.out.print( "Sorry!  You have no more attempts left!" );
  }
}

System.exit(0);

}
}

答案 6 :(得分:0)

此代码不完整,但它具有您需要的ide。试一试。

boolean firstTry = true; boolean keepLo​​oping = true;

do
    {
    if(!firstTry){
            System.out.printf( "Invalid! Try Again! %d attempt(s) left!\n ", attempt);
    }

        System.out.printf("Enter the word of the day:  ");
        wordOfTheDay = input.nextLine();
    if(wordOfTheDay.equals("hey!")){
        keepLooping = false;
    }
    --attempt;
    } while (attempt >= 1 && keepLooping);

答案 7 :(得分:0)

你最好用一个休息时间跳出循环。否则循环将继续,打印“3 * 8 =”并等待你的输入。 如果你不打算使用休息,那么使尝试= -1也是有意义的。

if( answer == 24)
         {
            System.out.printf( "Please enter your first name, last name, and phone number (no dashes or spaces)\n"                              +"in a drawing for an all-expenses-paid vacation in the Bahamas: " );

        firstName = input.next();
        lastName = input.next();
        phoneNumber = input.nextLong();
        attempt = -1;
        System.out.printf( "Thank you %s %s. We'll call you at %d if you're a winner.", firstName, lastName,                                + phoneNumber);

         }