【问题标题】:how to split multiple line input using split function java如何使用拆分函数java拆分多行输入
【发布时间】:2015-12-09 17:28:03
【问题描述】:

我想使用拆分功能拆分多行输入,但我尝试它时它不起作用

    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 a d g d ,

输出,

但所需的输出是 整数 一种 d G d

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 这个答案中的代码有一个小错误。执行此代码时,控制台窗口不会打开,因为输入块之前没有打印语句。要解决这个问题,您需要在第 8 行之前添加一个打印语句。例如:System.out.println(" Enter a multiple line input terminated with ',' ");
    • 你是如何运行代码的?当我按原样测试它时,它工作正常。我创建了名为 LoopTest.java 的文件,然后在命令行中运行 javac LoopTest.java,然后运行 ​​java LoopTest。
    猜你喜欢
    • 2012-05-12
    • 2013-01-14
    • 1970-01-01
    • 2011-02-19
    • 1970-01-01
    • 2013-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多