-1

Right now I'm working on taking an equation, in "infix" notation and remove any spaces within that string prior to performing the rest of my program. Right now, without any spaces in the string, I receive the correct "Postfix" equation in return. But for some reason I can't seem to remove the spaces of a string that was entered using new Scanner(System.in); prior to performing my "Postfix" method(s). Here is the main method of my file:

public static void main(String[] args){
    Scanner keyboard = new Scanner(System.in);
    System.out.print("Enter the equation you'd like to evaluate: ");
    InfixToPostFix postFixString = new InfixToPostFix();
    String infix = keyboard.next();
    String newInfix = infix;
    //String newInfix = "9 * 5.3";
    //String deleteSpaceInInfix = newInfix.replace(" ", "");
    //System.out.println("deleteSpaceInInfix: " + deleteSpaceInInfix);

    System.out.println("Postfix representation: " + postFixString.InfixToPostfix(infix));
}

Now I've noted out three lines that I tried to test while noting out the lines using the scanner information. In doing so, the result of the lines commented out is: 9*5.3 as expected. So I believe that it is something with the Scanner String object.

The way that you see this method now, when 9 * 5.3 is entered produces only 9. Everything after the first space is dropped.

I've tried to look up possible causes for this problem I'm not understanding and looked it up in the API documentation but haven't seen anything.

I'd appreciate any information in helping me better understand why my Scanner object (String infix = keyboard.next(); in this instance) is being treated differently than a normal String newInfix = "9 * 5.3; object is?

Pwrcdr87
  • 935
  • 3
  • 16
  • 36
  • 1
    Have you try to use nextLine() instead of next() ? If no separator is provided, scanner will use any whitespace character as separator. This is why it is returning 9 only. – VirtualTroll Feb 22 '16 at 18:39
  • as VT said above, [next()](http://www.tutorialspoint.com/java/util/scanner_next.htm) gets the first word only, the space is the separator. – Phiter Feb 22 '16 at 18:40
  • If I could I'd give you all points for the assistance. – Pwrcdr87 Feb 22 '16 at 22:49

1 Answers1

1

The default delimiter of Scanner is whitespace. Use nextLine() if you want to read an entire line:

Scanner keyboard = new Scanner(System.in);
String infix = keyboard.nextLine();
infix = infix.replace(" ", "");
System.out.println(infix);

Note: There's also hasNextLine() to check if there is another line in the input.

pp_
  • 3,435
  • 4
  • 19
  • 27