【发布时间】:2018-12-06 18:59:21
【问题描述】:
程序功能是从两个单独的文本文件中读取,一个文本文件称为gift(随机名称)和cost(每天的总成本)。如果用户输入为 3,我必须打印,它将打印 3 行以及这 3 天的成本。此外,我必须打印 12 天的总成本。
我的代码
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.text.NumberFormat;
public class GiftsTwelveDays{
public static void main(String[] args) {
String[] gifts = new String[12];
double[] costGifts = new double[12];
String total = new String();
//Following code reads the Gifts.txt file
File file = new File("gifts.txt");
try
{
Scanner scannerFile = new Scanner(file);
while (scannerFile.hasNextLine())
{
int i = scannerFile.nextInt();
String present = scannerFile.nextLine();
gifts[i - 1] = present;
}
scannerFile.close();
}
catch (FileNotFoundException e)
{
System.out.println("File not Found.");
}
//This reads the cost and stores in array of double
File file1 = new File("cost.txt");
try
{
Scanner scannerFile = new Scanner(file1);
while (scannerFile.hasNextInt()) {
scannerFile.next();
if(scannerFile.hasNextInt())
{
int i = scannerFile.nextInt();
double cost = scannerFile.nextDouble();
costGifts[i-1] = cost;
}
else
{
scannerFile.nextInt();
total = scannerFile.nextLine();
}
}
scannerFile.close();
}
catch (FileNotFoundException e)
{
System.out.println("File could not be found");;
}
//following gets user input and runs
Scanner userInput = new Scanner(System.in);
NumberFormat money = NumberFormat.getInstance(); //for format with comma
money.setGroupingUsed(true);
double costDay = 0;
System.out.println("Enter the day:");
int choice = userInput.nextInt();
userInput.nextLine();
if (choice < 1 || choice > 12)//runs if choice is invalid
{
System.out.println("Invalid Choice");
}
else
{
System.out.println("Your gifts for the day " + choice + " are: \n");
//calculates the day cost and prints gift simultaneously
for(int i = 0; i < choice; i++)
{
System.out.println((i + 1) + gifts[i]);
costDay = costDay + costGifts[i];
}
//prints the calculated cost.
System.out.println("\nCost of Day: $" + money.format(costDay));
System.out.println("\nTotal Cost for Twelve Days: $" + total);
}
}
}
输出:
Enter the day:
3
Your gifts for the day 3 are:
1 Patridge in a Pear Tree
2 Turtle Doves
3 French Hen
Cost of Day: $0
Total Cost for Twelve Days: $
gifts.txt
1 Patridge in a Pear Tree
2 Turtle Doves
3 French Hen
4 Calling Birds
5 Gold Rings
6 Geese-a-Laying
7 Swans-a-Swimming
8 Maids-a-Milking
9 Ladies Dancing
10 Lords-a-Leaping
11 Piper
12 Drummers Drumming
成本.txt
220.13
595.13
776.63
1376.59
2126.59
2516.59
15641.59
15699.59
23252.43
33252.43
36056.83
39094.93
【问题讨论】:
-
那么想要的输出是什么?
-
当日成本为 0,但我的文本文件有 12 个数字,总成本不显示意味着将所有 12 个数字相加等于 12 天的总成本。
标签: java arrays string file java.util.scanner