我是 java 的菜鸟,我需要建议来修复此代码,我需要编写一个 Java 程序来显示三位数的百位、十位和个位的值。这是我到目前为止所拥有的,关于如何让它工作的任何想法?我没有收到任何错误,但我的号码甚至没有正确输出到控制台。就像我输入 123 作为我的 3 位数字一样,所有内容都打印为空白。例如:
输入3位数字:123 百位数字: 十位数字: 个位数字: 错误!号码超过 3 位数。错误!号码少于 3 位。
例如,它没有检测到我输入的“123”或我输入的任何其他内容。
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.");
}
}
原文由 Wilyum 发布,翻译遵循 CC BY-SA 4.0 许可协议
替换
System.out.printf("Hundreds place digit: " , hundreds);
if
System.out.println("Hundreds place digit: " + hundreds);
;
如果你想使用
printf
看看这个: https://docs.oracle.com/javase/7/docs/api/java/io/PrintStream.html#printf(java.lang.字符串,%20java.lang.Object…)