对象的字符串表示形式... verbose vs hexadecimal

时间:2017-01-20 23:52:38

标签: java arrays

我正在制作一个程序,我必须阅读一个文件并存储奖品的名称和价格。我试图打印出我存储信息的数组,但它打印出十六进制代码。我该如何解决这个问题,以便数组中存储正确的名称和价格?这是我的代码:

OutputProjectionWrapper

这是我的代码():

public class PrizeGame {

    public static void main(String[] args) {

        Prize[] prizes = new Prize[50];

        Random random = new Random();

        try {
            Scanner fileScanner = new Scanner(new File("prizeList.txt"));

            int count = 0;
            while (fileScanner.hasNextLine()) {
                String fileLine = fileScanner.nextLine();
                String[] splitLine = fileLine.split("\t");
                if (splitLine.length == 2) {
                    prizes[count] = new Prize(splitLine[0], Integer.parseInt(splitLine[1]));

                    count++;
                }
            }

            for (int i = 0; i < prizes.length; i++) {
                System.out.println(prizes[i]);
            }
        } catch (IOException e) {
            System.out.println("Error reading file");
        }
    }
}

1 个答案:

答案 0 :(得分:0)

在Prize中添加toString方法:

@Override
public String toString() {
  return this.name + " " + this.price;
}

代替:

System.out.println(prizes[i]);

System.out.println(prizes[i].getName() + " " + prizes[i].getPrice());