2017-11-20 2 views
0

I 파일 (dna.txt)에서 각 라인에 대해 "예"를 인쇄하기 위해 노력하고있어 . 그것은 파일의 라인이 끝난 후에 멈춰야 만하지만 출력 파일 (hi.txt)에는 아무 것도 출력되지 않고 끝없이 "내"코드에 어떤 종류의 루프를 만들었습니다. 나는 그것이 "예"ses도 있어야한다는 것을 알고 있지만, 문제는 분명히 파일의 토큰을 올바르게 읽지 못하는 것보다 큽니다.라인 스캐너 루프

내 코드 :

public static void Results(Scanner console) throws 
     FileNotFoundException { 
    System.out.print("Input file name? "); 
    Scanner input = new Scanner(new File("dna.txt")); 
    System.out.print("Output file name: "); 
    File outputFile = new File("hi.txt"); 
    System.out.println(); 

    PrintStream outputRead = new PrintStream(outputFile); 
    String isProtein = "NO"; 
    while (input.hasNextLine()) { 
     String line = input.nextLine().toUpperCase(); 
     Scanner lineScan = new Scanner(line); 
     while (lineScan.hasNext()) { 
      if (line.startsWith("ATG")) { 
       if (line.endsWith("TAA") || line.endsWith("TAG") || 
         line.endsWith("TGA")) { 
        isProtein = "YES"; 
       } 
      } 
     } 
     outputRead.println(isProtein); 
    } 
    System.out.println(isProtein); 
} 

텍스트 파일 (이 텍스트 파일로 작업해야하며, 그렇지 않을지라도) :

protein? 
ATGCCACTATGGTAG 
protein? 
ATgCCAACATGgATGCCcGATAtGGATTgA 
protein? 
CCATt-AATgATCa-CAGTt 
protein? 
ATgAG-ATC-CgtgatGTGgg-aT-CCTa-CT-CATTaa 
protein? 
AtgC-CaacaTGGATGCCCTAAG-ATAtgGATTagtgA 
protein? 
atgataattagttttaatatcaga-ctgtaa 

이 루프가 형성입니다 당신이 어떤 생각을 가지고 있습니까 ? 그렇다면이 문제를 해결하는 방법에 대한 힌트를주세요.

감사합니다. 그냥 수정 된 몇 줄

+0

'lineScan'의 목적은 무엇입니까? – shmosel

+0

나는 이것을 사용하여 텍스트 파일의 개별 토큰을 읽어야한다고 생각합니다. –

+0

음 ... 당신 은요? – shmosel

답변

4

,

변경

1.))

2. Scanner lineScan = new Scanner(line);을 댓글 다음 반복, 루프, isProtein에 대한 값을 재설정해야합니다.

o/p은 텍스트 파일 hi.txt에 인쇄됩니다. BTW 나는 R/W 작업에 대한 텍스트 파일을 사용하여 스캐너 부분을 주석 처리했습니다.

코드

public static void Results() throws FileNotFoundException { 
     //System.out.print("Input file name? "); 
     Scanner input = new Scanner(new File("dna.txt")); 
     //System.out.print("Output file name: "); 
     File outputFile = new File("hi.txt"); 
     //System.out.println(); 

     PrintStream outputRead = new PrintStream(outputFile); 
     String isProtein = "NO"; 
     while (input.hasNextLine()) { 
      String line = input.nextLine().toUpperCase(); 
      //Scanner lineScan = new Scanner(line); 
      //while (lineScan.hasNext()) { 
       if (line.startsWith("ATG")) { 
        if (line.endsWith("TAA") || line.endsWith("TAG") || line.endsWith("TGA")) { 
         isProtein = "YES"; 
        } 
       }else{ 
         isProtein = "NO"; 
       } 
      //} 
      outputRead.println(isProtein); 
      isProtein = "NO"; 
     } 
     //System.out.println(isProtein); 
    } 

출력

NO 
YES 
NO 
YES 
NO 
NO 
NO 
YES 
NO 
YES 
NO 
YES 
+1

그냥 자세히,'isProtein = "NO"; 'else' 블록에 있어야합니다. 두 개의'if'를 병합하여 작동하게하면됩니다. 이것은 루프 당 인스턴스 수를 줄입니다. – AxelH

+0

@AxelH 네, 맞습니다. 더 최적화 할 수 있습니다. 코드를 수정했습니다. –

+0

고마워요! 내 반복 문제는 두 번째'while' 루프로 인해 발생 했습니까? –