[英]Comparing command line arguments in java to a character array
我正在為我的類編寫一個程序,該程序從命令行(java ADCB等)獲取參數,並將其與字符數組進行比較。 在這種情況下,這是考試的關鍵,而命令行參數就是答案。 我想我幾乎想通了,但是已經遇到了arrayIndexOutofBoundsException:1一段時間了。 我對命令行參數不是很熟悉,因此我可能缺少一些重要的東西,但是我的Java書籍中沒有涵蓋此信息。 任何意見,將不勝感激。 提前致謝。
碼:
public class GradeExam {
/** Main method */
public static void main(String args[]) {
// Key to the questions
char[] keys = {'D', 'B', 'D', 'C', 'C', 'D', 'A', 'E', 'A', 'D'};
int correctCount = 0;
for(int i = 0; i < args.length; i++){
String newargs = args[i];
char[] argarray = newargs.toCharArray();
for (int j = 0; j < args.length; j++) {
if (argarray[j] == keys[j])
correctCount++;
}
}
System.out.println("Your correct count is " +
correctCount);
}
}
Input: java GradeExam D B D C C D A E A D
Expected output: Your correct count is 10
如果您這樣調用程序...
java GradeExam D B D C C D A E A D
...那么每個字母都是一個單獨的參數( args[0] = "D"
, args[1] = "B"
等)。 根據您的代碼,我認為您打算這樣做:
java GradeExam DBDCCDAEAD
您可能還希望內部循環如下所示:
for (int j = 0; j < argarray.length && j < keys.length; j++) {
if (argarray[j] == keys[j])
correctCount++;
}
這樣,即使命令行參數的字母太多或太少,也不會耗盡任何一個數組的末尾。
您在此行上得到arrayIndexOutofBoundsException: 1
:
if (argarray[j] == keys[j])
因為您的argarray
總是只有一個元素,並且j
接受0...args.length
值。
另外,您根本不需要內部循環,可以像這樣簡化程序:
public static void main(String args[]) {
char[] keys = {'D', 'B', 'D', 'C', 'C', 'D', 'A', 'E', 'A', 'D'};
int correctCount = 0;
for (int i = 0; i < args.length && i < keys.length; i++) {
if (args[i].charAt(0) == keys[i]) {
correctCount++;
}
}
System.out.println("Your correct count is " + correctCount);
}
問題是:
char[] argarray = newargs.toCharArray();
for (int j = 0; j < args.length; j++) {
if (argarray[j] == keys[j])
correctCount++;
}
實際上,您實際上是試圖將當前正在查看的String參數轉換為字符數組,而實際上您應該只將String參數轉換為單個字符。 將其轉換為字符后,可以將其與您正在查看的當前鍵進行比較。
您可能需要在開始時進行一些檢查,以確保給出的答案數量等於鍵的數量,如下所示。
public class GradeExam {
public static void main(String[] args) {
char[] keys = {'D', 'B', 'D', 'C', 'C', 'D', 'A', 'E', 'A', 'D'};
if (args.length != keys.length) {
throw new RuntimeException("Expected number of input answers: " + keys.length + " but got " + args.length);
}
int correctCount = 0;
try {
for (int i = 0; i < keys.length; i++) {
char key = keys[i];
// We need to convert the String into a character
char answerChar = args[i].charAt(0);
if (answerChar == key) {
correctCount++;
}
}
} catch (IndexOutOfBoundsException ex) {
ex.printStackTrace();
}
System.out.println("Your correct count is " + correctCount);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.