Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java UnknownFormatConversionException

Tags:

java

debugging

The code below throws this error, and I'm not sure why. There is clearly a problem with outputting String.format to the str variable, but I don't know what's wrong with it.

Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = 'i'
    at java.util.Formatter$FormatSpecifier.conversion(Unknown Source)
    at java.util.Formatter$FormatSpecifier.<init>(Unknown Source)
    at java.util.Formatter.parse(Unknown Source)
    at java.util.Formatter.format(Unknown Source)
    at java.util.Formatter.format(Unknown Source)
    at java.lang.String.format(Unknown Source)
    at Donor.toString(Donor.java:41)
    at Donor.main(Donor.java:65)

-

import java.util.Scanner;

public class Donor {

    public String name;
    public int age;
    public double donation;

    Donor() {

        //Initialized to these values for debugging
        name = "NoName";
        age = 0;
        donation = 0;

    }

    Donor(String nameinit, int ageinit, double donationinit) {

        name = nameinit;
        age = ageinit;
        donation = donationinit;

    }

    public String toString() {

        String str = "";

        str = String.format("%s-30%i-6$%d-20", name, age, donation);

        return str;

    }

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        String nameinit = null;
        int ageinit = -1;
        double donationinit = -1;
        String outp = null;

        System.out.print("Enter the donor's name: ");
        nameinit = input.nextLine();

        System.out.print("Enter the donor's age: ");
        ageinit = input.nextInt();

        System.out.print("Enter the donation amount: ");
        donationinit = input.nextDouble();

        Donor d = new Donor(nameinit, ageinit, donationinit);
        outp = d.toString();

        System.out.printf("%s30 %s6 %s10", "Name", "Age", "Donation");
        System.out.print("\n" + outp);

        input.close();

    }

}
like image 623
vaindil Avatar asked Sep 15 '12 21:09

vaindil


1 Answers

Use d for int instead of i and ffor double instead of d in the following line

str = String.format("%s-30%i-6$%d-20", name, age, donation); 

You can read about formatting syntax here http://docs.oracle.com/javase/6/docs/api/java/util/Formatter.html.

like image 137
Bhesh Gurung Avatar answered Nov 11 '22 23:11

Bhesh Gurung