2010-11-30 102 views
2

在我正在处理的程序中,我创建了一个循环来接收20个单独的字符作为用户输入,转换为char,存储在array2中,并将array2返回到main。当我运行我编写的程序时,似乎我写的代码没有正确地将字符存储在array2中。JAVA-返回一个数组主要

在主:

// 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; 
} 

回答

6

尝试

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

您获得价值到输入变量,而不是分配给它一个新的字符后,数组每次通过循环。

+0

啊,明白了。谢谢。 – Jett 2010-11-30 05:03:59

2

现在你正在创建一个新的array2与每个输入,从而摧毁任何以前的输入与您创建的前一个array2。

如果您绝对需要创建一个char数组,那么为什么不将String答案追加到StringBuffer对象中,然后在完成时调用StringBuffer上的toString()。toCharArray()。

我自己,我会创建一个ArrayList,并将响应追加到ArrayList,并在最后返回ArrayList。

+0

+1用于正确识别问题。 – mvg 2010-11-30 05:04:41

0

修改方法参数不是个好主意。你可以试试:

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(); 
}