-1

I am writing a program where it takes a file and tries to use data from the file in order to create an output.

this is the program:

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);
}
}       


 }    
}  

and this is the error that prints out:

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)

I have no idea what i am doing wrong with the printf statement, and any help would be nice.

(This is a duplicate of Having trouble with program output an printf but i felt like this was a seperate quesion from what i was originally asking and no one was answering my question so i made a new post to have this question answered)

Community
  • 1
  • 1

1 Answers1

2

%f is used to print floats. Since a is an int, you should be using %d. E.g.:

int a = 75 * Integer.parseInt(words[2]);
System.out.printf(" " + words[0] + " " + words[1] + " $%d%n ", a);
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • how do i have the output rounded to 2 decimal places though? i tried $.2%d%n , $%d%.2n , $%.2d%n , etc, but it isnt printing as decimal rounded like $400.00 – user3479350 Apr 19 '14 at 17:36
  • Alternatively, you could print with `%f` like you did, but store `a` as a `float`. – Mureinik Apr 19 '14 at 17:39