java - 将字符串值添加到数组索引时出错
问题描述
public class aa {
public static void main(String[] args) {
int number = 521;
String temp1 = "" + number;
int result = 0;
int[] temp2 = new int[temp1.length()];
for(int i=0; i<temp1.length(); i++){
int len = temp1.length();
temp2[i] = temp1.charAt(len-i-1);
System.out.println(temp2[i]);
System.out.println(temp1.charAt(len-i-1));
}
}
}
这个程序应该使 521 到 125(反向)。但是当我运行这个程序时,结果是
49
1
50
2
53
5
我认为字符串值是正确的,但是当我将该字符串值添加到数组时,它会出错。有人可以告诉我出了什么问题吗?
解决方案
正如我在评论中所说,temp2
是错误的类型。您将其声明为int
s 的数组,因此 sprintln
当然是将其视为数字数组,而不是可打印字符的数组。
只需将temp2
类型更改为char[]
:
public class aa {
public static void main(String[] args) {
int number = 521;
String temp1 = "" + number;
int result = 0;
char[] temp2 = new char[temp1.length()];
for(int i=0; i<temp1.length(); i++){
int len = temp1.length();
temp2[i] = temp1.charAt(len-i-1);
System.out.println(temp2[i]);
System.out.println(temp1.charAt(len-i-1));
}
// print the whole reversed number on one line
for(char c : temp2) {
System.out.print(c);
}
System.out.println();
}
}
输出
1
1
2
2
5
5
125
当然,这不是最佳解决方案,只是一种修复您编写的代码以使其正常工作的方法。请参阅Alex Rudenko 的评论,以获取有关反转数字数字问题的更好解决方案的链接。
推荐阅读
- laravel - Laravel 上一页内容加载问题
- android - 简单循环执行时间的巨大差异:怎么会?
- android - ArCore 增强图像图像不可见
- javascript - 使用 JavaScript 将每个数组元素的首字母大写
- vaadin - Vaadin 10+:tomcat 必须扫描哪些罐子?
- java - 当我在 CardStackView 中的最后一项时?
- reactjs - 异步等待 Firestore 用户 ID
- java - 无法访问 JavaFX GridPane setRow 或 setCol 方法
- python - 将 PyQT5 信号从服务类连接到多个插槽
- javascript - 实现最低限度的承诺功能以了解其他承诺框架