0
我试图提示用户输入他们想要写入的文件的名称,创建该.txt文件,然后编写文本的限定行进入该文件并保存。在这段时间内,它似乎跳过了用户输入的文件名称,他们想要保存,循环回去,然后得到一个FileNotFoundException,它甚至不应该寻找一个文件。我在创建文件时遇到了FileNotFound异常
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) {
Scanner user = new Scanner(System.in);
Scanner docInName = null;
PrintWriter docOutName = null;
do {
System.out.println("Please enter the filename of the file you
would like to read from: ");
try {
docInName = new Scanner(new File(user.nextLine()));
} catch (FileNotFoundException e) {
System.out.println("File not found!");
}
} while (docInName == null);
int lineNum = docInName.nextInt();
BikePart[] bp = new BikePart[lineNum];
System.out.println("please enter the max cost for a part: ");
int cost = user.nextInt();
do {
System.out.println("please enter a name for the file to write to
(end with .txt): ");
String out = user.nextLine(); //PROBLEM HERE! SKIPS USER INPUT
try {
docOutName = new PrintWriter(out);
for (int i = 0; i < lineNum; i++) {
String line = docInName.nextLine();
String[] elements = line.split(",");
bp[i] = new BikePart(elements[0],
Integer.parseInt(elements[1]),
Double.parseDouble(elements[2]),
Double.parseDouble(elements[3]),
Boolean.parseBoolean(elements[4]));
double temp = Double.parseDouble(elements[3]);
if ((temp < cost && bp[i].isOnSale() == true)
|| (bp[i].getListPrice() < cost &&
bp[i].isOnSale() == false)) {
docOutName.write(line);
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
} while (docOutName == null);
user.close();
}
}
的可能的复制[扫描仪被使用next()之后跳过nextLine(),nextInt()或其它nextFoo()?(https://stackoverflow.com/questions/13102045/scanner-is-skipping -nextline-after-next-nextint-or-other-nextfoo) –
实际上恰恰相反,我需要在调用最大成本线后再跳过一行。正确的主意,谢谢! –