首页 > 解决方案 > java - 如何按空格获取和拆分多个字符串行输入,然后将它们添加到Java中的arrayList?

问题描述

如何获取多行字符串并按空格拆分它们然后添加到 Java 中的 ArrayList?

输入的第一行是一个整数,表示应该扫描多少行字符串。此输入将用于检查字谜词,然后打印反字谜词。单词应该只用空格分隔,并且应该删除破折号 (-)。

样本输入:

4
sali est p-o-s-t try tset luf
set boo ins pick too let sim
set post sho kim lack
flu est test soo tick
public static Scanner scan;
public static void main(String[] args) {
     scan = new Scanner(System.in);
     int l = scan.nextInt();
     scan.nextLine();
     String[][] arr = new String[][];
     List<String> ss1 = new ArrayList<String>();
     for (int i=0; i<l; i++) {
       arr[i] = scan.nextLine().replaceAll("\\-", "").split("\\ |\\n");
            String[] dd = arr[i];
            String ddd = dd[i];
            ss1.add(ddd);
         }
      } 
      ...
}

或这个:

public static Scanner scan;
public static void main(String[] args) {
    scan = new Scanner(System.in);
    int line = scan.nextInt();
    scan.nextLine();
    String str = "";
    ArrayList<String> shd = new ArrayList<String>();
    for (int i=0; i<line; i++) {
        str += scan.nextLine();
        shd.add(str);
     }
}

此输入将用于检查字谜词,然后打印反字谜词。单词应该只用空格分隔,并且应该删除破折号 (-)。

它应该用空格分隔([ sali, est, post, ...]

实际输出:

[sali est p-o-s-t try tset luf, 
sali est p-o-s-t try tset lufset boo ins pick too let sim, 
sali est p-o-s-t try tset lufset boo ins pick too let simset post sho kim lack, 
sali est p-o-s-t try tset lufset boo ins pick too let simset post sho kim lackflu est test soo tick]

标签: javastringarraylistinputjava.util.scanner

解决方案


你的意思是?

Scanner io = new Scanner(System.in);
int n = io.nextInt();
io.nextLine();
List<String> list = new ArrayList<>();
for (int i = 1; i <= n; i++) {
    String str = io.nextLine();
    String join = String.join("", list) + str;
    list.add(join);
}

推荐阅读