我有一个问题,要求我告诉给定数字中的位数。我插入条件语句,但无论我插入什么数字,它都给我“九”数字。代码如下。我是一名数学学生,而不是计算机科学,所以我认为我没有使用最有效的方法。
import java.util.Scanner;
public class E52 {
public static void main(String[] args) {
// part 1: import scanner
Scanner sc = new Scanner(System.in);
// part 2: ask user for a number
System.out.println("Please enter a number: ");
int number = sc.nextInt();
// part 3: tell how many digits are in each number by using string and conditional statements
String number1Str;
if (number >= 0 || number <= 10) number1Str = "one";
if (number >= 10 || number <= 100) number1Str = "two";
if (number >= 100 || number <= 1000) number1Str= "three";
if (number >= 1000 || number <= 10000) number1Str = "four";
if (number >= 10000 || number <= 100000) number1Str = "five";
if (number >= 100000 || number <= 1000000) number1Str = "six";
if (number >= 1000000 || number <= 10000000) number1Str = "seven";
if (number >= 10000000 || number <= 100000000) number1Str = "eight";
if (number >= 100000000 || number <= 1000000000) number1Str = "nine";
else number1Str = "undefined";
System.out.println("There are " + number1Str + " digits in the given number.");
sc.close();
}
}
答案 0 :(得分:1)
创建一个数组会更容易,然后获取输入的长度并选择让它选择条目:
Scanner sc = new Scanner(System.in);
// part 2: ask user for a number
System.out.println("Please enter a number: ");
Integer number = sc.nextInt();
final String[] numNames = {
"",
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine",
"ten",
"eleven",
"twelve",
"thirteen",
"fourteen",
"fifteen",
"sixteen",
"seventeen",
"eighteen",
"nineteen"
};
System.out.println(numNames[number.toString().length()]);
答案 1 :(得分:0)
无论大小有多少,这都会给你数字计数。虽然有角落的情况可能会使代码失败,但我仍然认为这会以其他方式对你有用
public class CountNum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String numAsString = sc.nextLine();
System.out.println(numAsString.length());
sc.close();
}
}