2016-12-06 57 views
0

我希望程序使用地圖和集合輸出給定輸入的鄰接列表。輸入本身應該是一個有向圖,每條線都應該是一條邊。我希望用戶通過邊緣輸入邊緣,然後輸入空白行來運行程序。我無法測試它是否有效,因爲當我嘗試運行該程序並輸入一個空白行時,光標只移動到下一行並且不運行該程序。我認爲它必須對我的while循環做一些事情,但我一直在修補一個小時左右,但沒有運氣。任何幫助!如何讓我的程序停止接受輸入並運行程序?

import java.util.*; 

public class AdjList { 

    public static void main(String[] args) { 

     Map<String, Set<String>> graph = new TreeMap<String, Set<String>>(); 

     ArrayList<String> lines = new ArrayList<String>(); 

     boolean control = true; 
     while(control == true){ 
      Scanner in = new Scanner(System.in); 
      if (in.nextLine().length() == 0){ 
       control = false; 
      } else { 
       while (in.hasNextLine()) { 
        lines.add(in.nextLine()); 
        if (in.nextLine().length() == 0){ 
         break; 
        } 
       } 
       for (int i = 0; i < lines.size(); i++){ 
        String line = lines.get(i); 
        String[] vertices = line.split(" "); 
        if (graph.get(vertices[0]) == null){ 
         Set<String> newSet = new HashSet<String>(); 
         newSet.add(vertices[1]); 
         graph.put(vertices[0], newSet); 
        } else { 
         Set<String> oldSet = new HashSet<String>(); 
         oldSet = graph.get(vertices[0]); 
         oldSet.add(vertices[1]); 
         graph.put(vertices[0], oldSet); 
        } 
       } 
      } 
     } 
     for(String entry : graph.keySet()) { 
      System.out.println(entry + ":" + graph.get(entry)); 
     } 
    } 
} 

什麼樣的投入將是一個例子是:

A B 
C D 
B D 
E C 
E B 

,然後輸入一個空行來運行。讓我知道你是否需要更多信息。

+0

CTRL + D模擬我相信的eof。所以你可以這樣做,!= eof,當用戶按下CTRL + D時,它會運行 – bpgeck

+0

@bpgeck我會用它,但這是一項任務,我的教授特別希望在輸入空白行時運行它。我之前在過去的任務中完成了它,但無法破解這一個 –

+0

首先,它看起來像你跳過第一行輸入。你在else之前的語句獲得下一行,並且不會將它分配給任何東西 – bpgeck

回答

1

這個while循環的問題是:

while (in.hasNextLine()) { 
    lines.add(in.nextLine()); 
    if (in.nextLine().length() == 0){ 
     break; 
    } 
} 

你做nextLine()每當它移動文件指針向前所以下次你用nextLine()它看下一行。所以,在這個while循環中,它添加行,移動到下一行,然後檢查是否爲空。你應該保存線,檢查它是否是空的,如果不是,那麼它添加到您的ArrayList像這樣:

while (in.hasNextLine()) 
{ 
    String temp = in.nextLine(); 
    if (temp.length() == 0) 
     break; 
    else 
     lines.add(temp); 
} 

即使是說,在你的代碼中的其他一些問題。例如,不需要使用while (control == true)循環。控制永遠是錯誤的唯一方法是如果第一行沒有字符。我會讓你自己找到其餘的錯誤。

+0

是的,我認爲會有,但謝謝! –

相關問題