我必须编写一个程序来计算圣诞节的十二天。程序要求输入1到12之间的整数,然后列出当天的礼物以及费用。该程序还应该计算所有十二天的总费用。该程序应从文本文件中读取信息。
我的代码:
import java.util.Arrays;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class TwelveDaysOfChristmas {
private String[] nameDays = new String[12];
private int[] costDays = new int[12];
public void readData(String fileName)
{
String[] name = new String[12];
int[] total = new int[12];
BufferedReader bufferedReader = null;
String line = null;
int countNum = 0;
try
{
bufferedReader = new BufferedReader(new FileReader(fileName));
while((line = bufferedReader.readLine()) != null)
{
String[] data = line.split(",");
name[countNum] = data[0];
total[countNum] = Integer.parseInt(data[1]);
countNum++;
}
if(fileName == "nameDays.txt")
{
nameDays = name;
costDays = total;
}
else
{
System.out.println("Error ocurred.Not days encountered.");
}
if(fileName == "costDays.txt")
{
costDays = total;
}
else
{
System.out.println("Not cost encountered.");
}
bufferedReader.close();
}
catch(FileNotFoundException e)
{
System.out.println("File Not Found");
}
catch(IOException e)
{
System.out.println("Error input file.");
}
}
public void setNameData()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter day: ");
int day = keyboard.nextInt();
if(Arrays.asList(nameDays).contains(day))
{
int index = Arrays.asList(nameDays).indexOf(day);
int ocurrences = costDays[index];
System.out.println("User Input: " + day);
System.out.println("Sample output: ");
System.out.println("Your gifts for Day " + day + " are:");
System.out.println((index + day) + "\n" + ocurrences);
}
else
{
System.out.println("Error try again :D");
}
if(Arrays.asList(costDays).contains(day))
{
int index = Arrays.asList(costDays).indexOf(day);
int ocurrences = costDays[index];
System.out.println("cost of day: " + day);
System.out.println("Total cost of twelve days: ");
System.out.println("Your gifts for Day " + day + " are:");
System.out.println((index + day) + "\n" + ocurrences);
}
else
{
System.out.println("Error try again :D");
}
}
}
我的驱动器程序
public class Test {
public static void main(String[]args)
{
TwelveDaysOfChristmas user = new TwelveDaysOfChristmas();
user.readData("nameDays.txt");
user.readData("costDays.txt");
user.setNameData();
}
}
我得到了错误:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at TwelveDaysOfChristmas.readData(TwelveDaysOfChristmas.java:32)
at Test.main(Test.java:7)
文本文件:
nameDays.txt
One Patridge in a Pear Tree,
Two Turtle Doves,
Three French Hen,
Four Calling Birds,
Five Gold Rings,
Siz Geese-a-Laying,
Seven Swans-a-Swimming,
Eight Maids-a-Milking,
Nine Ladies Dancing,
Ten Lords-a-Leaping,
Eleven Piper,
Twelve Drummers Drumming
costDays.txt
220.13,
375.00,
181.50,
599.96,
750.00,
390.00,
13125.00,
58.00,
7552.84,
10000.00,
2804.40,
3038.10