因此,我编写了一个程序,该程序创建红黑树并确定树中红色节点的百分比。现在我正在为它制定主要方法。所以,这就是我现在所拥有的:更改输入循环条件跳过输入值的一半
public static void main(String[] args) {
Scanner s;
if (args.length > 0){
try{
s = new Scanner(new File(args[0]));
} catch(java.io.FileNotFoundException e){
System.out.printf("Unable to open %s\n",args[0]);
return;
}
System.out.printf("Reading input values from %s.\n",args[0]);
} else {
s = new Scanner(System.in);
System.out.printf("Enter a list of non-negative integers. Enter a negative value to end the list.\n");
}
RedBlackBST<String, Integer> st = new RedBlackBST<String, Integer>();
int i = 0;
while ((s.hasNextInt())){
int key = s.nextInt();
st.put(key, i);
i++;
}
double percent = percentRed();
System.out.println("There are " + redcount + " red nodes so");
System.out.println(percent + "% of the nodes are red");
}
我试图做的是创建一个基于无论是整数的(因此如果用户通过键入运行程序“Java RedBlackBST test10.txt”文件树其中包含10个要插入树中的值),或者如果用户没有指定文件,则会提示用户输入自己的值并在结尾处输入负值以结束列表。现在输入你自己的值不起作用,但是如果你传入一个包含数字的.txt文件,那么它的工作原理与预期完全一致。现在,作为对自己的价值观打字,我的想法改变了while循环看起来像这样:
while ((s.hasNextInt()) && (s.nextInt()) >= 0){
那么这是应该做的是经过值的列表,如果你打一个负值在列表中,然后停止读取值。这个问题是由于某种原因(即使我传入一个文件)它只读取整数中任何数组的值的一半。那么如何改变while循环,现在程序只读取数组值的一半呢?
另外我调用put
方法是插入方法,它将值插入到树中。
但是,如果在循环之外声明了键并且里面什么都没有,那么我得到一个错误,说没有初始化键。 –
@davidmah如果你试图在循环之后使用'key'作为参数,你只会得到这个错误。你是? –
那么在while循环中,我打电话给我的插入方法,该方法将密钥插入到红黑树中,如果密钥未分配给任何内容,则会导致问题。我认为它可以工作,如果我可以将键分配给扫描仪中的第一个值。 –