问题引入
在校招面试的时候我踩过的一个大坑。题目第一行要求输入一个二叉树,第二行输出二叉树的之字遍历。题目本身不难,但是如何输入一个二叉树对于只会写核心代码的我还是第一次见。
首先,可以将输入二叉树转变为输入一个数组来思考,但是问题在于我们事先不知道这个数组的长度。
解决方案一
利用字符串输入转数组实现
public static void main(String[] args) {Scanner sc = new Scanner(System.in);System.out.println("输入你的数组(以逗号隔开)");String in = sc.nextLine();String[] str = in.split(",");//以逗号隔开输入//String[] str = in.split(" ");//以空格隔开输入int[] arr = new int[str.length];for(int i = 0; i < str.length; i++){arr[i] = Integer.parseInt(str[i]);}System.out.println("你输入的数组是:" + Arrays.toString(arr));
}
执行命令,结果如下:

注意:
.split(" ")只能分割间隔空格数为1的输入,若要保证任何输入的空格数都能分隔开可使用.split("\\s+")。- 输入用逗号隔开时可使用
sc.next(),用空格隔开时只能使用sc.nextLine()。
解决方案二
利用hasnext()方法判断输入长度
public static void main(String[] args) {//System.in代表标准输入,就是键盘输入Scanner sc = new Scanner(System.in);//创建列表接收数组元素List<Integer> list = new LinkedList<>();//判断是否还有下一个输入项while(sc.hasNextInt()) {list.add(sc.nextInt());}//将列表转换为数组Object[] arr = list.toArray();//输出输入项System.out.println("你输入的数组为:" + Arrays.toString(arr));
}
执行命令,输出结果如下:

可以看到,如果不按
Ctrl + D是无法退出循环的,那么问题来了,如果实例输入不执行中止命令,就无法退出hasNext()循环了。
使用hasNext()重载
while(!sc.hasNext("%")){list.add(sc.next());
}
执行命令,查看输出结果:

注意:
hasNext()没有输入的时候返回true。















