gpt4 book ai didi

java - FileInputStream 未读取第一个值

转载 作者:行者123 更新时间:2023-12-02 05:10:38 26 4
gpt4 key购买 nike

我需要读取的文件如下所示:

  • 30 15
  • 6 3
  • 12 20
  • 3 4

(没有要点)

inputStream 没有读取 30 和 15,但它正在读取所有其他的。

如何让 inputStream 读取第一行?

import java.io.*;
import java.util.*;

public class Program6 {
// private static Fraction [] fractionArray;
public static void main(String[] args) throws FileNotFoundException, IOException {
System.out.println("Please enter the name of the input file: ");


Scanner inputFile = new Scanner(System.in);
Scanner outputFile = new Scanner(System.in);

String inputFileName = inputFile.nextLine();
System.out.println("Please enter the name of the output file: ");
String outputFileName = outputFile.nextLine();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
FileWriter fileWriter = new FileWriter(outputFileName, true);
//Declaring an inputstream to get file
Scanner inputStream = new Scanner(new FileInputStream(inputFileName));


//while the file still has a line
while (inputStream.hasNextLine()) {
String theLine = inputStream.nextLine();
if (theLine.length() >= 0) {
//declares a numerator and denominator from the file
int num = inputStream.nextInt();
int denom = inputStream.nextInt();
//new fraction from file
Fraction fract = new Fraction(num, denom);
fract.reduce();
System.out.println(fract);
fileWriter.write("" + fract + "\r\n");
}
}

//closes streams and flushes the file writer
fileWriter.flush();
fileWriter.close();
inputStream.close();
}
}

最佳答案

这里的问题是Scanner.nextLine()消耗来自 InputStream 的输入行。然后,使用 Scanner.nextInt()返回从同一个输入流消耗 - 它不从 nextLine() 返回的值消耗.

因此,请使用其中之一。

如果使用 nextLine()方法,则需要解析包含该行的字符串以提取值。使用scanner.nextInt() ,文件中的整数值立即可用。唯一的损失是,您将失去关于值是在同一行还是不同行的知识。

关于java - FileInputStream 未读取第一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27371191/

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