0

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.

4
  • 2
    You're using a Scanner, and using next() - the token is space (actually whitespace, which includes EOL characters). Commented Jul 12, 2013 at 20:49
  • Scanner.next() gets user input until the next space, or the next newline. I'm not sure what you expected. Commented Jul 12, 2013 at 20:50
  • Try commenting out the body of the calculatePolynomial function, so that it "does nothing at all". Does the result behave according to your current assumptions? Commented Jul 12, 2013 at 20:50
  • 1
    I don't know why this was down-voted. It may be an amateur mistake, but we're not all experts. @BrianRoach you're right, I should be using nextLine(). Commented Jul 12, 2013 at 20:55

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.