英文:
How to replace all even elements in an integer array with a special symbol "$" using java
问题
我们有一个整数数组,其中所有偶数必须被替换为"$"。
以下是我的代码:
int[] array = {1, 2, 3, 4, 5, 6};
char specialChar = '$';
for (int i = 0; i < array.length; i++) {
if (array[i] % 2 == 0) {
array[i] = specialChar;
}
}
System.out.println(Arrays.toString(array));
输出结果:[1, $, 3, $, 5, $]
预期输出:[1, $, 3, $, 5, $]
英文:
We have an integer array and all even numbers in that array must be replaced by "$";
Here is my code :
int[] array = {1, 2, 3, 4, 5, 6};
char specialChar = '$';
for (int i = 0; i < array.length; i++) {
if (array[i] % 2 == 0) {
array[i] = specialChar;
}
}
System.out.println(Arrays.toString(array));
Output Obtained : [1, 42, 3, 42, 5, 42]
Expected Output : [1, $, 3, $, 5, $]
答案1
得分: 3
我认为你需要将结果数组切换为字符数组。
char specialChar = '$';
int[] array = {1, 2, 3, 4, 5, 6};
char[] result = new char[array.length];
for (int i = 0; i < array.length; i++) {
if (array[i] % 2 == 0) {
result[i] = specialChar;
} else {
result[i] = (char)(array[i] + '0');
}
}
System.out.println(Arrays.toString(result));
英文:
I think you need to switch the result array into char array
char specialChar = '$';
int[] array = {1, 2, 3, 4, 5, 6};
char[] result = new char[array.length];
for (int i = 0; i < array.length; i++) {
if (array[i] % 2 == 0) {
result[i] = specialChar;
} else {
result[i] = (char)(array[i] + '0');
}
}
System.out.println(Arrays.toString(result));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论