I am a noob to java and I need advice to fix this code, I need to write a Java program to show the value of the hundreds place, the tens place, and the ones place for a three-digit number. This is what I have so far, any ideas to how to get it to work? I'm not getting any errors, but my number isn't even outputting to the console correctly. Like if I typed in 123 for my 3 digit number everything prints blank. For example:
Enter a 3 digit number: 123 Hundreds place digit: Tens place digit: Ones place digit: Error! Number more then 3 digits. Error! Number less then 3 digits.
It's not detecting my input of '123' for example, or anything else I put.
import java.util.Scanner;
public class ValueOfDigits {
public static void main(String[] args) {
//Create new scanner
Scanner input = new Scanner(System.in);
//Values of each digit
int hundreds = 0;
int tens = 0;
int ones = 0;
//Prompt user to input 3 digit number
System.out.print("Enter a 3 digit number: ");
int number = input.nextInt();
//Displays hundreds place digit
hundreds = number / 100;
System.out.printf("Hundreds place digit: " , hundreds);
//Displays tens digit
tens = (number - hundreds) / 10;
System.out.printf("\nTens place digit: " , tens);
//Display ones digit
ones = (number - tens - hundreds);
System.out.printf("\nOnes place digit: " , ones);
//Error if number is less or more then three digits
if (number > 999);
System.out.println("\nError! Number more then 3 digits.");
if (number < 100);
System.out.println("Error! Number less then 3 digits.");
}
}
Replace System.out.printf("Hundreds place digit: " , hundreds);
with System.out.println("Hundreds place digit: " + hundreds);
and remove the ;
after the if
-statments.
If you want to use printf
take a look at this: https://docs.oracle.com/javase/7/docs/api/java/io/PrintStream.html#printf(java.lang.String,%20java.lang.Object...)