2012-11-02 39 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'语句中需要'booleans'。使用'.matches(“\?”)'(这是一个正则表达式,但是一个字符就足够了,你也可以使用'.indexOf('?')> -1' – durron597

回答

2

不少有)问题

  • nextLine(实际上返回扫描仪上的下一行,移机,所以你需要读一次,而
  • 的indexOf返回一个int,不一个布尔值,我猜你更喜欢C++吗?您可以使用任何的下列代替:( “?”)
    • 的indexOf> = 0
    • 包含( “?”)
    • 比赛( “\?”)等
  • 请遵循Java方法和使用驼峰的瓦尔...

代码

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++进行编码。面向对象编程降低了我的沟槽 –

相关问题