Click here to Skip to main content
15,887,135 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
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:

Java
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]);
    }
}
Posted
Updated 10-Apr-16 21:22pm
v2

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

in the loop ?
 
Share this answer
 
v2
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.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900