我试图打印字符串中的每个第二个字母,但出于某种原因,我只正确打印了第一个第二个字母,但之后它一直以奇怪的顺序打印。这是我的代码:
out.print("Please enter a word: ");
String word = in.nextLine();
char[] c = word.toCharArray();
int x = 0;
while (x < c.length) {
if (c[x] % 2 != 0) {
out.print(word.charAt(x) + " ");
}
x++;
}
最佳答案
你应该改变这个:
if (c[x] % 2 != 0) {
到
if (x % 2 != 0) {
这比较的是您正在使用的索引,而不是比较字符。 x
是字符的位置。 c[x]
是字符。您可以将 c[x]
读作“数组 c
中位置 x
的值”。
关于java - 字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18901273/