列表和arraylist初始化和使用

时间:2014-03-26 22:42:20

标签: java arrays list arraylist

我试图创建一个列表,因为它能够添加"和元素相反,而不是检查大小,然后每次输入新元素时动态扩展数组。我无法编译。我已经搜集了堆栈和google,而我发现的任何东西都没有帮助我。有人提到创建一个数组并使用它添加到列表中,但在我看来,我应该能够做到这一点而没有这一切。

每次发生某个结果时,我都试图让系统在列表中添加一个字符串。

为了便于查找列表被调用"不正确"

import java.text.DecimalFormat;
import java.util.*;

public class User{
    private String wrongQuestion;       //quiz question
    private String userName;        //store user name
    private String myOutput;        //store output for toString and file write
    private int score;          //store user current score
    private float average;          //store user average score
    private int diffLevel;          //difficulty level
    private int testType;           //last test type
    private int numTests;           //store number of tests taken
    private List <String> incorrect;    //declare list for incorrect answers
    private FileIO uFile;           //declare FileIO object

    public User(String inName) throws Exception
    {
        //local constants
        final int VARIABLE_COUNT = 5;   //loop sentinel
        final int TOKEN_SKIP = 4;       //loop sentinel

        //local variables
        int index;                  //loop index
        int count;                  //loop counter
        String token;               //store tokens from line
        StringTokenizer tokenLine;  //store tokenized line

        //instantiate file object
        uFile = new FileIO (inName);

        //if user exists
        if (uFile.checkUser())
        {
            for (count = 0; count < VARIABLE_COUNT; count++)
            {
                //initialize tokenized line
                tokenLine = new StringTokenizer(uFile.readLine());

                //try to store the variables
                try
                {   
                    //get and store user average
                    //for the first 2 tokens, skip
                    for (index = 0; index < TOKEN_SKIP; index++)
                    {
                        //move to next token
                        token = tokenLine.nextToken();//end for

                        switch (count)
                        {
                            case 1:
                                //store number of tests taken
                                numTests = Integer.parseInt(token);

                                //end case
                                break;
                            case 2:
                                //store difficulty of last test taken
                                diffLevel = Integer.parseInt(token);

                                //end case
                                break;
                            case 3:
                                //store score of last test taken
                                score = Integer.parseInt(token);

                                //end case
                                break;
                            case 4:
                                //store average of tests taken
                                average = Integer.parseInt(token);

                                //end case
                                break;

                            default:
                                break;
                        }//end switch
                    }//end for

                    //store next line
                    token = uFile.readLine();

                    //while there are more lines in the file
                    while (token != null)
                    {
                        //instantiate list for incorrect answers
                        incorrect = new ArrayList<String>();

                        //add line to end of list
                        incorrect.get(token);

                        //store next line
                        token = uFile.readLine();
                    }//end while
                }//end try

                //catch input mismatch exception
                catch (InputMismatchException error)
                {
                    //output error message
                    System.out.println ("This file is not formatted properly." +
                            " Either continue as a new user or log in again");

                    //initialize data to 0
                    average = 0;
                    testType = 0;
                    diffLevel = 0;
                    numTests = 0;
                    incorrect = new ArrayList <String>();
                }//end catch
            }//end for
        }//end if

        else
        {
            //initialize data to 0
            average = 0;
            testType = 0;
            diffLevel = 0;
            numTests = 0;
            incorrect = new ArrayList<String>();
        }//end else

        //close input stream
        uFile.closeFileReader();
    }//end constructor

    public float calcAverage(int newScore)
    {
        //local constants
        //local variables
        float avg;              //store temp average

        /**************Begin calcAverage*********/
        //recalibrate avg for new calculation
        avg = 0;

        //calculate new average test score
        avg = ((average * numTests) + newScore )/(numTests + 1);

        //return average to be stored
        return avg;
    }

    public void updateUser(int newTestType, int newDiffLevel, int newScore)
    {
        //local constants
        //local variables

        /***************Begin updateUser************/

        //update new data after test is taken
        score = newScore;
        average = calcAverage(newScore);
        diffLevel = newDiffLevel;
        testType = newTestType;
        numTests = numTests + 1;
    }

    public void writeFile() throws Exception
    {
        //local constants
        //local variables
        String line;        //current line to write to file
        int index;          //loop index

        /*************************Begin writeFile***************/
        //open output stream
        uFile.openOutput(userName);

        //write user name
        line = "User Name:\t" + userName +"\n";
        uFile.writeLine(line);

        //write number of tests taken
        line = "Tests Taken:\t" + numTests + "\n";

        //write number of tests taken
        line = "Difficulty Level:\t" + diffLevel + "\n";
        uFile.writeLine(line);

        //write score of last test taken
        line = "Last Test:\t" + score + "\n";
        uFile.writeLine(line);

        //write current user average
        line = "User Average:\t" + average + "\n";
        uFile.writeLine(line);

        //for each element in the list
        for (index = 0; index < incorrect.size(); index++)
        {
            //store then write the string
            line = incorrect.get(index);
            uFile.writeLine(line);
        }//end for

        //close file writer
        uFile.closeFileWrite();
    }//end writeFile

    public void storeIncorrect(String inString)
    {
        //local constants
        //local variables

        /************Begin storeIncorrect*************/
        //add formatted question to the list
        incorrect.add(inString);
    }

    public String toString()
    {
        //local constants
        //local variables
        String buildUserName;
        String buildAvg;
        String buildNumTests;
        String buildDiffLevel;
        String buildScore;
        DecimalFormat fmt;      //declare decimal format object

        /****************Begin toString***********/
        //initialize decimal format
        fmt = new DecimalFormat ("0.00");

        //build output strings
        buildUserName = Util.setLeft(20, "User Name:") + Util.setRight(25, userName);
        buildNumTests = Util.setLeft(20, "Tests Taken:") + Util.setRight(18, numTests+"");
        buildDiffLevel = Util.setLeft(20, "Last Difficulty:") + Util.setRight(24, diffLevel+"");
        buildScore = Util.setLeft(20, "Last Score:") + Util.setRight(24, score+"");
        buildAvg = Util.setLeft(20, "Test Average:") + Util.setRight(24, fmt.format(average)+"");

        myOutput = buildUserName + "\n" + buildNumTests + "\n" + buildDiffLevel + "\n" + buildScore + "\n" + buildAvg;
        return myOutput;

    }//Display all users info
}

1 个答案:

答案 0 :(得分:0)

很少有评论可能会有所帮助:

// add line to end of list
incorrect.get(token); // <- change this to incorrect.add(token)

通过列表使用迭代:

   for (String item : incorrect) {
       System.out.printlnt(item);
   }

此外,您不需要多次重新初始化列表

incorrect = new ArrayList<String>();

如果您想清除它,可以使用incorrect.clear()

由于您对随机访问(即通过索引)不感兴趣,也许您可​​以使用LinkedList代替ArrayList