Java 文件输入和输出方法问题
所以我的程序应该从我的输入文件中说出它是什么类型的令牌。我的第二个方法是将键盘上的任何输入写入输出文件,直到用户停止键入。问题是我的第一个方法不会将整数输出到正确的类型。我的第二个方法将只在输出文件中停止。这是我的密码。任何帮助都是非常感激的Java 文件输入和输出方法问题,java,Java,所以我的程序应该从我的输入文件中说出它是什么类型的令牌。我的第二个方法是将键盘上的任何输入写入输出文件,直到用户停止键入。问题是我的第一个方法不会将整数输出到正确的类型。我的第二个方法将只在输出文件中停止。这是我的密码。任何帮助都是非常感激的 public class R16 { public void readFile(String inputFile) { try { File in = new File(inputFile); Scanner sc
public class R16 {
public void readFile(String inputFile) {
try {
File in = new File(inputFile);
Scanner scan = new Scanner(in);
while (scan.hasNext()) {
if (scan.hasNextInt()) {
System.out.println("Integer: " + scan.nextInt());
}
if (scan.hasNext()) {
System.out.println("String: " + scan.next());
}
if (scan.hasNextDouble()) {
System.out.println("Double: " + scan.nextDouble());
}
}
scan.close();
} catch (IOException e) {
System.out.println("Error, not good");
}
}
public void writeFile(String outputFile) {
try {
File out = new File(outputFile);
PrintWriter w = new PrintWriter(out);
Scanner scan= new Scanner(System.in);
System.out.print("Enter Text: ");
while(!scan.next().equals("stop")){
w.print(scan.next());
}
w.close();
scan.close();
} catch (IOException e) {
System.out.println("Error, it just got real");
}
}
public static void main(String[] args) {
R16 test = new R16();
test.readFile(args[0]);
test.writeFile(args[1]);
}
}在循环中,检查
停止
,然后丢弃所有输入
while(!scan.next().equals("stop")){
试着使用类似于
String input;
while (!(input = scan.next()).equals("stop")) {
w.print(input);
现在在循环中,您可以访问包含输入字符串的输入变量。也许您应该将后两个
if
语句转换为else if
语句,也许您应该在hasNextDouble()之前选中hasNextDouble()
。实际上,这将使hasNext()
成为最后一个,并且是多余的,因为您已经在while
循环中检查了它,所以一个简单的else
就足够了。谢谢。next()
不会返回“行”。Meh,行,输入。够近了。