2013-04-09 2 views
0

나는이 방법을 사용하여 텍스트 파일에서 단어를 검색하지만 지속적으로 부정적인 결과를 돌려 준다.자바 텍스트 파일 검색

public static void Option3Method(String dictionary) throws IOException 
{ 
Scanner scan = new Scanner(new File(dictionary)); 
String s; 
int indexfound=-1; 
String words[] = new String[500]; 
String word1 = JOptionPane.showInputDialog("Enter a word to search for"); 
String word = word1.toLowerCase(); 
word = word.replaceAll(",", ""); 
word = word.replaceAll("\\.", ""); 
word = word.replaceAll("\\?", ""); 
word = word.replaceAll(" ", ""); 
while (scan.hasNextLine()) { 
s = scan.nextLine(); 
indexfound = s.indexOf(word); 
} 
if (indexfound>-1) 
{ 
JOptionPane.showMessageDialog(null, "Word found"); 
} 
else 
{ 
JOptionPane.showMessageDialog(null, "Word not found"); 
} 

답변

0

증가 indexfound = s.indexOf (word)가 아닌 while 루프에서 indexfound를 증가시킵니다.

당신은 또한 파일에 occurance의 번호를 찾을 수 indexfound 값을 사용하여

while (scan.hasNextLine()) 
    { 
    s = scan.nextLine(); 
    if(s.indexOf(word)>-1) 
     indexfound++; 

    } 

제공합니다.

1

루프의 indexfound 값을 바꾸기 때문입니다. 따라서 마지막 줄에 단어가 없으면 indexfound의 최종 값은 -1이됩니다.

나는 운영자 추천 것 :

public static void Option3Method(String dictionary) throws IOException { 
    Scanner scan = new Scanner(new File(dictionary)); 
    String s; 
    int indexfound = -1; 
    String word1 = JOptionPane.showInputDialog("Enter a word to search for"); 
    String word = word1.toLowerCase(); 
    word = word.replaceAll(",", ""); 
    word = word.replaceAll("\\.", ""); 
    word = word.replaceAll("\\?", ""); 
    word = word.replaceAll(" ", ""); 
    while (scan.hasNextLine()) { 
     s = scan.nextLine(); 
     indexfound = s.indexOf(word); 
     if (indexfound > -1) { 
      JOptionPane.showMessageDialog(null, "Word found"); 
      return; 
     } 
    } 
    JOptionPane.showMessageDialog(null, "Word not found"); 
} 
0
while 루프를 브레이크

단어가 위의 코드와

while (scan.hasNextLine()) { 
    s = scan.nextLine(); 
    indexfound = s.indexOf(word); 
    if(indexFound > -1) 
    break; 
} 

문제가 발견되면합니다 - indexFound을 덮어지고 있습니다. 코드가 마지막 줄 파일에있는 경우에만 코드가 FINE으로 작동합니다.