我试图用最近的偶数索引字符在字符串中将每个奇数索引字符切换到它。
public class A3_Q1 {
public static void main(String... args) {
System.out.print("Enter the messgae you want to be coded: ");
Scanner in = new Scanner(System.in);
String msg = in.nextLine();
in.close();
msg = msg.trim();
char msg1[] = msg.toCharArray();
int index = 0;
while (index<msg.length()) {
msg1[index] = msg1[++index];
index++;
}
System.out.print(msg1);
}
}我试着去找更有经验的朋友,问他们出了什么问题,但我们都不知道是怎么回事。
发布于 2022-11-02 07:16:12
如果索引是msg.length() -1,会发生什么情况?你会越界的。
因此,您应该检查循环中的两个条件。
index + 1不是超出限制范围的指数。发布于 2022-11-02 07:44:56
++index在使用该值之前先增加索引。index++在增量之前首先使用该值。这意味着每次迭代都会使index增加2。如果msg有一个奇数长度(您的示例5),并且index = 4,则进入循环。[++index]被计算为[5],您将得到异常。
因此,您必须忽略while (index<msg.length() - 1)的最后一个奇数字符。
发布于 2022-11-02 06:26:42
public static void main(String... args) {
// Best practice: one instruction per one line
System.out.print("Enter the message you want to be coded: ");
// When using System.in you should not close the Scanner
Scanner scan = new Scanner(System.in);
String message = scan.nextLine().trim();
// Best practice: move encoding logic to the separate method
String convertedMessage = convert(message);
System.out.println(convertedMessage);
}
public static String convert(String str) {
// String is immutable, so we have to use StringBuilder to build a new string
StringBuilder buf = new StringBuilder();
// does not matter what to use, I prefer for...loop
for (int i = 0; i < str.length(); i++) {
// do not forget to check case for the last index
if (i == str.length() - 1 || i % 2 != 0)
buf.append(str.charAt(i));
else
// here we have odd and not last index (just use the next one)
buf.append(str.charAt(i + 1));
}
return buf.toString();
}Demo
Enter the message you want to be coded: abcdefghijklmnopqrstuvwxyz
bbddffhhjjllnnpprrttvvxxzzhttps://stackoverflow.com/questions/74285043
复制相似问题