leigero
leigero

Reputation: 3283

Java String replaceAll method having unusual affect on looping?

I'm convinced this is a product of how the string.replaceAll() method works, but for some odd reason its making my loop run twice when you type anything with a space in it?

public class TestCode{



public static void main(String[] args) throws IOException{

    Scanner scan = new Scanner(System.in);
    String input = "";

    while(!input.equals("X")){
        System.out.println("Prompt user for input");
        input = scan.next().toUpperCase();
        calculatePolynomial(input);
    }       
}


public static void calculatePolynomial(String input){
    //Clean up entry removing spaces and extracting polynomial names
    String calculation = input.replaceAll("\\s", "");
    System.out.println(calculation);
}   
}

The idea was to have the code run... printing out the message, prompting input. Then process the input and do some stuff. Repeat the process over and over until the sentinel value 'x' is entered.

But when you type input that contains a space it, for some reason, runs the loop as if each word was now separate input. So if you enter three words, it just runs the loop three times instead of once.

I just want the user's input to be without spaces and without a nightmare of logical errors.

Upvotes: 0

Views: 230

Answers (1)

rgettman
rgettman

Reputation: 178263

When using a Scanner, by default, next() tokenizes the input by whitespace. So if the user enters two words separated by whitespace, your loop will run twice.

To get the entire input in the user's input line, try using the nextLine() method instead.

Upvotes: 5

Related Questions