簡體   English   中英

JAVA-將數組返回到main

[英]JAVA- Returning an Array to main

在我正在處理的程序中,我創建了一個循環來接收20個單獨的字符作為用戶輸入,轉換為char,存儲在array2中,並將array2返回到main。 當我運行我編寫的程序時,似乎我編寫的代碼沒有正確地存儲array2中的字符。

主要:

// Create array to hold user's answers, and pass answers to the array.
char array2[ ] = new char[20];
getAnswers(array2);

在getAnswers()中:

// getAnswers method requests user input and passes to array2.
public static char[ ] getAnswers(char array2[ ])
{
   String input;  // Holds user input.

   Scanner keyboard = new Scanner(System.in);

   // Request user input.
   System.out.println("Enter the answers for the the multiple choice exam.");

   // Loop to receive input into array.
   for (int index = 0; index < 20; index++)
   {
      System.out.print("Enter number " + (index + 1) +": ");
      input = keyboard.nextLine();
      array2 = input.toCharArray();
   }
   return array2;
}

嘗試

array2[index] = input.charAt(0);

在將值輸入到輸入變量之后,而不是每次循環時為其分配一個新的char數組。

現在,您正在使用每個輸入創建一個新的array2,從而使用您創建的前一個array2銷毀任何先前的輸入。

如果您絕對需要創建一個char數組,為什么不將String答案附加到StringBuffer對象中,然后在完成后,在StringBuffer上調用toString()。toCharArray()。

我自己,我創建一個ArrayList,只是將響應附加到ArrayList,最后返回ArrayList。

修改方法參數不是一個好主意。 你可以試試 :

public static char[ ] getAnswers(char array2[ ])
{
   String input;  // Holds user input.

   Scanner keyboard = new Scanner(System.in);

   // Request user input.
   System.out.println("Enter the answers for the the multiple choice exam.");

String tmp = "";
for (int index = 0; index < 20; index++)
{
   System.out.print("Enter number " + (index + 1) +": ");
   input = keyboard.nextLine();
   tmp += input.chaAt(0);   // check length is > 0 here
}
return tmp.toCharArray();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM