mino
mino

Reputation: 7298

What's wrong with my Java code? It should count the spaces, but returns 0

The code is copied below. It should return the number of spaces if the character variable l is equal to a space, but always returns a 0.

I've tested it with letters and it worked, for example if I'm asking it to increment when the variable l is equal to e and enter a sentence with e in, it will count it. But for some reason, not spaces.

import java.util.Scanner;

public class countspace {

    public static void main(String[] args) {            
        Scanner input = new Scanner(System.in);         
        System.out.println("Enter a sentence:");            
        String str = input.next();          
        System.out.println(wc(str));

    }

    public static int wc(String sentence) {

        int c = 0;          
        for (int i = 0; i < sentence.length(); i++) {           
            char l = sentence.charAt(i);                
            if (l == ' ') {                 
                c++;                    
            }               
        }           
        return c;           
    }       
}

Upvotes: 0

Views: 136

Answers (3)

lc2817
lc2817

Reputation: 3742

Use String str = input.nextLine(); instead of String str = input.next(); This is the way you should do to get the next string. You could have checked that str has the wrong value.

Upvotes: 1

Matthew Flaschen
Matthew Flaschen

Reputation: 285077

Use nextLine instead. You can also print the line for debugging:

System.out.println(str);

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1504182

Scanner.next() (with the default delimited) is only parsing as far as the first space - so str is only the first word of the sentence.

From the docs for Scanner:

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.

Upvotes: 3

Related Questions