2016-10-09 6 views
1

자바로 코딩하는 것이 처음입니다. 누구든지 내 코드를 도와 줄 수 있습니까? 나는 현재 jTextArea에 문자열을 입력하는 프로그램을 만들고 있는데, 입력 된 단어가 텍스트 파일에있는 단어와 일치하면 뭔가 할 것입니다.텍스트 파일에서 특정 단어를 읽고 무언가를 수행하기 위해 조건문을 사용하는 방법

예를 들어 'Hey'라는 단어를 입력하면 입력 된 단어가 텍스트 파일과 일치 할 때 'Hello'와 같은 텍스트가 인쇄됩니다.

내가 무슨 뜻인지 이해하시기 바랍니다. 라인이 많은 단어를 포함하기 때문에

String line; 
    String yo; 
    yo = jTextArea2.getText(); 

    try (
     InputStream fis = new FileInputStream("readme.txt"); 
     InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8")); 
     BufferedReader br = new BufferedReader(isr); 
    ) 
    { 
     while ((line = br.readLine()) != null) { 

      if (yo.equalsIgnoreCase(line)) { 
       System.out.print("Hello"); 
      } 
     } 
    } catch (IOException ex) { 
     Logger.getLogger(ArfArf.class.getName()).log(Level.SEVERE, null, ex); 
    } 

답변

1

당신은 사용할 수 없습니다 라인에 대한 같습니다 :

여기 내 코드입니다. 한 줄에있는 단어의 색인을 검색하려면이 단어를 수정해야합니다.

 try (InputStream fis = new FileInputStream("readme.txt"); 
       InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8")); 
       BufferedReader br = new BufferedReader(isr);) { 
      while ((line = br.readLine()) != null) { 
       line = line.toLowerCase(); 
       yo = yo.toLowerCase(); 
       if (line.indexOf(yo) != -1) { 
        System.out.print("Hello"); 
       } 
       line = br.readLine(); 
      } 
     } catch (IOException ex) { 
     } 
+0

코드에서 = br.readLine()를 행을 제거하십시오 도움의 종류를 제공 할 수 있습니다 = br.readLine)). 이렇게하면 일부 줄을 건너 뜁니다. – Eric

0

자바에 익숙하지 않으므로 더 깨끗한 코드를 작성할 수 있도록 자바 8을 배우시기 바랍니다. 아래 자바 8의 솔루션을 쓰기가, 희망이 선이 ((그동안의 라인을 할당되기 때문에

 String yo = jTextArea2.getText(); 
     //read file into stream, 
     try (java.util.stream.Stream<String> stream = Files.lines(Paths.get("readme.txt"))) { 

      List<String> matchLines = stream.filter((line) -> line.indexOf(yo) > -1).collect(Collectors.toList()); // find all the lines contain the text 
      matchLines.forEach(System.out::println); // print out all the lines contain yo 

     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
0
import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.Scanner; 

public class WordFinder { 
    public static void main(String[] args) throws FileNotFoundException { 
     String yo = "some word"; 
     Scanner scanner = new Scanner(new File("input.txt")); // path to file 
     while (scanner.hasNextLine()) { 
      if (scanner.nextLine().contains(yo)) { // check if line has your finding word 
       System.out.println("Hello"); 
      } 
     } 
    } 
}