Java 使用indexOf读入文本文件的行以分隔数组
我想根据行是否包含问号,将文本文件的元素分成不同的数组。这是我能到的最远的地方Java 使用indexOf读入文本文件的行以分隔数组,java,indexof,Java,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(f
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());
}
Scanner inScan=新扫描仪(System.in);
字符串文件名;
System.out.print(“完整文件路径名是什么?\n>>”;
file_name=inScan.next();
Scanner fScan=新扫描仪(新文件(文件名));
ArrayList问题=新建ArrayList();
ArrayList Other=新的ArrayList();
而(fScan.hasNextLine())
{
if(fScan.nextLine.indexOf(“?”))
{
添加(fScan.nextLine());
}
添加(fScan.nextLine());
}
这里有很多问题
- nextLine()实际上返回下一行并在扫描仪上移动,因此您需要读取一次
- INTROXOF返回int,而不是布尔值,我猜你对C++更有用?您可以改为使用以下任一选项:
- indexOf(“?”>=0
- 包含(“?”)
- 匹配(\?)等
- 请遵循java方法并使用camelCase for VAR
indexOf返回一个整数,因此您似乎还没有编译代码。您面临的问题是什么?java在
if
语句中需要booleans
。使用<代码>匹配((\)”<代码>(这是正则表达式,但一个字符就足够了)。您也可以使用<代码> >索引(“?”)> -1 < /Cord>,是的,我通常用C++编码。面向对象编程正在降低我的效率。
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);
}
line without question mark
line with question mark?
another line