我需要阅读的文件如下所示:
(没有要点)
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();
}
}
答案 0 :(得分:2)
这里的问题是Scanner.nextLine()
消耗InputStream的输入行。然后,使用Scanner.nextInt()
返回使用相同的InputStream - 它不会消耗nextLine()
返回的值。
所以,请使用其中一个。
如果使用nextLine()
方法,则需要解析包含该行的String以提取值。使用scanner.nextInt()
,文件中的整数值立即可用。唯一的损失是你不知道价值是在同一条线上还是在不同的线上。