gpt4 book ai didi

java - 从带有数字的文本文件中读取字母

转载 作者:行者123 更新时间:2023-11-30 06:55:13 24 4
gpt4 key购买 nike

这是一项学校作业。我得到了这个文本文件,我需要从中读取值,如下所示
T = 门票销售D = donationsE = expenses,文本文件将其列为;

T 2000.00
E 111.11
D 500.00
E 22.22

我想从文本文件中获取数据,添加类似的值,询问用户是否希望添加其他数据,然后显示计算输出。

import java.io.*;
import java.util.Scanner;

public class MyEventManager {
public static String amountType;
public static int amount;

public static String validationMethodType () throws IOException
{
Scanner keyboard = new Scanner ( System.in );
System.out.printf("\nPlease enter an amount type ('T' - Tickets), ('D' - Donations), ('E' - Expenses): ");
amountType = keyboard.next().toUpperCase();
char choice = amountType.charAt(0);
//choice = Character.toUpperCase(choice);

if (choice != 'T' && choice != 'D' && choice != 'E')
{
do
{
System.out.printf("\nInvlaid amount entered...");
System.out.printf("\nPlease enter an amount type ('T' - Tickets), ('D' - Donations), ('E' - Expenses): ");
amountType = keyboard.next().toUpperCase();
choice = amountType.charAt(0);
//choice = Character.toUpperCase(choice);
}
while(choice != 'T' && choice != 'D' && choice != 'E');
return amountType;
}
else
{
return amountType;
}
}
public static int validationMethodAmount()
{
Scanner keyboard = new Scanner ( System.in );
System.out.printf("\nPlease enter an amount (amount must be positive and non-zero): ");
amount = keyboard.nextInt();

if (amount <= 0)
{
do
{
System.out.printf("\nInvlaid amount entered...");
System.out.printf("\nPlease enter an amount (amount must be positive and non-zero): ");
amount = keyboard.nextInt();
}
while (amount <= 0);
return amount;
}
else
{
return amount;
}
}
public static void main(String [] args) throws IOException
{
Scanner keyboard = new Scanner ( System.in );
System.out.printf("This program will read a text file and add data to it, then compute the results.\n\n"); // display purpose
MyEventClass myEvent = new MyEventClass(); //create object
//
String readFile = "Event.txt"; //file location constant
try
{
File inputFile = new File (readFile); //open the file
InputStream is;
Scanner scanFile = new Scanner (inputFile); //scan the file
{
is = new BufferedInputStream(new FileInputStream(inputFile));
//
try
{
while(scanFile.hasNext())
{
if ( scanFile.hasNextLine())
{
myEvent.instanceMethod(amountType, amount);
}

}
}
catch (IllegalArgumentException o)
{
System.out.println("Error code 3: No data found!" );
}

}
byte[] c = new byte[1024];
int count = 1;
int readChars;

while ((readChars = is.read(c)) != -1)
{
for (int i = 0; i < readChars; ++i)
{
if (c[i] == '\n')
{
++count;
}
}
}
System.out.println("Total number of valid lines read was " + count);
}
catch (FileNotFoundException e)
{
System.out.println("Error code 4: The file " + readFile + " was not found!" );
}
System.out.println("Are there any more amounts to add that where not in the text file? ");
String questionOne = keyboard.next();

if ("y".equalsIgnoreCase(questionOne))
{
validationMethodType();
validationMethodAmount();
myEvent.instanceMethod(amountType, amount);

}
myEvent.displayResults();
}
}

第二类

public class MyEventClass {
private double ticketSales;
private double moneyDonated;
private double moneySpent;

public MyEventClass ()
{
this.ticketSales = 0.0;
this.moneyDonated = 0.0;
this.moneySpent = 0.0;

}

public double getTicketSales ()
{
return ticketSales;
}

public double getMoneyDonated ()
{
return moneyDonated;
}

public double getMoneySpent ()
{
return moneySpent;
}

public double instanceMethod (String amountType, double amount)
{

char choice = amountType.charAt(0);
if(amount <= 0)
{
throw new IllegalArgumentException("Error code 1: Amount should be larger then 0");
}

if(choice != 'T' && choice != 'D' && choice != 'E')
{
//increment the current total for the amount type specified by the first parameter by the amount in the second paramter?
return amount++;
}
else
{
throw new IllegalArgumentException("Error code 2: Invalid input, data will be ignored");
}
}

public void displayResults()
{
double income = this.ticketSales + this.moneyDonated;
double profits = income - this.moneySpent;
System.out.printf("\nTotal Ticket Sales: " + "%8.2f", this.ticketSales);
System.out.printf("\nTotal Donations: " + "%11.2f" + " +", this.moneyDonated);
System.out.printf("\n --------");
System.out.printf("\nTotal Income: " + "%14.2f", income);
System.out.printf("\nTotal Expenses: " + "%12.2f" + " -", this.moneySpent);
System.out.printf("\n --------");
System.out.printf("\nEvent Profits: " + "%13.2f", profits);
System.out.println();
}
}

我认为我的问题之一是 instanceMethod 返回应该在此处添加值的位置。

当前输出;

run:
This program will read a text file and add data to it, then compute the results.

Exception in thread "main" java.lang.NullPointerException
at MyEventClass.instanceMethod(MyEventClass.java:34)
at MyEventManager.main(MyEventManager.java:90)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)

最佳答案

添加到 pczeus 的答案中,您还需要设置金额。改变

amountType = scanFile.nextLine();

String[] temp = scanFile.nextLine().split(" ");

amountType = temp[0];
amount = new Double(temp[1]);

应该解决这个问题。之后的下一个错误是在您的类(class)中,似乎选择选项被颠倒了。

    if (choice == 'T' || choice == 'D' || choice == 'E') {
//increment the current total for the amount type specified by the first parameter by the amount in the second paramter?
return amount++;
} else {
throw new IllegalArgumentException("Error code 2: Invalid input, data will be ignored");
}

应该是

    if (choice != 'T' && choice != 'D' && choice != 'E') {
throw new IllegalArgumentException("Error code 2: Invalid input, data will be ignored");
} else {
//increment the current total for the amount type specified by the first parameter by the amount in the second paramter?
return amount++;
}

你的最后一个类会是这样的

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class MyEventManager {

private Map<String, Double> amountMap = new HashMap<>();
public String amountType;
public double amount;

public static void main(String[] args) throws IOException {
MyEventManager eventManager = new MyEventManager();
eventManager.runEvent();
}

private void runEvent() throws IOException {
System.out.printf("This program will read a text file and add data to it, then compute the results.\n\n");

File inputFile = new File("Event.txt");
handleFileInput(inputFile);

System.out.println("Are there any more amounts to add that where not in the text file?\n");
Scanner keyboard = new Scanner(System.in);
String questionOne = keyboard.next();

if ("y".equalsIgnoreCase(questionOne)) {
do {
validationMethodType();
validationMethodAmount();
addAmount(amountType, amount);

System.out.println("Are there any more amounts to add that where not in the text file?\n");
keyboard = new Scanner(System.in);
questionOne = keyboard.next();
} while (questionOne.equalsIgnoreCase("y"));
}

displayResults();
}

private void handleFileInput(File inputFile) throws IOException {
try (Scanner scanFile = new Scanner(inputFile)) {
int lineCount = 0;
while (scanFile.hasNext()) {
if (scanFile.hasNextLine()) {
String[] temp = scanFile.nextLine().split(" ");

String amountType = temp[0];
double amount = new Double(temp[1]);

try {
checkType(amountType);
checkAmount(amount);
} catch (IllegalArgumentException e) {
e.printStackTrace();
continue;
}

addAmount(amountType, amount);
lineCount++;
}
}
System.out.println("Total number of valid lines read was " + lineCount);
} catch (FileNotFoundException e) {
System.out.println("Error code 4: The file " + inputFile.getName() + " was not found!");
}
}

private String validationMethodType() throws IOException {
Scanner keyboard = new Scanner(System.in);
System.out.printf("\nPlease enter an amount type ('T' - Tickets), ('D' - Donations), ('E' - Expenses): ");
amountType = keyboard.next().toUpperCase();

if (amountTypeValid(amountType)) {
do {
System.out.printf("\nInvlaid amount entered...");
System.out.printf("\nPlease enter an amount type ('T' - Tickets), ('D' - Donations), ('E' - Expenses): ");
amountType = keyboard.next().toUpperCase();
}
while (amountTypeValid(amountType));
}

return amountType;
}

private double validationMethodAmount() {
Scanner keyboard = new Scanner(System.in);
System.out.printf("\nPlease enter an amount (amount must be positive and non-zero): ");
amount = keyboard.nextInt();

if (amount <= 0) {
do {
System.out.printf("\nInvlaid amount entered...");
System.out.printf("\nPlease enter an amount (amount must be positive and non-zero): ");
amount = keyboard.nextInt();
}
while (amount <= 0);
}

return amount;
}

private void checkAmount(double amount) {
if (amount <= 0) {
throw new IllegalArgumentException("Error code 1: Amount should be larger then 0");
}
}

private void checkType(String type) {
if (amountTypeValid(type)) {
throw new IllegalArgumentException("Error code 2: Invalid input, data will be ignored");
}
}

private void addAmount(String amountType, double amount) {
if (amountMap.containsKey(amountType)) {
double currentAmount = amountMap.get(amountType);
amountMap.put(amountType, currentAmount + amount);
} else {
amountMap.put(amountType, amount);
}
}

private boolean amountTypeValid(String type) {
return !type.equalsIgnoreCase("T") && !type.equalsIgnoreCase("D") && !type.equalsIgnoreCase("E");
}

private void displayResults() {
double ticket = amountMap.containsKey("T") ? amountMap.get("T") : 0;
double donated = amountMap.containsKey("D") ? amountMap.get("D") : 0;
double spent = amountMap.containsKey("E") ? amountMap.get("E") : 0;
double income = ticket + donated;
double profits = income - spent;
System.out.printf("\nTotal Ticket Sales: " + "%8.2f", ticket);
System.out.printf("\nTotal Donations: " + "%11.2f" + " +", donated);
System.out.printf("\n --------");
System.out.printf("\nTotal Income: " + "%14.2f", income);
System.out.printf("\nTotal Expenses: " + "%12.2f" + " -", spent);
System.out.printf("\n --------");
System.out.printf("\nEvent Profits: " + "%13.2f", profits);
System.out.println();
}
}

关于java - 从带有数字的文本文件中读取字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35544613/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com