【问题标题】:Loop Statement Logic循环语句逻辑
【发布时间】:2012-03-25 19:15:38
【问题描述】:

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

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

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

对不起!你没有更多的尝试了!

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

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

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

谢谢啦啦啦啦。如果您中奖,我们会致电 5555555555。 3 * 8 = 不应显示 3 * 8 的位置。我意识到我可以休息一下;在此语句之后,但说明明确表示我不能使用 break 命令。

正确的输出应该是:Thank you blah blah。如果您中奖,我们会致电 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!" );
        }
    }
}

我希望我已经说得够清楚了。

回顾一下,我需要解决我的问题,同时在尝试失败后不让我输入正确的单词。

另外,我需要去掉用户输入正确输入后出现的 3 * 8 =。

【问题讨论】:

  • 您为当天的正确单词所做的唯一检查是在两个循环之外,因此在您第一次检查后,无论您输入什么内容,您都不会再检查一次。跨度>
  • 我应该把它重新标记为家庭作业吗?
  • 您可以尝试改进您的格式吗?例如您的 IDE 将为您执行此操作。
  • 我不知道为什么当我粘贴它时它会发生如此大的变化。我正在使用 JCreator,它在那里排列整齐。也许有更好的方法将其复制到窗口中?

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


【解决方案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.

【讨论】:

  • 这修复了我的第二个输出错误。我不知道她是否会接受这种不间断的做事方式,但我会找到一种或另一种方式。感谢您的帮助,现在找出第一个输出错误。
  • 将获得wordOfTheDay的do {} while();移动到if (wordOfTheDay.equals("tired"))校验前。
  • 我这样做了,但是每次都没有显示错误消息提示,并且在最后一次失败的尝试中它需要说“对不起!您没有更多尝试了!”例如,我将输入“tir”,它只会提示输入当天的单词而不是无效!然后重新提示。
  • 您是否查看了对答案的编辑?如果不正确,此代码将输出“无效!重试”消息。要打印“不再尝试”,您只需在 if (wordOfTheDay.equals("tired")) 之后添加 branch。
  • 是的,我将代码复制进去,这是我得到的输出: 输入当天的词汇:tir 输入当天的词汇:tirInvalid! Try Again! 1 attempt(s) left! 注意它是怎么做到的'不提示 2 次尝试!
【解决方案2】:

除非我遗漏了什么,否则您正在等待第一个输入,如果输入错误,您将进入一个 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);

}

【讨论】:

  • 我刚刚将它复制到 JCreator 的一个测试类中。这仅在第一次尝试错误时才有效。我可以输入一次tried这个词,它会提示 3 * 8 = ,但是如果我输入错误两次然后在最后一次输入时正确,它仍然会给我“”对不起!你没有更多的尝试了!”
  • 是的,因为当你到达最后一次尝试时,attempt 为 0,所以它会检查 while 条件并退出。
  • 我已经对 attempt 递减的 else 分支进行了编辑。现在应该是正确的。
  • 感谢您抽出宝贵时间帮助我。我真的很感谢愿意抽出时间帮助一个完全陌生的人的每个人。
【解决方案3】:

尝试将整个事情分解成非常小的函数,每个函数都做一件特定的事情。例如,您可能有一个函数只检查一个单词是否正确,如果是则返回 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首先,例如:

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

【讨论】:

    【解决方案4】:

    我认为您正在尝试这样做。!

    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);
        }
    }
    

    【讨论】:

      【解决方案5】:

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

      当您在 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】:

        你最好使用一个break跳出循环。否则循环将继续,打印“3 * 8 =”并等待你的输入。 如果你不想使用 break,让 attemp = -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);
        
                 }
        

        【讨论】:

          【解决方案7】:

          此代码不完整,但它具有您需要的 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);
          

          【讨论】:

            【解决方案8】:

            当你得到正确的结果时,你需要跳出循环。这是使用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
            }
            

            【讨论】:

            • 根据问题,不允许他使用break。
            • 不幸的是,我不能使用 break 语句。说明说:在 main() 结束时只对 System.exit(0) 编码一次,这意味着您必须将循环控制变量设置为一个值,如果用户将强制终止 do/while 和 for 循环提示输入正确。不能使用 break 语句。
            猜你喜欢
            • 1970-01-01
            • 2016-02-25
            • 2021-09-09
            • 2020-12-01
            • 2011-07-19
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多