这个程序应该从用户那里获取一行,例如“1 2 5 8 3”,并使用它来构建一棵树。无法将每个数字分离为整数。使用 scanner.next()
读取输入,尝试使用字符串拆分,然后将每个字符串解析为整数。但我检查了树,它是空的。对出了什么问题有什么想法吗?
System.out.println("Please enter the inital values. Press enter when done.");
String input = scan.next(); // gets the entire line
String[] values = input.split(" "); // split by spaces
int[] intVals = new int[values.length]; //array to store integers
//string to int and stores in integer value array
for (int i = 0; i < values.length; i++) {
intVals[i] = Integer.parseInt(values[i]);
}
//goes through integers and adds them to tree
for (int j = 0; j < intVals.length; j++) {
oak.add(j);
}
最佳答案
如果您尝试读取诸如“1 2 5 8 3”之类的输入,请改用以下内容:
System.out.println("Please enter the inital values. Press enter when done.");
final String line = scan.nextLine();
final Scanner lineScanner = new Scanner(line);
while(lineScanner.hasNextInt()) {
oak.add(lineScanner.nextInt());
}
它首先读取整行,然后创建一个单独的 Scanner
来解析它。与您当前的方法相比,这是一种更好的方法(在我看来),因为它避免了将字符串拆分为数组并将项目手动转换为整数的必要性。扫描仪将为您完成此操作。
话虽如此,现在谈谈您当前的问题:
scan.next(); // gets the entire line
这不是真的。这只是读取一个标记,所以“一切”直到下一个分隔符(通常是空格)。所以这样做 input.split("");//用空格分割
在这里并没有多大帮助。
oak.add(j);
这会将循环计数器添加到 oak
,而不是数组 intVals
中的值。但好处是,这不再重要了。
关于java - 从用户读取一行整数 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33192928/