2017-09-25 8 views
-3

文字列の一致を見つけるためにこれを配置しました。文字列の一致、ちょうど他の何も他のビルドが正常に表示されています。テキストファイルを読み込んで特定のマッチを見つけて印刷しようとしていますが、コードが機能しません。

public class Lab1 { 
    public static final String FileName = "E:\\test\\new.txt"; 
    public static void main(String[] args) { 

     BufferedReader br = null; 
     FileReader fr = null; 
     try { 
      fr = new FileReader(FileName); 
      br = new BufferedReader(fr); 

      String r = null; 
      r = br.readLine(); 

      String key = "int, float, if, else , double"; 
      String iden = "a, b, c, d, e , x , y , z"; 
      String mat = "int, float, if, else , double"; 
      String logi = "int, float, if, else , double"; 
      String oth = "int, float, if, else , double"; 


      if(r.contains(key)) { 
       System.out.println(key.matches(r)); 
      } 

     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    }  
} 
+0

あなたのコンテンツを追加することができますテキストファイル ? – Berger

+0

入力ファイルはどのように見えますか? –

+0

ok ... elseブロックを追加してrを印刷します。ちょうどキックのためです。 – Stultuske

答えて

0

contains()はそのようには機能しません。

は、この文字列はchar値の 指定された配列を含む場合にのみ真リターンが含まれています。

何を行う可能性がある:

String key = "(int|float|if|else|double)"; // is a regex to check if one of the words exist 
Pattern pattern = Pattern.compile(key); 
Matcher matcher = pattern.matcher(r); 
while (matcher.find()) { // Checks if the matcher matches r. 
    System.out.println(matcher.group()); // return all the words which matched 
} 

あなたはこのために正規表現を使用する必要がありますし、単にこのような何かをしない:

List<String> keys = Arrays.asList("int", "float", "if", "else", "double"); 

Optional<String> possibleMatch = keys.stream() 
    .filter(a::contains) // if a contains one of the keys return true 
    .findFirst(); // find the first match 

if (possibleMatch.isPresent()) { // if a match is present 
    System.out.println(possibleMatch.get()); // print the match 
} 
+0

おかげで、私はそれを試してみると、これは私のために働く場合はお知らせください –

+0

それは、最初の1つを動作します –

+0

Aight素敵です。あなたはあなたの質問に答えたものを記入することができますか? –

関連する問題