Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 4 of 4

Thread: printf error

  1. #1
    Junior Member
    Join Date
    Oct 2012
    Posts
    14
    My Mood
    Fine
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default printf error

    Hello again, I finished my code and it works fine (it's far from elegant), but when I tried to format the printing of a few values, I started getting errors.

    Here is the code (errors occur after the loop):
    Scanner in = new Scanner (System.in);
     
    			int w = 0;
    			int d = 0;
    			int p = 0;
    			double total = 0;
    			double overall = 0;
    			int n = 0;
    			double max = 0;
    			double min = 0;
    			String maxTroop = "";
    			String minTroop = "";
     
    			System.out.println("Cookie Sales Report for Young Scouts of America");
    			System.out.println("Enter the troop name (or exit to quit): ");
     
    			String t = in.nextLine();
     
    			while (!t.equals("exit"))
    				{
    				System.out.println("Enter number of boxes of Chocolate Mint Wafers: ");
    				w = in.nextInt();
    				in.nextLine();
    				System.out.println("Enter number of boxes of Peanut Delights: ");
    				d = in.nextInt();
    				in.nextLine();
    				System.out.println("Enter number of boxes of Coconut Plops: ");
    				p = in.nextInt();
    				in.nextLine();
    				total = w*3+d*3.5+p*2.25;
    				System.out.printf("The total collected by Troop " + t + " is $%7.2f\n", total);
    				overall += total;
    				n++;
    				if (1 == n)
    				{
    					max = total;
    					min = total;
    					maxTroop = t;
    					minTroop = t;
    				}
    				else if (total > max)
    				{
    					max = total;
    					maxTroop = t;
    				}
    				else if (total < min)
    				{
    					min = total;
    					minTroop = t;
    				}
    				System.out.println("Enter the troop name (or exit to quit): ");
    				t = in.nextLine();
    				}
    			double avg = overall/n;
    			System.out.printf("The total collected overall is $%7.2f\n", overall + ".");
    			if (n > 0)
    			{
    			System.out.printf("The average collected per troop is $%7.2f\n", avg);
    			System.out.printf("The minimum was collected by Troop " + minTroop + " and is $%7.2f\n", min + ".");
    			System.out.printf("The maximum was collected by Troop " + maxTroop + " and is $%7.2f\n", max + ".");
    			}
    		}

    I get this error message:
    The total collected overall is $Exception in thread "main" java.util.IllegalFormatConversionException: f != java.lang.String
    	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 tjf1218_lab5.Scouts.main(Scouts.java:66)

    Why is this happening? Does it have something to do with the variable declarations earlier in the program?

    Any help would be greatly appreciated. Thanks!


  2. #2
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: printf error

    Quote Originally Posted by Thor View Post
    ...
    Why is this happening? ...
    When you have an expression that adds a numerical variable to a String, Java converts the number to a String and concatenates it with the other String. It decides how to format the number in a generic manner.

    The compiler is complaining that the stuff it sees after the comma is a String, but the format specifies %f.

    Bottom line: If you want to print a number with formatting, and you want to put a '.' character after the number, put the '.' inside the formatting string.

    The safest way is to keep the formatting string all together and put the comma-separated list of variables after the format.

    If n is an int or a long, and mean is a float or a double, it goes like this:
    System.out.printf("There are %d numbers and their average is %7.2f.\n", n, mean);

    Java takes the "%" things inside the format String and applies them to the variables in the same order.


    Cheers!

    Z
    Last edited by Zaphod_b; October 9th, 2012 at 11:28 PM.

  3. #3
    Super Moderator pbrockway2's Avatar
    Join Date
    Jan 2012
    Posts
    987
    Thanks
    6
    Thanked 206 Times in 182 Posts

    Default Re: printf error

    System.out.printf("The total collected overall is $%7.2f\n", overall + ".");

    I'm guessing line 66 of Scouts.java is this one. (It's a good idea to say)

    What the runtime message is saying is that the format for what is printed includes %7.2f but the next argument (overall+".") is a string. The format specifier - in his case f for floating point value - must match the argument type.

    There are two ways to go. You could change the format string so that it uses s (for string) instead of f. But the other way is better: put the dot inside the format string the same as you do for the dollar sign.

    System.out.printf("The total collected overall is $%7.2f.\n", overall);

    Now the f will agree with the type of overall which is a double.

    In general I think it looks neater to put as much of the text as possible into the format string and have the rest of the arguments just expressions to be evaluated (including variables which are simple expressions).

    //System.out.printf("The minimum was collected by Troop " + minTroop + " and is $%7.2f\n", min + ".");
    System.out.printf("The minimum was collected by Troop %s and is $%7.2f.%n", minTroop, min);

    Notice how s (for string) and f (for floating point) match the following arguments (string then double). And how the text is all gathered together in the format string and what follows are variables to be substituted. printf() calls can become long and I would format this as

    System.out.printf(
            "The minimum was collected by Troop %s and is $%7.2f.%n", 
            minTroop, min);

    Typically twice the normal indentation is used when breaking long lines.

    Consult the API documentation for these format strings. But don't be overwhelmed by it. Just figure out what you want to use and remember the location so that you can look up what you want when you want it. The same (or similar) syntax is used in a number of languages so it isn't wasted effort to become familiar with it.
    Last edited by pbrockway2; October 9th, 2012 at 11:43 PM. Reason: slow ;( Two heads might be better, but I wouldn't have though they'd necessarily be faster...

  4. #4
    Junior Member
    Join Date
    Oct 2012
    Posts
    14
    My Mood
    Fine
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: printf error

    Thanks a lot! That makes too much sense for me to have thought of it haha

Similar Threads

  1. Please! Help me to this error "ERROR CANNOT FIND SYMBOL"
    By mharck in forum Object Oriented Programming
    Replies: 8
    Last Post: July 3rd, 2012, 09:20 AM
  2. [SOLVED] Setting field width System.out.printf
    By ranjithfs1 in forum Java Theory & Questions
    Replies: 3
    Last Post: March 18th, 2012, 01:55 PM
  3. How to align text? Printf?
    By shifat96 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: February 20th, 2012, 12:51 PM
  4. about printf please help having errors
    By Macgrubber in forum What's Wrong With My Code?
    Replies: 2
    Last Post: November 15th, 2010, 11:01 PM
  5. The printf() method explanation needed
    By darek9576 in forum Object Oriented Programming
    Replies: 1
    Last Post: March 14th, 2010, 12:11 AM