2011-05-25 161 views
2

好吧,所以我已經輸入了一些記錄到一個文本文件,我可以寫入和從這個文件中讀取,但我現在試圖通過搜索這個文本文件並遇到了問題。Txtfile搜索不起作用

package assignmentnew; 

// Import io so we can use file objects 
import java.io.*; 
import java.util.Scanner; 

public class SearchProp { 
    public void Search() throws FileNotFoundException { 
     try { 
      String details, input, id, line; 
      int count; 
      Scanner user = new Scanner(System.in); 
      System.out.println(); 
      System.out.println(); 
      System.out.println("Please enter your housenumber: "); 
      input = user.next(); 
      Scanner housenumber = new Scanner(new File("writeto.txt")); 
      while (housenumber.hasNext()) 
      { 
       id = housenumber.next(); 
       line = housenumber.nextLine(); 
       if (input.equals(id)) 
       { 
        System.out.println("House number is: " + id + "and" + line); 
        break; 
       } 
       if(!housenumber.hasNext()) { 
        System.out.println("no house with this number"); 
       } 
      } 
     } 
     catch(IOException e) 
     { 
      System.out.print("File failure"); 
     } 
    } 
} 

無論輸入怎樣的價值,有人告訴我的門牌號碼不存在的文件中,但顯然是,任何想法?

附錄:

文本文件中的文件結構。

27,Abbey View,Hexham,NE46 1EQ,4,150000,Terraced 
34,Peth Head,Hexham,NE46 1DB,3,146000,Semi Detached 
10,Downing Street,London,sw19,9,1000000,Terraced 
+1

你可以給門牌號碼文件的結構? – phtrivier 2011-05-25 11:29:50

+4

輸入文件是怎樣的? (將其粘貼並將其格式化爲問題中的代碼。) – aioobe 2011-05-25 11:29:51

+0

難道是user.next()和housenumber.nextLine()之一有尾隨空格/行分隔符而不是其他嗎?也許一個忽略空白的比較會有所幫助... – phtrivier 2011-05-25 11:32:30

回答

6

掃描儀的默認分隔符是空格,而不是,

+0

謝謝,菜鳥錯誤,剛編輯我的默認分隔符 – 2011-05-25 11:45:59

2

你必須使用​​和代碼將工作。

編輯: 之前設置它。 這就是我得到的例子27.

Please enter your housenumber: 
27 
House number is: 27 and ,Abbey View,Hexham,NE46 1EQ,4,150000,Terraced 
+0

謝謝剛纔發現在看這個 – 2011-05-25 11:45:32

+0

@Darren Burgess究竟是什麼你對你的代碼做了些什麼改變?在掃描器結束之後和while循環之前,我已經將useDelimeter放置好了,這就是我得到的,請參閱我的答案中的EDIT。 – Boro 2011-05-25 12:10:19

+0

我剛剛刪除逗號時,將我的值輸入到文本字段中,這意味着沒有必要更改掃描器的分隔符。明白你的意思,謝謝 – 2011-05-25 12:33:36