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

时间:2018-05-04 23:07:48

标签: java input while-loop logic palindrome

我在初学者级编码课,这是我的任务:    编写一个名为palindromeCheck的void方法,该方法不带参数。该方法应该具有检查单词是否是回文并且在屏幕上打印所有回文的功能,每行一个。此外,输出的最后一行应该有消息:“用户提供的y字中有x个回文”(其中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.");
}

4 个答案:

答案 0 :(得分: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
}

"\\s+"的{​​{1}}参数是正则表达式,用于指定单词之间的分隔符,意思是&#34; white-space(split),一个或多个(\s)&#34;。

答案 1 :(得分:0)

键入Ctrl / z(在Windows上按Ctrl / d - 或者反过来?)。它会好起来的。

答案 2 :(得分:0)

你的循环似乎是错误的,你拥有的东西,你正在每个循环上获得新的输入,这将无限期地继续。 (即,用户输入内容,按下输入,循环再次开始;冲洗并重复)。我猜这不是你的目标......

您可以接受输入,将其存储在String中,然后将该String拆分为多个其他字符串,并将它们存储在一个数组中。然后,您可以迭代该数组中的每个String并比较字符。

顺便说一下,发布的代码会崩溃某些单词。

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

    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 :(得分:0)

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