2017-02-08 16 views
0

中的.txt文件及其相應的值這是我下面的.txt文件如何挑選的關鍵,在java中

.txt file

我想要檢索基於URl.I IP地址嘗試下面的代碼但它失敗了。我可以使用Hashmap。這是我的第一篇文章。我爲我的錯誤道歉。

公共靜態無效的主要(字符串ARGS [])拋出IOException異常{

FileReader fr = new FileReader("C:/Users/charan/Desktop/Resources/HashCheck.txt"); 
    BufferedReader br = new BufferedReader(fr); 
    Scanner in = new Scanner(System.in); 
    System.out.println("enter:"); 
    String output = in.next(); 
    String line; 

    while((line = br.readLine()) != null){ 
     if (line.contains(output)) 
     { 
      output = line.split(":")[1].trim(); 
      System.out.println(output); 
      break; 
     } 
     else 
      System.out.println("UrL not found"); 
     break; 
    } 
    in.close(); 

}} 
要刪除底部突破
+1

,否則它會破壞在第一次迭代(第一行)。如果你已經調試過,你可以很容易地看到。 –

+0

@ Nuthann98您的意思是有一個塊'{...}'周圍的'else'與塊內'break'?你有一個浮動'}'收於年底 – Nic

+0

@Nic括號爲什麼會幫助嗎?這仍然意味着它會在第一次迭代時破裂 - 噢,我明白了,你說代碼甚至不會編譯? –

回答

-1
public static void main(String args[]) throws IOException { 

    FileReader fr = new FileReader("C:/Users/charan/Desktop/Resources/HashCheck.txt"); 
    BufferedReader br = new BufferedReader(fr); 
    Scanner in = new Scanner(System.in); 
    System.out.println("enter:"); 
    String output = in.next(); 
    String line; 
    String myIp = null;      //assign a new variable to put IP into 
    while ((line = br.readLine()) != null) { 
     if (line.contains(output)) { 
      myIp = line.split(":")[1].trim(); //assign IP to the new variable 
      System.out.println(myIp); 
      break;       //break only if you get the IP. else let it iterate over all the elements. 
     } 
    } 
    in.close(); 
    if (myIp == null) {      //if the new variable is still null, IP is not found 
     System.out.println("UrL not found"); 
    } 
} 
+0

@downvoters:小心解釋還是隻投了票? –

+0

我沒有downvote,但它看起來像成功此代碼將輸出的用戶輸入,你的意思'的System.out.println(MYIP);'? – Nic

+0

謝謝@Nic。糾正。 –