2016-10-22 79 views
0

因此,我編寫了一個程序,該程序創建紅黑樹並確定樹中紅色節點的百分比。現在我正在爲它制定主要方法。所以,這就是我現在所擁有的:更改輸入循環條件跳過輸入值的一半

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方法是插入方法,它將值插入到樹中。

回答

1

假設你從字面上讓你提到的精確變化,你的循環最終會看起來像:

while ((s.hasNextInt()) && (s.nextInt()) >= 0){ 
    int key = s.nextInt(); 
    st.put(key, i); 
    i++; 
} 

其中每次迭代調用nextInt()兩次,這當然跳過所有其他價值,爲nextInt()消耗輸入。

一個典型這裏的做法是聲明key外循環,所以你有它的條件的範圍內都有效,然後分配和測試這一切一氣呵成,如:

int key; 
while ((s.hasNextInt()) && (key = s.nextInt()) >= 0){ // <- key is assigned *and* tested 
    st.put(key, i); 
    i++; 
} 

因此,每次迭代一個nextInt()

+0

但是,如果在循環之外聲明瞭鍵並且裏面什麼都沒有,那麼我得到一個錯誤,說沒有初始化鍵。 –

+0

@davidmah如果你試圖在循環之後使用'key'作爲參數,你只會得到這個錯誤。你是? –

+0

那麼在while循環中,我打電話給我的插入方法,該方法將密鑰插入到紅黑樹中,如果密鑰未分配給任何內容,則會導致問題。我認爲它可以工作,如果我可以將鍵分配給掃描儀中的第一個值。 –