我正在编写一个程序,它接受一个文件,并尝试使用该文件中的数据来创建输出。
这是该计划:
import java.util.Scanner;
import java.io.*;
public class WebberProjectTest
{
public static void main(String[] args) throws IOException
{
Scanner scanner = new Scanner(new File("portlandvip.txt"));
while(scanner.hasNext())
{
String line = scanner.nextLine();
String[] words = line.split(" ");
if(words[3].equals("Court"))
{
int a = 75 * Integer.parseInt(words[2]);
System.out.printf(" " + words[0] + " " + words[1] + " $%.2f\n ", a);
}
if(words[3].equals("Box"))
{
int a = 50 * Integer.parseInt(words[2]);
System.out.printf(" " + words[0] + " " + words[1] + " $%.2f\n", a);
}
if(words[3].equals("Club"))
{
int a = 40 * Integer.parseInt(words[2]);
System.out.printf(" " + words[0] + " " + words[1] + " $%.2f\n", a);
}
}
}
}
这是打印出来的错误:
Loras Tyrell Loras Tyrell $java.util.IllegalFormatConversionException: f != java.lang.Integer
at java.util.Formatter$FormatSpecifier.failConversion(Unknown Source)
at java.util.Formatter$FormatSpecifier.printFloat(Unknown Source)
at java.util.Formatter$FormatSpecifier.print(Unknown Source)
at java.util.Formatter.format(Unknown Source)
at java.io.PrintStream.format(Unknown Source)
at java.io.PrintStream.printf(Unknown Source)
at WebberProjectTest.main(WebberProjectTest.java:32)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
我不知道我对printf语句做错了什么,任何帮助都会很好。
(这是Having trouble with program output an printf的副本,但我觉得这是我原来问的一个单独的问题,没有人回答我的问题所以我发了一个新的帖子来回答这个问题)
答案 0 :(得分:2)
%f
用于打印float
。由于a
是int
,因此您应该使用%d
。 E.g:
int a = 75 * Integer.parseInt(words[2]);
System.out.printf(" " + words[0] + " " + words[1] + " $%d%n ", a);