2014-11-29 2 views
1

파일의 내용을 읽고 각 줄을 역순으로 인쇄해야하는 Java 프로그램에서 작업하고 있습니다. 예를 들어 텍스트 :ArrayList Java의 역방향 코드

Public Class Helloprinter 
Public static void 

내 역 프로그램을 실행 한 후 다음을 인쇄 할 것이다 : 여기

retnirPolleh ssalc cilbup 
diov citats cilbup 

는 내가 지금까지 가지고있는 작업은 다음과 같습니다

public static void main(String[] args) throws FileNotFoundException { 
    // Prompt for the input and output file names 
     ArrayList<String> list = new ArrayList<String>(); 
     //String reverse = ""; 
     Scanner console = new Scanner(System.in); 
     System.out.print("Input file: "); 
     String inputFileName = console.next(); 
     System.out.print("Output file: "); 
     String outputFileName = console.next(); 


     // Construct the Scanner and PrintWriter objects for reading and writing 

     File inputFile = new File(inputFileName); 
     Scanner in = new Scanner(inputFile); 
     PrintWriter out = new PrintWriter(outputFileName); 
     String aString = ""; 

     while(in.hasNextLine()) 
     {   
      String line = in.nextLine(); 
      list.add(line);  
     } 

     in.close(); 

     for(int i = 0; i <list.size(); i++) 
     { 
      aString = list.get(i); 
      aString = new StringBuffer(aString).reverse().toString(); 
      out.printf("%s", " " + aString); 
     } 

     out.close(); 

} 

} 편집 :

로버트의 글을 게시하면 나를 올바른 방향으로 인도 할 수있었습니다. 문제는 그것이 라인을 유지하지 않는다는 것입니다.

Public Class Helloprinter 
Public static void 

내 프로그램을 실행 한 후이된다 :

retnirPolleh ssalc cilbup diov citats cilbup 

는 동일한 라인 레이아웃을 유지해야합니다. 따라서 다음과 같아야합니다 :

retnirPolleh ssalc cilbup 
diov citats cilbup 
+0

당신이지고 어떤 출력? –

+3

당신은 아마 우리에게 일하지 않는 것을 말해야 할 것입니다. – luuksen

+0

무엇이 당신의 질문입니까? – fishinear

답변

0

귀하의 문제는 라인

 out.printf("%s", " " + aString); 

이 출력되지 않습니다 줄 바꿈에 있습니다. 나는 왜 거기에 공간을두고 있는지도 확신하지 못합니다.

그것은해야 하나 :

 out.println(aString); 

또는

 out.printf("%s%n", aString); 
+0

새 행을 추가하는 % n을 알지 못했습니다. 그 점을 지적 해 주셔서 감사합니다. 나는 다음 번에 그것을 염두에두고 그것을 필요로 할 것이다! –

0

마지막 루프에서 목록을 거꾸로 반복하지 마십시오. 그래서 :

for(int i = 0; i <list.size(); i++) 

가된다 :

for(int i = list.size() - 1; i >=0; i--) 
+0

문제를 말하지 않는 것이 나쁘다! 당신의 생각은 올바른 방향으로 나를 몰아 넣었지만 여전히 100 % 정확하지는 않습니다. –

0

그냥 문자열 빌더를 사용합니다. 너는 옳은 길을 걷고 있었다. 아마도 약간의 도움이 필요할 것입니다. 이 아무것도 할 "방법은 하나"입니다,하지만 당신은 같은 것을 시도 할 수 :

참고 : 여기 내 출력은 다음과 같습니다 retnirPolleh이 ssalc cilbup diov citats cilbup

import java.io.BufferedReader; 
import java.io.BufferedWriter; 
import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.FileReader; 
import java.io.IOException; 
import java.io.OutputStreamWriter; 
import java.io.Writer; 
import java.util.ArrayList; 
import java.util.Scanner; 

public class Reverse { 

    public static void main(String[] args) { 
     ArrayList<String> myReverseList = null; 
     System.out.println("Input file: \n"); 
     Scanner input = new Scanner(System.in); 
     String fileName = input.nextLine(); 
     System.out.println("Output file: \n"); 
     String outputFileName = input.nextLine(); 
     BufferedReader br = null; 
     try { 
      br = new BufferedReader(new FileReader(fileName)); 
      String text = null; 
      myReverseList = new ArrayList<String>(); 
      StringBuilder sb = null; 
      try { 
       while ((text = br.readLine()) != null) { 
        sb = new StringBuilder(); 
        for (int i = text.length() - 1; i >= 0; i--) { 
         sb.append(text.charAt(i)); 
        } 
        myReverseList.add(sb.toString()); 
       } 

      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
     } catch (FileNotFoundException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     Writer writer = null; 
     try { 
      writer = new BufferedWriter(new OutputStreamWriter(
       new FileOutputStream(outputFileName), "utf-8")); 
      for (String s : myReverseList) { 
       writer.write("" + s + "\n"); 
      } 

     } catch (IOException ex) { 
      // report 
     } finally { 
      try { 
       writer.close(); 
      } catch (Exception ex) { 
      } 
     } 

    } 

} 
0

그것은 이미 것 같아 파일을 읽는 법을 알고 있다면, 각 행에 대해이 메소드를 호출하십시오. 참고로 이것은 재귀이며 가장 효율적은 아니지만 간단하고 원하는대로 처리합니다.

public String reverseString(final String s) { 
     if (s.length() == 0) 
      return s; 
     // move chahctrachter at current position and then put it at the end of the string. 
     return reverseString(s.substring(1)) + s.charAt(0); 
    }