gpt4 book ai didi

java - 文件扫描-nextLine方法

转载 作者:行者123 更新时间:2023-11-30 06:46:13 25 4
gpt4 key购买 nike

我的程序的一部分有问题。我想要从文件中写信。该文件包含一些字母和数字,每个字母和数字都位于单独的行中。 (我只需要“P”、“O”和“W”字母)我不明白为什么程序不输出这些字母。下面的代码和文件图像。

http://i.imgur.com/sdyGkCn.jpg

File file = new File("file.txt");
Scanner in;
try {
in = new Scanner(file);

while (in.hasNextLine())
{
if(in.nextLine() == "W" || in.nextLine() == "O" || in.nextLine() == "P")
{
System.out.println(in.nextLine());
}
}


in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}

最佳答案

您的代码跳过检查某些行。每次调用 in.nextLine() 时,它都会读取第二行。

试试这个方法

File file = new File("file.txt");
Scanner in;
try {
in = new Scanner(file);

while (in.hasNextLine())
{
String MyLine = in.nextLine();
if(MyLine.equals( "W") || MyLine.equals( "O") || MyLine.equals( "P"))
{
System.out.println(MyLine);
}
}


in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}

关于java - 文件扫描-nextLine方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43653230/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com