我正在嘗試將每個奇數索引字符與最近的偶數索引字符切換到字串中。
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);
}
}
我嘗試搜索并詢問更有經驗的朋友出了什么問題,但我們不知道我們所有的 Compsci 新生
uj5u.com熱心網友回復:
如果 index 是 會發生什么msg.length() -1?您將超出范圍。
因此,您應該檢查回圈中的兩個條件。
- 索引是奇數或偶數
- 索引并且
index 1沒有越界msg.length。
uj5u.com熱心網友回復:
index在使用值之前先增加索引。
index 在遞增之前首先使用該值。這意味著每次迭代都會增加index2。如果msg有一個奇數長度(您的示例 5)并且index = 4您進入回圈。
[ index]被評估為[5]并且你得到例外。
所以你必須忽略奇數長度的最后一個字符while (index<msg.length() - 1)
uj5u.com熱心網友回復:
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();
}
演示
Enter the message you want to be coded: abcdefghijklmnopqrstuvwxyz
bbddffhhjjllnnpprrttvvxxzz
uj5u.com熱心網友回復:
它將超出范圍,因為:
while (index<msg.length()) {
msg1[index] = msg1[ index];
index ;
}
java索引從0開始。所以如果長度為5,它將是0、1、2、3、4。
msg1[index] = msg1[ index];
在索引為 4 的這條線上,您將超出范圍,因為 4 1 為 5。您需要添加類似這樣的內容
if( index<msg.length())
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/525399.html
上一篇:如何在java中修改最終地圖
下一篇:Java位解碼函式
