Exception in thread “main” java.util.IllegalFormatConversionException: d != java.lang.String

后端 未结 3 1539
深忆病人
深忆病人 2020-11-28 00:15

I\'m new to Java and I\'m not sure how to fix the error I\'m getting when trying to run this code:

import java.util.Scanner;
public class P3_3 
{

    publi         


        
相关标签:
3条回答
  • 2020-11-28 00:39

    Change your last printf to:

    System.out.printf("number has %d digits ", number);
    

    Try to append all the string together and use specifier i.e.

    System.out.printf("blah %d blah ", value).
    
    0 讨论(0)
  • 2020-11-28 00:45

    The problem is here:

    System.out.printf("%d has ", number + "digits.");
    

    the %d format specifier requires an integer to be passed as second parameter to printf, but by concatenating number and "digits.", you actually passed a String.

    Fixed version:

    System.out.printf("has %d digits ", number);
    

    note that you cannot print both the original number and the number of digits, because you overwrote one with the other in the number variable. Maybe use two different ones.

    0 讨论(0)
  • 2020-11-28 00:46

    Like others have said, the issue was in the print statement. A better approach, instead of using all the if statements you should use the log10 method:

    public static void main(String[] args){
            Scanner in = new Scanner(System.in);
            System.out.print("Please enter a number: ");
            int number = in.nextInt();
            if (number < 0) number *= -1;
            System.out.printf("%d has %d digits\n", number, (int)Math.log10(number) + 1 );
    }
    
    0 讨论(0)
提交回复
热议问题