【发布时间】:2018-05-11 22:40:44
【问题描述】:
我正在尝试比较两个 int 数组,其中数组 1 是标准 (1...n),数组 2 是 (1...n) 范围内的随机数。需要打印出数组 2 中缺少的数字。到目前为止,我已经完成了以下操作,但我似乎无法弄清楚如何使用布尔数组来使我受益。
import java.util.Scanner;
public class findLeaves {
private boolean[] id;
private String[] surface;
private int[] head;
public boolean[] inputId() {
System.out.println("Input number of IDs");
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
id = new boolean[n];
return this.id;
}
public int[] inputHead() {
System.out.println("Input each head value.");
head = new int[id.length];
for (int i = 0; i < id.length; i++){
Scanner scan = new Scanner(System.in);
head[i] = scan.nextInt();
}
return this.head;
}
public boolean Leaves() {
for (int i = 0; i < head.length; i++);
for (int j = 0; j < id.length; j++) {
if (!id[j]) System.out.print(j + ",");
}
return true;
}
public static void main(String[] args) {
findLeaves x = new findLeaves();
x.inputId();
x.inputHead();
x.Leaves();
}
}
目前,Leaves() 只是打印出来:
0,1,2,3,4,5,6,7,8,
有没有人知道可以做到这一点的方法?我对 Java 比较陌生,并且无法在谷歌上找到任何可以解决我问题的东西。提前致谢!
编辑:
当我将 Leaves 更新为:
public boolean Leaves() {
for (int i = 0; i < head.length; i++) id[head[i]] = true;
for (int j = 0; j < id.length; j++) {
if (!id[j]) System.out.print(j + ",");
}
return true;
}
我收到以下错误:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
at findLeaves.Leaves(findLeaves.java:28)
at findLeaves.main(findLeaves.java:39)
【问题讨论】: