【问题标题】:.hasNext() and .next() cause infinite while loop.hasNext() 和 .next() 导致无限循环
【发布时间】:2018-10-15 11:38:57
【问题描述】:

我正在上初级编码课程,这是我的作业: 编写一个名为 palindromeCheck 的 void 方法,它不接受任何参数。该方法应该具有检查单词是否是回文并将所有回文打印到屏幕上的功能,每行一个。此外,输出的最后一行应该有消息:“There are x palindromes out of y words provided by user”(其中 x 是检测到的回文词数,y 是用户输入的词总数)。提示:对于本实验练习,您将需要对 String 对象使用以下方法:length() 给出字符串的长度(即它包含的字符数)和 charAt(i) - 给出位置 i 处的字符。 由于输入的输入应该由空格分隔,我对如何创建每个输入的单词进行迭代的 while 循环感到困惑。我的教授以她希望我们创建的方法的骨架形式帮助我们。在那个骨架中有一个 while 循环,它对输入的每个单词执行操作

while (keyboard.hasNext()){
someWord = keyboard.next();
// some code that performs actions
}

这个 while 循环可以工作,但在它完成并应该终止后,它只会提示输入更多输入。下面是我当前的代码,除了这个逻辑错误之外应该完成。

public static void palindromeCheck(){
    String someWord = ""; // Stores words read from user input
    int count = 0;        // keeps track of Palindrome words only
    int total = 0; // Counts the total number of lines read from the given text file
    int score = 0; // used as a condition to count palindrome words   
    System.out.println("Enter some words separated by white space."); 
    Scanner keyboard = new Scanner(System.in);

    while (keyboard.hasNext()) { // for each word user enters
        someWord = keyboard.next(); // store each word in a string variable and then do operations
        score = 0;
        int n = (someWord.length()-1);
        for (int i = 0; i < (someWord.length()-2); i++){
            for (int j = (someWord.length()-1); i < (someWord.length()-2); j--){
                j = n;
                n--;
                if(someWord.charAt(i) == someWord.charAt(j)){
                    break;
                }
                else
                    score++;
            }
        }
        if(score == 0){ // if word is palindrome adds to counter
            count++;
        }
        total++; // increment number of words as you read each one
        //System.out.println("  " + total + " " + someWord);   // test
    }
    System.out.println("There are " + count + " palindromes out of " + total + " words provided by user.");
}

【问题讨论】:

  • 你能发布你的主要方法吗?
  • 什么时候终止?
  • @m0skit0 import java.util.Scanner; public class Lab5 { public static void main (String [] args) { palindromeCheck(); }
  • @shmosel 循环应该在用户输入的所有单词都被读取后终止。
  • @sinclair 我不明白你的意思,一切都在与操纵字符串有关的循环中,我只在 main 中调用 palindromeCheck() 一次

标签: java input while-loop logic palindrome


【解决方案1】:

您不能依靠keyboard.hasNext() 来告诉您程序何时应该停止。键盘基本上是一个无限的输入源,所以keyboard.hasNext() 可能从不返回false。如果上一个输入行有一些数据还没有处理,它会立即返回true。但是如果上一行的所有数据都用完了,keyboard.hasNext() 将等待您输入另一行,然后在您按下 ENTER 后返回true

由于您不能依赖keyboard.hasNext() 来告诉您该停止处理单词,您必须编写其他方式来决定程序何时停止。

从用户的角度来看,最好的方法是读取一整行输入,处理该行中的所有单词,然后停止。您使用keyboard.nextLine() 读取整行输入:

String inputLine = keyboard.nextLine();

之后,您可以选择任意数量的方式来将该行拆分为单个单词。以下是两种方式的示例。

使用Scanner(String)

String inputLine = keyboard.nextLine();
Scanner wordScn = new Scanner(inputLine);
while (wordScn.hasNext())
{
    String someWord = wordScn.next();
    // ... process someWord
}

使用String.split(String delimRegEx)

String inputLine = keyboard.nextLine();
String[] words = inputLine.split("\\s+");
for (String someWord : words)
{
    // ... process someWord
}

split"\\s+" 参数是一个正则表达式,它指定单词之间的分隔符,意思是“空白 (\s)、一个或多个 (+) ”。

【讨论】:

    【解决方案2】:

    您的循环似乎是错误的,就您所拥有的而言,您在每个循环上都接受了新的输入,并且这种情况会无限继续下去。 (即,用户输入某些内容,按下回车键,循环再次开始;冲洗并重复)。我猜这不是你的目标所以......

    您可以获取输入,将其存储在一个字符串中,然后将该字符串拆分为多个其他字符串,并将它们存储在一个数组中。然后,您可以遍历该数组中的每个字符串并比较字符。

    顺便说一句,发布的代码因某些单词而崩溃。

    请在此处查看我的更新版本... :-)

        public static void palindromeCheck(){
    
            String someWord = ""; // Stores words read from user input
            int count = 0;        // keeps track of Palindrome words only
            int total = 0; // Counts each word/String read from the array
            System.out.println("Enter some words separated by white space."); 
            Scanner keyboard = new Scanner(System.in);
    
            //Get input from user
            String userInput = keyboard.nextLine();
    
            int nextWord = 0;
            String[] userInputArray = userInput.split("\\s+"); //Split into separate words (returns an array)
    
            while (nextWord<userInputArray.length) { //for each word in array        
    
                someWord = userInputArray[nextWord++]; // store each word in a string variable and then do operations, increments nextWord 
    
                int lastChar = (someWord.length()-1);
                int firstChar = 0;
                int loops = (someWord.length())/2;
                for(int i = 0;i<loops;i++){
                    //If characters don't match, break out of loop, otherwise carry on
                    if(someWord.charAt(firstChar++)!=someWord.charAt(lastChar--)) //move to next/previous characters once checked
                       break;
                    //if we've checked the whole word, then we've found a palindrome
                    if(i>=loops-1){
                        count++; 
                    }
                }
                total++; // increment number of words as you read each one
            }
            System.out.println("There are " + count + " palindromes out of " + total + " words provided by user.");
        }
    }
    

    【讨论】:

      【解决方案3】:

      键入 Ctrl/z(Windows 上的 Ctrl/d - 或者反过来?)。它会停止的。

      【讨论】:

        【解决方案4】:

        我还没有了解string.split,所以我想避免使用它。在看了这些答案一点点之后,我想出了一个变通方法,对于将来看到这个的任何人都可能会发现它有用。我解决了我的程序因boop之类的某些词而崩溃的问题。我通过添加两件事来修复我的程序......

        这个

        System.out.println("Enter some words separated by white space. Type exit at anytime to receive results."); 
        

        someWord = keyboard.next().toLowerCase(); // store each word in a string variable and then do operations
                if(someWord.equals("exit")){
                    break;
                }
        

        并通过在此 if/else 语句中的 else 中添加 break 语句来修复某些单词的崩溃

        if(someWord.charAt(i) == someWord.charAt(j)){
            break;
         }
         else{
            score++;
            break;
         }
        

        下面是我的更新和最终代码。

         public class Lab5
        {
            public static void main (String [] args){
                palindromeCheck();
            }
        
        public static void palindromeCheck(){
                String someWord = ""; // Stores words read from user input
                int count = 0;        // keeps track of Palindrome words only
                int total = 0; // Counts the total number of lines read from the given text file
                int score = 0; // used as a condition to count palindrome words
                String exit = "exit";
        
                System.out.println("Enter some words separated by white space. Type exit at anytime to receive results."); 
                Scanner keyboard = new Scanner(System.in);
        
                while (keyboard.hasNext()) { // for each word user enters
                    someWord = keyboard.next().toLowerCase(); // store each word in a string variable and then do operations
                    if(someWord.equals("exit")){
                        break;
                    }
                    score = 0;
                    int n = (someWord.length()-1);
                    for (int i = 0; i < (someWord.length()-2); i++){
                        for (int j = (someWord.length()-1); i < (someWord.length()-2); j--){
                            j = n;
                            n--;
                            if(someWord.charAt(i) == someWord.charAt(j)){
                                break;
                            }
                            else{
                                score++;
                                break;
                            }
                        }
                    }
                    if(score == 0){ // if word is palindrome adds to counter
                        count++;
                    }
                    total++; // increment number of words as you read each one
                }
                System.out.println("There are " + count + " palindromes out of " + total + " words provided by user.");
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-01-02
          • 2015-06-25
          • 2016-09-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-08-27
          相关资源
          最近更新 更多