该程序应从用户那里获取一行,例如“ 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(" "); // split by spaces
这里这样做并没有真正的帮助。
oak.add(j);
这将添加循环计数器oak
,而不是数组中的值intVals
。但这很好,那就不再重要了。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句