izzy streaks
izzy streaks

Reputation: 13

For loop doesn't loop my else statement (Java)?

I am writing a simple code that takes an input read by the scanner and saved into a variable word. It is required for an assignment to create a separate method that will take that string and convert all the letters to a '?' mark. At the spaces, however, there should be a space. The problem is that every time I run this code, it stops at the space.

Here is my code:

import java.util.Scanner;

public class commonPhrase {
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        String word;
        System.out.print("Welcome to the Guessing Game.");
        System.out.println("");
        System.out.println("Please enter a common phrase");
        word = input.next();
        createTemplate(word);
    }
    public static String createTemplate(String word) {
        String sPhrase = "";
        for (int i=0; i < word.length(); i++) {
            if (word.charAt(i) == ' '){
                sPhrase += " ";
            }
            else {
                sPhrase += "?";                 
            }
        }
        System.out.println(sPhrase);
        return sPhrase;
    }
}

And here is a sample run of it:

Welcome to the Guessing Game.
Please enter a common phrase.
Why wont it add spaces!!!!!!!
???

Upvotes: 0

Views: 285

Answers (1)

rgettman
rgettman

Reputation: 178263

You call next() on the Scanner, but that method grabs the next token, and by default it's separating tokens by whitespace. You only gathered one word.

Call nextLine() instead, to grab the text of the entire line.

word = input.nextLine();

Sample run with fix above:

Welcome to the Guessing Game.
Please enter a common phrase
Stack Overflow
????? ????????

Upvotes: 4

Related Questions