2012-11-02 3 views
1

줄에 물음표가 있는지 여부에 따라 텍스트 파일의 요소를 다른 배열로 나누고 싶습니다. 내가 가진 한 여기있다. 이indexOf를 사용하여 배열을 분리하기 위해 텍스트 파일의 행을 읽습니다.

Scanner inScan = new Scanner(System.in); 

    String file_name; 
    System.out.print("What is the full file path name?\n>>"); 
    file_name = inScan.next(); 

    Scanner fScan = new Scanner(new File(file_name)); 
    ArrayList<String> Questions = new ArrayList(); 
    ArrayList<String> Other = new ArrayList(); 

    while (fScan.hasNextLine()) 
    { 
     if(fScan.nextLine.indexOf("?")) 
     { 
      Questions.add(fScan.nextLine()); 
     } 

     Other.add(fScan.nextLine()); 
    } 
+1

indexOf는 정수를 반환하므로 코드를 컴파일하지 않은 것처럼 보입니다. 당신이 겪고있는 문제는 무엇입니까? – Vikdor

+0

java는'if' 문에서'boolean '을 요구합니다. '.matches ("\?")'를 사용하십시오 (정규 표현식이지만 한 문자만으로 충분합니다.)'.indexOf ('?')> -1' – durron597

답변

2

꽤 몇 가지 문제

  • 꽵()는 실제로 스캐너의 다음의 행 및 이동을 반환, 그래서 당신은 한 번 대신
  • 같이 IndexOf는 int를 반환하지 읽을해야합니다 부울, 당신이 C++에 더 익숙하다고 생각합니까? 대신 다음 중 하나를 사용할 수 있습니다 ("?")
    • 같이 IndexOf를> = 0
    • 포함 ("?")
    • 일치 ("\?") 등
  • 하십시오

코드 ... 자바 방법과 바르에 대한 사용 낙타 표기법에 따라

public static void main(String[] args) throws FileNotFoundException { 

    Scanner scanner = new Scanner(new File("foo.txt")); 
    List<String> questions = new ArrayList<String>(); 
    List<String> other = new ArrayList<String>(); 
    while (scanner.hasNextLine()) { 
     String line = scanner.nextLine(); 
     if (line.contains("?")) { 
      questions.add(line); 
     } else { 
      other.add(line); 
     } 
    } 
    System.out.println(questions); 
    System.out.println(other); 
} 

foo.txt

line without question mark 
line with question mark? 
another line 
+0

당신은 신사이고 학자입니다. –

+0

그리고 네, 저는 보통 C++로 코딩하고 있습니다. 객체 지향 프로그래밍은 내 홈을 무너 뜨 렸습니다. –

관련 문제