java - 从用户读取一行整数 - Java

标签 java tree

这个程序应该从用户那里获取一行,例如“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/

相关文章:

java - 如何在GWT CellTree中选择父节点时选择所有子节点?

java - jooq 3.7.2 for Java6 不排除是否使用模式

java - JSF 错误 - IllegalStateException : PWC3999: Cannot create a session after the response has been committed

java - 执行线程中出现 "java.lang.OutofMemoryError"的可能原因是什么?

java - 如何使用 DWR 更新用户列表

java - 如何检测树中的循环引用?

java固定线程池和定时线程池的区别

algorithm - 查找树结构中元素之间的关系,其中没有初始关系

algorithm - 递归构建六边形网格

java - 测试两棵二叉树是否相等