如何使用拆分函数java

时间:2015-12-09 17:28:03

标签: java compiler-construction tokenize stringtokenizer lexical-analysis

我想使用拆分功能拆分多行输入,当我尝试它无效时

    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++;
    }
}

}

输入int d d d ,

输出,

但所需的输出是                        INT                        一个                        d                        G                        d

1 个答案:

答案 0 :(得分:0)

你在str而不是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++;
        }
    }
}