我已经编写了一段代码,其中我扫描了一个整数(假设为 121)并将其分为 3 部分,我将其设为字符串并尝试通过拆分再次转换它。但我不明白?有什么简单的方法可以做到这一点吗?
public static void main(String []args){
Scanner scan = new Scanner(System.in);
int n = scan.nextInt() ;
int sum = 0;
for(int i = 1 ; i<=n; i++){
String s = Integer.toString(i);
int[] c = Integer.parseInt(s.split("")); //Here's the problem
int sm = 0 ;
for(int x :c){
sm +=x ;
}
System.out.print(sm+" ");
}
}
输入 = 12
预期输出:1 2 3 4 5 6 7 8 9 1 2 3
输出:Main.java:14:错误:不兼容的类型:String[] 不能 转换为字符串 int[] c = Integer.parseInt(s.split(""));
最佳答案
您的预期输出甚至似乎不需要任何整数到字符串的转换:
int n = scan.nextInt();
for (int i=0; i < n; i++) {
if (i > 0) System.out.print(" ");
System.out.print(1 + i % 9);
}
对于 n = 12
的输入,将打印:
1 2 3 4 5 6 7 8 9 1 2 3
关于java - 字符串到 int 数组的转换可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57503315/