gpt4 book ai didi

java - 如何获取从 1 开始到 n 结束的 String ?

转载 作者:行者123 更新时间:2023-12-01 06:37:38 26 4
gpt4 key购买 nike

如何做到这一点,当用户 inputs n=4那么它应该生成一个像 str="1234" 这样的字符串?

最佳答案

您可以使用一个简单的循环,例如:

int n = 4;
String str = "";
for (int i = 1; i <= n; i++) {
str+=i;
}
<小时/>

can we directly get int= 1234

在这种情况下,您可以像这样解析它:

int result = Integer.parseInt(str);
<小时/>

如果你想避免这种情况并从请求中获取 int ,你可以使用:

int n = 4;
int result = 0;
for (int i = 1; i <= n; i++) {
result *= 10;
result += i;
}

关于java - 如何获取从 1 开始到 n 结束的 String ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43693690/

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