.hasNext() 和 .next() 导致无限 while 循环

.hasNext() and .next() cause infinite while loop

我处于初级编码阶段 class,这是我的作业: 编写一个没有参数的名为 palindromeCheck 的 void 方法。该方法应该具有检查单词是否是回文并将所有回文打印到屏幕的功能,每行一个。此外,输出的最后一行应包含消息:“用户提供的 y 个单词中有 x 个回文”(其中 x 是检测到的回文单词的数量,y 是用户输入的单词总数)。提示:对于本实验练习,您将需要对 String 对象使用以下方法:length() 给出字符串的长度(即它包含的字符数)和 charAt(i) - 给出位置 i 处的字符。 由于输入的输入应该用白色 space 分隔,所以我对如何创建 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.");
}

您不能依赖 keyboard.hasNext() 告诉您程序何时应该停止。键盘基本上是无限的输入源,因此 keyboard.hasNext() 可能 永远不会 return false。如果上一个输入行还有一些数据还没有被处理,它会立即return true。但是,如果上一行的所有数据都用完了,keyboard.hasNext() 将等待您输入另一行,然后在您按下 ENTER 后 return 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+"参数是一个正则表达式,指定单词之间的分隔符,意思是"white-space (\s), one or more of (+)"。

键入 Ctrl/z(Windows 上的 Ctrl/d - 还是相反?)。一切都会好起来的。

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

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

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

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

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

我还没有了解 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.");
    }
}