java - Java:使用扫描仪根据用户输入构造二维矩阵数组
问题描述
我正在尝试使用扫描仪读取二维 3x3 矩阵的元素。输入看起来像这样:
3
11 2 4
4 5 6
10 8 -12
我目前收到错误:
Scanner scan = new Scanner(System.in);
int a = scan.nextInt();
scan.next();
List<List<Integer>> array = new ArrayList<>();
for (int i = 0; i < a; i++) {
String number = scan.nextLine();
String[] arrRowItems1 = number.split(" ");
List<Integer> list = new ArrayList<>();
for (int j = 0; j < a; j++) {
int arrItem = Integer.parseInt(arrRowItems1[j]);
list.add(arrItem);
}
array.add(list);
}
scan.close();
我该如何解决这个问题,以便根据用户输入构造一个 2d 3x3 矩阵数组的末尾?谢谢你。
解决方案
请执行下列操作:
Scanner scan = new Scanner(System.in);
int a = scan.nextInt();
scan.nextLine(); // change to nextLine
只要您进行上述更改,您的程序就可以正常工作。但是,我建议您拆分"\\s+"
以允许数字之间有任意数量的空格。
推荐阅读
- django - 为什么 CSS 效果不会出现在网页上?
- python - TensorFlow 类占位符,以及其他定义输入张量的方法
- qt - Qthread在Golang中只发出一个信号
- ios - .sqlite 文件在文档文件夹中不再可用 - Swift 5
- grails - 有没有办法从数据库中注销特定用户或所有用户?
- reactjs - 在不卸载 MainRoute 的情况下切换子路由(React-Router-Dom)
- java - Retrofit2 在 json 中解析 json
- node.js - 我可以混合使用 Ionic、Nodejs、MongoDB 和 Python 来构建混合 Web 应用程序吗?
- python - 如何使用边缘 webdriver 修复错误“SessionNotCreatedException”
- python - 为什么不接受列表作为此类中的参数?