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