Click here to Skip to main content
15,922,015 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Im tyring to write a program that computes the sum of all the odd digits in a number with java. FOr some reason im getting a format conversion error:



at the line:
System.out.printf("Sum of %s's odd digits: %f", number, odd_digits_sum);   



Sum of Exception in thread "main" 0's odd digits: 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 practicebook.sum1.main(sum1.java:86)




import java.util.Scanner;

public class sum1 {

	
	 public static void main(String[] args) {
		 
		 Scanner input = new Scanner(System.in);
		 
		
			System.out.print("Number: ");
			int number = input.nextInt();
			input.close();
			int odd_digits_sum = 0;
			while (number > 0) {
			    int digit = number % 10;
			    if (digit % 2 != 0) {
				odd_digits_sum += digit;
			    }
			    number /= 10;
			}
			System.out.printf("Sum of %s's odd digits: %f", number, odd_digits_sum);   
			
			//System.out.printf("number is " + number);
			
			
			
		    }
	
	
}
//end main}
// end class


What I have tried:

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Posted
Updated 13-Feb-17 12:01pm
Comments
PIEBALDconsult 13-Feb-17 19:31pm    
Which base?

1 solution

Quote:
Sum of Exception in thread "main" 0's odd digits: java.util.IllegalFormatConversionException: f != java.lang.Integer

Java complain because odd_digits_sum is an integer and %f expect something else.
One can guess that if you look at documentation of printf, you will find how it works.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900