I am working my way through Cay Horstmann's book Big Java early objects, and I am having trouble with the worked example number 12. I want to read information from a text file but the code doesn't seem to work for me. What am I doing wrong?
Here is the code:
package javaprogrammingproject;
import java.io.IOException;
import java.util.Scanner;
/**
* A text-based simulation of an automatic teller machine.
*/
public class ATMSimulator {
public static void main(String[] args) {
ATM theATM;
try {
Bank theBank = new Bank();
theBank.readCustomers("customers.txt");
theATM = new ATM(theBank);
} catch (IOException e) {
System.out.println("Error opening accounts file.");
return;
}
Scanner in = new Scanner(System.in);
while (true) {
int state = theATM.getState();
if (state == ATM.START) {
System.out.print("Enter customer number: ");
int number = in.nextInt();
theATM.setCustomerNumber(number);
} else if (state == ATM.PIN) {
System.out.print("Enter PIN: ");
int pin = in.nextInt();
theATM.selectCustomer(pin);
} else if (state == ATM.ACCOUNT) {
System.out.print("A=Checking, B=Savings, C=Quit: ");
String command = in.next();
if (command.equalsIgnoreCase("A")) {
theATM.selectAccount(ATM.CHECKING);
} else if (command.equalsIgnoreCase("B")) {
theATM.selectAccount(ATM.SAVINGS);
} else if (command.equalsIgnoreCase("C")) {
theATM.reset();
} else {
System.out.println("Illegal input!");
}
} else if (state == ATM.TRANSACT) {
System.out.println("Balance=" + theATM.getBalance());
System.out.print("A=Deposit, B=Withdrawal, C=Cancel: ");
String command = in.next();
if (command.equalsIgnoreCase("A")) {
System.out.print("Amount: ");
double amount = in.nextDouble();
theATM.deposit(amount);
theATM.Back();
} else if (command.equalsIgnoreCase("B")) {
System.out.print("Amount: ");
double amount = in.nextDouble();
theATM.withdraw(amount);
theATM.Back();
} else if (command.equalsIgnoreCase("C")) {
theATM.Back();
} else {
System.out.println("Illegal input!");
}
}
}
}
}
Also here is the code for the method:
public void readCustomers(String filename) throws IOException {
Scanner in = new Scanner(new File(filename));
while (in.hasNext()) {
int number = in.nextInt();
int pin = in.nextInt();
Customer c = new Customer(number, pin);
addCustomer(c);
}
in.close();
}
And this is what is in the text file:
1 1234 0 1
2 2468 0 1
3 3692 2 3
4 4826 4 3
5 5050 5 6
6 6284 5 7
7 7418 5 8
8 8642 9 10
9 9876 11 12
Any help is appreciated thanks!
In file, what are columns 3 and 4th for? when you do in.nextInt() in 2nd iteration of while loop you will get 0/1 and not 2/2468 which you are expecting to create customer object. either read file line by line or skip 2 integers to create next customer
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.