【发布时间】:2014-11-14 08:01:19
【问题描述】:
我正在尝试调用我的 add 方法来向我的数组添加分数 到目前为止我已经得到了这个,但我一直收到一个错误,说 myQuiz 从未初始化过。 ..................................................... .....................................
import java.util.Scanner;
public class Assignment7 {
public static void main (String[] args) {
//new scanner
Scanner in = new Scanner (System.in);
String choice;
char command;
// print the menu
int count = 0;
int counter = 0;
printMenu();
int array[] = new int[0];
//do while loop testing using user input
do{
// ask a user to choose a command
System.out.println("\nPlease enter a command or type ?");
choice = in.next().toLowerCase();
command = choice.charAt(0);
//start switch statement for user input cases
switch (command)
{
switch (command)
{
case 'n': //ask and read the size of the input array and name
System.out.print("\n\t n [Create a new Quiz]: ");
System.out.print("\n\t [Input the size of quizzes]: ");
int num=in.nextInt(); // read the integer
array = new int[num];
System.out.print("\n\t [Input the name of the student]: ");
String name = in.next(); //read name
Quiz myQuiz = new Quiz(num, name);
break;
case 'a': // ask and add score to array
System.out.print("\n\t a [Add a score]: ");
array[count] = in.nextInt();
myQuiz.add(array[count]);
counter++;
break;
/*
case 'a': // ask and add score to array
System.out.print("\n\t a [Add a score]: ");
array[count] = in.nextInt();
myQuiz.add(array[count]); //HELP
counter++;
break;
还有我的带有添加方法的 Quiz.java
public class Quiz {
private int count;
private int[] scores;
private String name;
public Quiz(int a,String name){
scores = new int [a];
for (int i = 0; i<scores.length; i++){
scores[i] = -1;
}
this.count = 0;
this.name = "";
}
public void add(int b){
for(int i : scores){
if(scores[i] == count){
System.out.println("Array is full. The value " + b + " cannot be added.");
}
else {
scores[count] = b;
count++;
}
【问题讨论】:
-
myQuiz从未在您的主类中定义Assignment7 -
我只看到一处提到了
myQuiz,那就是myQuiz.add(array[count]);。所以,我猜错误信息是对的 -
myQuiz.add(array[count]);你需要添加 Quiz myQuiz = new Quiz();我留给你弄清楚在哪里添加该行:)。
-
我确实添加了它,只是在这段代码中省略了它。仍然给我错误。将该语句放在 do-while 循环之前
-
如果您对代码进行了更改,请编辑问题以显示它们,而不是让人们猜测您有什么没有尝试过。
标签: java arrays methods non-static