java - 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]
解决方案
你的意思是?
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);
}
推荐阅读
- python - 管理内联多对多 autocomplete_fields
- python - 我在 pygame 中制作 Checkers,我希望棋子移动的方式是单击 2 次鼠标,但我不知道该怎么做
- xml - 在 IntelliJ 中添加外部依赖项后出现问题
- python-2.7 - 如何使用python解密亚马逊卖家api报告文件
- flutter - 继承 Dart Null 安全性以实现可测试性
- laravel - 无法将多个图像移动到laravel 7中的文件夹
- php - 如何在 Laravel 8 中设置不带前缀的默认语言环境
- php - Laravel:如何为“记住”的用户会话加载会话变量(绕过登录控制器)
- javascript - 如何在 Google Analytics(分析)4 (GA4) 媒体资源中添加引荐排除项
- c++ - 如何使用带有堆栈的结构?