0

I am wondering why the count is not returning anything except 0. I was wondering if it can be done without arrays meaning this way instead. Help is appreciated, thanks!

    String word= "";
    int value = 0;

    while(!word.equalsIgnoreCase("Exit")){
        System.out.print("Type words or exit to quit: ");
        word = scan.nextLine();


    } 
        value = numberCount(word);
        System.out.print("The number of words that start with a number is "+value);
}
    public static int numberCount(String str){
        int count =0;
        char c = str.charAt(0);
        if(c >= '0' && c <= '9'){
            count++;
        }
        return count;
    }

}

zirael
  • 29
  • 2

1 Answers1

3

The problem is that you only call the method outside of the loop. (When word will be the exit condition, "Exit", which does not start with a number) This makes it so that your program will always print 0. Use your counter variable and move the method call inside the loop, so as to check every word entered:

while(!word.equalsIgnoreCase("Exit")){
    System.out.print("Type words or exit to quit: ");
    word = scan.nextLine();
    value += numberCount(word);
}   
System.out.print("The number of words that start with a number is "+value);

Sample Input/Output:

Type words or exit to quit: 2foo
Type words or exit to quit: foo
Type words or exit to quit: 3foo
Type words or exit to quit: 10foo
Type words or exit to quit: Exit
The number of words that start with a number is 3
GBlodgett
  • 12,704
  • 4
  • 31
  • 45