-1

i want to split a multiple line input using split function when i tried it it was not working

    public static void main(String [] args)
{
    String TER = ",";
  int i=0;
    java.util.Scanner a = new java.util.Scanner(System.in);
    StringBuilder b = new StringBuilder();
    String str;
    while (!(str = a.nextLine()).equals(TER)) {
        b.append(str);//here i am getting the multiple line input
    }        
    String parts[] = str.split("\\ ");
    while(i<parts.length)
    {
        System.out.println(parts[i]);
        i++;
    }
}

}

input int a d g d ,

output ,

but the required output is int a d g d

dan diago
  • 17
  • 6

1 Answers1

0

You're splitting on str instead of b.toString()

public class LoopTest {
    public static void main(String [] args) {
        String TER = ",";
        int i=0;
        java.util.Scanner a = new java.util.Scanner(System.in);
        StringBuilder b = new StringBuilder();
        String str;
        System.out.println("Enter a multiple line input"); //opens console window
        while (!(str = a.nextLine()).equals(TER)) {
            b.append(str);//here i am getting the multiple line input
        }
        System.out.println(b.toString());
        String parts[] = b.toString().split("\\ ");
        while(i<parts.length) {
            System.out.println(parts[i]);
            i++;
        }
    }
}
flareback
  • 418
  • 1
  • 4
  • 14
  • There's a slight mistake in the code in this answer. When this code is executed, the console window does not open because there is no print statement before the input block. To solve it, you need to add a print statement before line 8. Eg.: `System.out.println(" Enter a multiple line input terminated with ',' ");` –  May 31 '16 at 07:12
  • How are you running the code? It works fine when I test it the way it was. I created the the file called LoopTest.java, then at the command line I run javac LoopTest.java and then java LoopTest. – flareback Jun 01 '16 at 13:13