gpt4 book ai didi

java - 代码位数

转载 作者:行者123 更新时间:2023-11-30 06:31:03 25 4
gpt4 key购买 nike

我在要求我说出给定数字中的位数时遇到问题。我插入了条件语句,但无论我插入什么数字,它都会给我“九”位数字。代码如下。我是一名数学学生,而不是计算机科学专业的学生,​​所以我认为我没有使用最有效的方法。

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

最佳答案

创建一个数组,然后获取输入的长度并选择让它选择条目会容易得多:

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()]);

关于java - 代码位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46121391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com