[英]How can I print a word two letters at a time? - java
The input is supposed to have an even length.输入应该有一个偶数长度。 The problem is that on the first iteration of the loop, it print Sc, but then it prints ch instead of ho.
问题是在循环的第一次迭代中,它打印出 Sc,但随后打印出 ch 而不是 ho。 I'm not sure how to make that jump.
我不知道怎么跳。
public static void twoAtATime(String a) { // School
int len = a.length();
if(len%2 == 0) {
for(int i = 0; i <a.length()/2; i++) {
System.out.print(a.substring(i,i+1) + a.substring(i+1,i+2));
System.out.println();
}
}
The output is supposed to be like this: output 应该是这样的:
Sc
ho
ol
To fix it:要解决这个问题:
i
by 2
.i
增加2
。i < len
.i < len
。 You can improve it:你可以改进它:
substring
once for two chars.substring
。println
with param.println
。i
once - i += 2
.i
一次 - i += 2
。 After improvements:改进后:
public static void twoAtATime(String s) {
int len = s.length();
if (len % 2 == 0) {
for (int i = 0; i < len; ) {
System.out.println(s.substring(i, i += 2));
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.