Java 将int转换为数组而不将其转换为字符串
我正在用Java编程,想把一个int转换成一个数组。例如,我想把122转换成{1,2,2}。你知道这是怎么回事吗?提前谢谢。不允许将其转换为字符串。以下示例使用纯算术方法(不将数字转换为字符串):Java 将int转换为数组而不将其转换为字符串,java,arrays,int,Java,Arrays,Int,我正在用Java编程,想把一个int转换成一个数组。例如,我想把122转换成{1,2,2}。你知道这是怎么回事吗?提前谢谢。不允许将其转换为字符串。以下示例使用纯算术方法(不将数字转换为字符串): int number=122; List digitList=新链接列表(); 而(数量>0){ int d=数字%10;//获取最后一位 添加(0,d); number=number/10;//省略最后一位 } 整数[]位=数字列表.toArray(新整数[0]); System.out.print
int number=122;
List digitList=新链接列表();
而(数量>0){
int d=数字%10;//获取最后一位
添加(0,d);
number=number/10;//省略最后一位
}
整数[]位=数字列表.toArray(新整数[0]);
System.out.println(数组.toString(数字));
以下是不使用数学
课堂的答案
import java.util.Arrays;
class int_to_array
{
public static void main(String arg[])
{
int number = 122;
int length=0;
int org=number;
while(org!=0)
{
org=org/10;
length++;
}
int[] array = new int[length];
for(int i = 0; i < length; i++) {
int rem = number % 10;
array[length - i - 1] = rem;
number = number / 10;
}
System.out.println(Arrays.toString(array));
}
}
导入java.util.array;
类int_to_数组
{
公共静态void main(字符串arg[])
{
整数=122;
整数长度=0;
int org=编号;
而(组织!=0)
{
org=org/10;
长度++;
}
int[]数组=新的int[length];
for(int i=0;i
这将以一个无休止的循环结束-为什么
int input = readInt("Bitte geben Sie eine positive Zahl ein:");
while(input < 0) {
input = readInt("Bitte geben Sie eine positive Zahl ein:");
}
int number = input;
int length = 0;
int org = number;
while(org != 0) {
org = org / 10;
length++;
}
int[] inputArray = new int[length];
int i = 0;
while(i < inputArray.length) {
int rem = number % 10;
inputArray[length - i - 1] = rem;
number = number / 10;
i++;
}
String output = "{";
i = 0;
while(i < inputArray.length) {
output += inputArray[i];
if(i < inputArray.length-1) {
output += ", ";
}
i++;
}
output += "}";
System.out.print(output);
int-input=readInt(“bite-geben-Sie-eine-positive-Zahl-ein:”);
while(输入<0){
输入=readInt(“bite-geben-Sie-eine-positive-Zahl-ein:”);
}
整数=输入;
整数长度=0;
int org=编号;
而(组织!=0){
org=org/10;
长度++;
}
int[]inputArray=新的int[长度];
int i=0;
while(i
谢谢,但我不允许使用数学。函数-没有它我怎么做?将for循环重构为一个递归函数,如果基于10的索引大于数字,它将跳过。如果你不能使用数学,你应该找到一种获取值的位数的方法。您可以实现自己的log10,也可以执行类似于';长度=0;i=值;虽然(i:100.9){i=i/10;length++;}'@Z.Wo我更新了代码,但没有使用数学和数字的长度。@udiboy1209没有。没有可能使用string谢谢!我将实现你的想法并对其进行测试。当我实现这个想法时,它似乎以一个无休止的循环结束:我已经编辑了你的代码,现在检查它。这是完美的!!!!伟大的非常感谢你!!!!请将答案标记为已接受
int input = readInt("Bitte geben Sie eine positive Zahl ein:");
while(input < 0) {
input = readInt("Bitte geben Sie eine positive Zahl ein:");
}
int number = input;
int length = 0;
int org = number;
while(org != 0) {
org = org / 10;
length++;
}
int[] inputArray = new int[length];
int i = 0;
while(i < inputArray.length) {
int rem = number % 10;
inputArray[length - i - 1] = rem;
number = number / 10;
i++;
}
String output = "{";
i = 0;
while(i < inputArray.length) {
output += inputArray[i];
if(i < inputArray.length-1) {
output += ", ";
}
i++;
}
output += "}";
System.out.print(output);