使用hasnext()无法通过无限循环 [英] Can't get past the infinite while loop using hasnext()

查看:125
本文介绍了使用hasnext()无法通过无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我编写的程序计算字符串用户输入中的大写和小写字母的数量。我知道hasNext()不会超过输入,但我有input.next()来推进。还有一个无限循环。



我尝试过:



Hi,
The program I wrote counts the # of upper and lowercase letters in a string user inputs. I know that hasNext() does not advance past the input, but I have input.next() to advance. Still there is an infinite loop.

What I have tried:

public class CountLetters {
    public static void main(String[] arg) {
        int[] lower = new int[26];
        int[] upper = new int[26];

        for(int i = 0; i < 26; i++)
            lower[i] = upper[i] = 0;
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the string: ");

        while(input.hasNext()) {
            String temp = input.next();
            for (int i = 0; i < temp.length(); i++) {
                char c = temp.charAt(i);
                if (Character.isUpperCase(c))
                    upper[(int) c - 65]++;
                if (Character.isLowerCase(c))
                    lower[(int) c - 97]++;
            }
            input.next();
        }
        System.out.print("a is " + lower[0]);
        System.out.print("A is " + upper[0]);
    }
}

推荐答案

请参阅以下链接:

See the following link:


无关错误?

丢弃是否正常输入的一部分

Unrelated bug ?
Is it normal to discard part of the input with
input.next();


循环中的


in the loop ?


输入中没有任何内容可以丢弃。我尝试在点击输入后添加一个ctrl + D并且它有效。显然,这是使hasNext为false的唯一方法。
No nothing in the input can be discarded. I tried adding a ctrl+D after hitting enter and it worked. Apparently that is the only way to make hasNext false.


这篇关于使用hasnext()无法通过无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆