Java code not executing as expected - java

I've written some Java code, as shown below, but it isn't behaving as I expected. Right near the bottom, starting from the line if (upgrade == "Y"). I did a test, I entered Y but this line did not execute. Could you please help me figure out why this behaviour occurred?
import java.io.*;
class P4
{
public static int get_price(String day_of_week, String age_group)
{
int price=0;
if (day_of_week == "WD")
{
if (age_group == "adult")
price = 66;
else if (age_group == "child")
price=48;
else
price = 32;
}
else
{
if (age_group == "adult")
price = 72;
else if (age_group == "child")
price=52;
else
price = 36;
}
return price;
}
public static void main(String[] args)
{
String adult2=null;
String child2=null;
String senior2=null;
String day_of_week=null;
String upgrade=null;
System.out.println("Enter Number of Adult Ticket:");
BufferedReader adult1 = new BufferedReader(new InputStreamReader(System.in));
try
{
adult2 = adult1.readLine();
}
catch (IOException e) {
System.out.println("Error!");
System.exit(1);
}
System.out.println("Enter Number of Child Ticket:");
BufferedReader child1 = new BufferedReader(new InputStreamReader(System.in));
try
{
child2 = child1.readLine();
}
catch (IOException e) {
System.out.println("Error!");
System.exit(1);
}
System.out.println("Enter Number of Senior Ticket:");
BufferedReader senior1 = new BufferedReader(new InputStreamReader(System.in));
try
{
senior2 = senior1.readLine();
}
catch (IOException e) {
System.out.println("Error!");
System.exit(1);
}
System.out.println("Choose Weekday or Weekend Pass (WD/WE):");
BufferedReader day_of_week1 = new BufferedReader(new InputStreamReader(System.in));
try
{
day_of_week = day_of_week1.readLine();
}
catch (IOException e) {
System.out.println("Error!");
System.exit(1);
}
System.out.println("Upgrade to Express Pass (Y/N):");
BufferedReader upgrade1 = new BufferedReader(new InputStreamReader(System.in));
try
{
upgrade = upgrade1.readLine();
}
catch (IOException e) {
System.out.println("Error!");
System.exit(1);
}
int adult = Integer.parseInt(adult2);
int child = Integer.parseInt(child2);
int senior = Integer.parseInt(senior2);
int total_a = adult * get_price(day_of_week, "adult");
int total_c = child * get_price(day_of_week, "child");
int total_s = senior * get_price(day_of_week, "senior");
int total_price = total_a + total_c + total_s;
int total_people = adult + child + senior;
int upgrade_price = 0;
if (upgrade == "Y")
{
if (day_of_week == "WD")
{
upgrade_price = total_people * 30;
}
else
{
upgrade_price = total_people * 68;
}
}
else
upgrade_price = 0;
int price = upgrade_price + total_price;
System.out.println("The total price is $" + price);
}}

Try using the .equal.. So else if (age_group.equals("child")
Check out the .equals() method: http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#equals(java.lang.Object)
and the .equalsIgnoreCase() method:
http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#equalsIgnoreCase(java.lang.String)
import java.io.*;
class P4
{
public static int get_price(String day_of_week, String age_group)
{
int price=0;
if (day_of_week.equals("WD"))
{
if (age_group.equals("adult"))
price = 66;
else if (age_group.equals("child"))
price=48;
else
price = 32;
}
else
{
if (age_group.equals("adult"))
price = 72;
else if (age_group.equals("child"))
price=52;
else
price = 36;
}
return price;
}

You cannot compare strings with ==, you need to use equals()
if("Y".equals(upgrade))
(I tend to put the constant first, to handle the case where upgrade == null)

In java string comparison
String s = "something", t = "maybe something else";
if (s == t) // Legal, but usually WRONG.
if (s.equals(t)) // RIGHT
if (s > t) // ILLEGAL
if (s.compareTo(t) > 0) // CORRECT>
So in your case, use:
if(upgrade.equals("Y")) {
//your codes
}
import java.io.*;
class P4
{
public static int get_price(String day_of_week, String age_group)
{
int price=0;
if (day_of_week.equals("WD"))
{
if (age_group.equals("adult"))
price = 66;
else if (age_group.equals("child"))
price=48;
else
price = 32;
}
else
{
if (age_group.equals("adult"))
price = 72;
else if (age_group.equals("child"))
price=52;
else
price = 36;
}
return price;
}
public static void main(String[] args)
{
String adult2=null;
String child2=null;
String senior2=null;
String day_of_week=null;
String upgrade=null;
System.out.println("Enter Number of Adult Ticket:");
BufferedReader adult1 = new BufferedReader(new InputStreamReader(System.in));
try
{
adult2 = adult1.readLine();
}
catch (IOException e) {
System.out.println("Error!");
System.exit(1);
}
System.out.println("Enter Number of Child Ticket:");
BufferedReader child1 = new BufferedReader(new InputStreamReader(System.in));
try
{
child2 = child1.readLine();
}
catch (IOException e) {
System.out.println("Error!");
System.exit(1);
}
System.out.println("Enter Number of Senior Ticket:");
BufferedReader senior1 = new BufferedReader(new InputStreamReader(System.in));
try
{
senior2 = senior1.readLine();
}
catch (IOException e) {
System.out.println("Error!");
System.exit(1);
}
System.out.println("Choose Weekday or Weekend Pass (WD/WE):");
BufferedReader day_of_week1 = new BufferedReader(new InputStreamReader(System.in));
try
{
day_of_week = day_of_week1.readLine();
}
catch (IOException e) {
System.out.println("Error!");
System.exit(1);
}
System.out.println("Upgrade to Express Pass (Y/N):");
BufferedReader upgrade1 = new BufferedReader(new InputStreamReader(System.in));
try
{
upgrade = upgrade1.readLine();
}
catch (IOException e) {
System.out.println("Error!");
System.exit(1);
}
int adult = Integer.parseInt(adult2);
int child = Integer.parseInt(child2);
int senior = Integer.parseInt(senior2);
int total_a = adult * get_price(day_of_week, "adult");
int total_c = child * get_price(day_of_week, "child");
int total_s = senior * get_price(day_of_week, "senior");
int total_price = total_a + total_c + total_s;
int total_people = adult + child + senior;
int upgrade_price = 0;
if (upgrade.equals("Y"))
{
if (day_of_week.equals("WD"))
{
upgrade_price = total_people * 30;
}
else
{
upgrade_price = total_people * 68;
}
}
else
upgrade_price = 0;
int price = upgrade_price + total_price;
System.out.println("The total price is $" + price);
}}

for equality condition in string you need equal method.
use
"Y".equals(upgrade); //is a good idea
instead of
upgrade == "Y"
Since Strings are objects, the equals(Object) method will return true if two Strings have the same objects. The == operator will only be true if two String references point to the same underlying String object. Hence two Strings representing the same content will be equal when tested by the equals(Object) method, but will only by equal when tested with the == operator if they are actually the same object.
refer http://blog.enrii.com/2006/03/15/java-string-equality-common-mistake/

I notised that your update variable is String, thus you should use:
if (upgrade.compareTo("Y") == 0) {
//your code
}
this is the correct way to compare Strings.

Related

Importing from text file into Java Array

Currently I am trying to import data from a text file regarding pets and doctors, and sending it to my "petArray" and "doctorArray".
I am extremely new to Java and as such am having great difficulty. This is what ive attempted to do, but it doesnt seem too work.
Please see attached Java code and text file (screenshot at link).
public void readFile() {
String fileName = "VetManagement.txt";
Scanner inputStream = null;
try {
inputStream = new Scanner(new File(fileName));
} catch (FileNotFoundException e) {
System.out.println("Error opening file: " + fileName);
System.exit(0);
}
while (inputStream.hasNextLine()) {
String line = inputStream.nextLine();
String initName = "";
String initSize = "";
String initType = "";
String initDoctor = "";
double initWeight = 0.0;
int initAge = 0;
if (line.equals("Pets")) {
inputStream.nextLine();
if (line.equals("type cat")) {
initType = "cat";
System.out.print(initType);
} else if (line.equals("type dog")) {
initType = "dog";
System.out.print(initType);
}
inputStream.nextLine();
if (line.equals("size small")) {
initSize = "small";
} else if (line.equals("size medium")) {
initSize = "medium";
} else if (line.equals("size large")) {
initSize = "large";
} else System.out.println("error");
inputStream.nextLine();
if (line.startsWith("name")) {
initName = inputStream.next();
} else {
System.out.println("error");
}
inputStream.nextLine();
if (line.startsWith("weight")) {
initWeight = inputStream.nextDouble();
} else {
System.out.println("error");
}
inputStream.nextLine();
if (line.startsWith("age")) {
initAge = inputStream.nextInt();
} else {
System.out.println("error");
}
inputStream.nextLine();
if (line.startsWith("doctor")) {
initDoctor = inputStream.toString();
} else {
System.out.println("error");
}
petArray[sumPets] = new Pet();
petArray[sumPets].setType(initType);
petArray[sumPets].setSize(initSize);
petArray[sumPets].setName(initName);
petArray[sumPets].setWeight(initWeight);
petArray[sumPets].setAge(initAge);
petArray[sumPets].setDoctorName(initDoctor);
} else if (line.equals("Doctors")) ;
}
inputStream.close();
}
TEXT FILE:
Pets
type cat
size small
name Lara
weight 4
age 5
doctor Joao
type dog
size large
name Biro
weight 15
age 12
doctor Maria
type cat
size large
name Benny
weight 7
age 10
doctor no doctor assigned
Doctors
name Joao
specialisation cat
name Maria
specialisation dog
nextLine can solve the problem easily no need to over-complicate the work
As the TEXT FILE contains information in format like
type cat
size small
name Lara
weight 4
age 5
doctor Joao
You can easily store information in desired variable using
nextLine = inputStream.nextLine().split(" ");
where nextLine[0] represent first column and nextLine[1] represent second column
I Hope this helps let me know if you have any other problem here is FULL CODE (in case you need)
public static void readFile() {
String fileName = "F:\\document\\eclipse\\JavaAZ\\src\\VetManagement.txt";
Scanner inputStream = null;
try {
inputStream = new Scanner(new File(fileName));
} catch (FileNotFoundException e) {
System.out.println("Error opening file: " + fileName);
System.exit(0);
}
String[] name = new String[100];
String[] size = new String[100];
String[] type = new String[100];
String[] doctor = new String[100];
double[] weight = new double[100];
int[] age = new int[100];
if (inputStream.hasNextLine()) {
String[] nextLine = inputStream.nextLine().split(" ");
int petCounter = 0;
int doctorCounter = 0;
String workingArray = new String(nextLine[0]);
while(inputStream.hasNextLine()) {
if(workingArray.equals("Pets")) {
nextLine = inputStream.nextLine().split(" ");
if (nextLine[0].equals("Doctors")) {
workingArray = "Doctors";
continue;
}
if (nextLine[0].equals("type")) {
type[petCounter] = nextLine[1];
//System.out.println(type);
}
else System.out.println("type error");
nextLine = inputStream.nextLine().split(" ");
if (nextLine[0].equals("size")) {
size[petCounter] = nextLine[1];
//System.out.println(size);
}
else System.out.println("size error");
nextLine = inputStream.nextLine().split(" ");
if (nextLine[0].equals("name")) {
name[petCounter] = nextLine[1];
//System.out.println(name);
}
else System.out.println("name error");
nextLine = inputStream.nextLine().split(" ");
if (nextLine[0].equals("weight")) {
weight[petCounter] = Double.parseDouble(nextLine[1]);
//System.out.println(weight);
}
else System.out.println("weight error");
nextLine = inputStream.nextLine().split(" ");
if (nextLine[0].equals("age")) {
age[petCounter] = Integer.parseInt(nextLine[1]);
//System.out.println(age);
}
else System.out.println("age error");
nextLine = inputStream.nextLine().split(" ");
if (nextLine[0].equals("doctor")) {
doctor[petCounter] = nextLine[1];
//System.out.println(doctor);
}
else System.out.println("doctor error");
petCounter++;
}
else if(workingArray.equals("Doctors")) {
// CODE HERE
doctorCounter++;
break;
}
}
}
System.out.println("PET NAME: "+name[0]+" and its Weight: "+weight[0]);
inputStream.close();
}
if (line.equals("Pets")) {
String nextLine = inputStream.nextLine();
if (nextLine.equals("type cat")) {
initType = "cat";
System.out.print(initType);
}
else if (nextLine.equals("type dog")) {
initType = "dog";
System.out.print(initType);
}
String lineAfterThat=inputStream.nextLine();
You have to store every line before you can do anything with that.
You are assuming that inputStream.nextLine() reads the same line again and again, but each time you use inputStream.nextLine() it reads the next line of the file and reaches the end of the file eventually. That's what is wrong.
You're not understanding the way Scanner works
Use this:
if (line.equals("Pets")) {
String nextLine = inputStream.nextLine();
if (nextLine.equals("type cat")) {
initType = "cat";
System.out.print(initType);
}
else if (nextLine.equals("type dog")) {
initType = "dog";
System.out.print(initType);
}
String lineAfterThat=inputStream.nextLine();
if (lineAfterThat.equals("size small")) {
initSize = "small";
} else if (lineAfterThat.equals("size medium")) {
initSize = "medium";
} else if (lineAfterThat.equals("size large")) {
initSize = "large";
} else System.out.println("error");
String nextFirstWord=inputStream.next(); //so that it reads only till the space
if (nextFirstWord.equals("name")) {
initName = inputStream.nextLine();
} else {
System.out.println("error");
}
String ageLineFirstWord = inputStream.next();
if (ageLineFirstWord .equals("age")) {
initAge =inputStream.nextInt();
} else {
System.out.println("error");
}
inputStream.nextLine(); //this is to move the scanner to the nextline
String doctorLineFirstWord = inputStream.next();
if (doctorLineFirstWord .equals("doctor")) {
initDoctor = inputStream.nextLine();
} else {
System.out.println("error");
}

Read and write an ArrayList to a .txt file

I can't get this part of my project to work. (fileOut() and fileIn() methods). I would appreciate any help!
I am trying to construct a method to open a text file and to write the details of an ArrayList of type to it.
I am also trying to construct a second method to open the text file containing details of all the bank’s accounts and uses the incoming data to create BankAccount objects using a BankAccount Constructor and storing each account in an ArrayList.
Please note that other methods in the class need to use the information stored in the arraylist(s).
Here is the main bit of code to focus on(reading and writing):
public void fileOut()
{
File fileName = new File("BankAccountFiles.txt");
try{
FileWriter fw = new FileWriter(fileName);
Writer output = new BufferedWriter(fw);
int numEntries = bankAccArrayList.size();
for (int i = 0; i < numEntries; i++) {
output.write(bankAccArrayList.get(i).toString() + "\n");
}
output.close();
}
catch(Exception e) {
JOptionPane.showMessageDialog(null,"File cannot be created");
}
}
public void fileIn()
{
ArrayList<BankAccount> aList = new ArrayList<BankAccount>();
String line;
try {
BufferedReader input = new BufferedReader(new FileReader("BankAccountFiles.txt"));
if(!input.ready()) {
throw new IOException();
}
while ((line = input.readLine()) != null) {
aList.add(line);
}
input.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(null,e);
}
}
Here is the code for the whole class:
import javax.swing.JOptionPane;
import java.util.ArrayList;
import java.io.*;
import java.lang.*;
import java.util.*;
import javax.swing.*;
public class MyBankController
{
private ArrayList<BankAccount> bankAccArrayList;
public MyBankController()
{
bankAccArrayList = new ArrayList<BankAccount>();
}
public void createAccount (String accNum, String custName)
{
bankAccArrayList.add(new BankAccount( accNum,custName));
printAccountDetails(bankAccArrayList.get(bankAccArrayList.size()-1));
}
private void printAccountDetails(BankAccount incomingAcc)
{
JOptionPane.showMessageDialog(null,incomingAcc.toString(),"Account Details",JOptionPane.PLAIN_MESSAGE);
}
public void listAllAccounts()
{
String outputStr = "List of all accounts :\n\n";
for(BankAccount account : bankAccArrayList){
outputStr += account + "\n\n";
}
JOptionPane.showMessageDialog(null,outputStr,"List of all Accounts",JOptionPane.PLAIN_MESSAGE);
}
public void listAllActiveAccounts()
{
String outputStr = "List of all active accounts :\n\n";
for(BankAccount account : bankAccArrayList){
if(account.getActive()) {
outputStr += account + "\n\n";
}
}
JOptionPane.showMessageDialog(null,outputStr,"List of all Active Accounts",JOptionPane.PLAIN_MESSAGE);
}
private int getIndex(String bankAccNum)
{
for (int i = 0; i < bankAccArrayList.size(); i++) {
if (bankAccNum.equals(bankAccArrayList.get(i).getAccNumber()))
{
return i;
}
}
JOptionPane.showMessageDialog(null,"Bank Account Number: " + bankAccNum + " is invalid","Error wrong account number",JOptionPane.ERROR_MESSAGE);
return -1;
}
public void makeWithdrawal(String accNumber, double amount)
{
if(getIndex(accNumber) != -1){
bankAccArrayList.get(getIndex(accNumber)).makeWithdraw(amount);
}
}
public void makeLodgement(String accNumber, double amount)
{
if(getIndex(accNumber) != -1){
bankAccArrayList.get(getIndex(accNumber)).makeLodgement(amount);
}
}
public void displayAccount(String accNumber)
{
if(getIndex(accNumber) != -1){
JOptionPane.showMessageDialog(null,(bankAccArrayList.get(getIndex(accNumber)).toString()),"Accounts Details",JOptionPane.PLAIN_MESSAGE);
}
}
public void closeAccount(String accNumber)
{
if(getIndex(accNumber) != -1){
bankAccArrayList.get(getIndex(accNumber)).closeAccount();
}
}
public void removeAccount(String accNumber)
{
int index = getIndex(accNumber);
if(index != -1){
BankAccount myAcc = bankAccArrayList.get(index);
if ((myAcc.getActive() == false) && (myAcc.getAccBalance() == 0)){
bankAccArrayList.remove(index);
}else if((myAcc.getActive() == false) && (myAcc.getAccBalance() > 0)){
int dialogResult = JOptionPane.showConfirmDialog(null," This account has a balance,do you wish to withdraw this balance " +
"so as to remove the account ?"," Balance in inactive account",JOptionPane.PLAIN_MESSAGE);
if(dialogResult == JOptionPane.YES_OPTION){
myAcc.setActive();
myAcc.makeWithdraw(myAcc.getAccBalance());
myAcc.setActive();
bankAccArrayList.remove(index);
JOptionPane.showMessageDialog(null,"Account Removed","Confirmation",JOptionPane.PLAIN_MESSAGE);
}
} else if((myAcc.getActive() == true) && (myAcc.getAccBalance() == 0)){
int dialogResult = JOptionPane.showConfirmDialog(null," This account still has an active status, do you wish to change its status so as to remove account ?"
,"Account Active",JOptionPane.PLAIN_MESSAGE);
if(dialogResult == JOptionPane.YES_OPTION){
myAcc.setActive();
bankAccArrayList.remove(index);
JOptionPane.showMessageDialog(null,"Account Removed","Confirmation",JOptionPane.PLAIN_MESSAGE);
}
} else{
int dialogResult = JOptionPane.showConfirmDialog(null," This account still has an active status and a balance, do you wish to close the account so as remove it"
,"Account Active with Balance",JOptionPane.PLAIN_MESSAGE);
if(dialogResult == JOptionPane.YES_OPTION){
myAcc.closeAccount();
bankAccArrayList.remove(index);
JOptionPane.showMessageDialog(null,"Account Removed","Confirmation",JOptionPane.PLAIN_MESSAGE);
}
}
}
}
public void customerInterface()
{
String accNumber = JOptionPane.showInputDialog(null,"Please enter your account number","Account Login",JOptionPane.PLAIN_MESSAGE);
if(getIndex(accNumber) != -1)
{
String numOption = JOptionPane.showInputDialog(null,"Please select an option below:\n\n" +
" [1] Make a lodgment:\n\n [2] Make a withdrawal:\n\n [3] Display account details:\n\n" +
" [4] Close account:\n\n [5] Exit","MyBank ATM",JOptionPane.PLAIN_MESSAGE);
if (numOption == null) //User presses cancel or 'x'.
{
JOptionPane.showMessageDialog(null,"Goodbye.","MyBank System",JOptionPane.INFORMATION_MESSAGE);
}
else if(Integer.parseInt(numOption) == 1) //Converts numOption from String to Integer.
{
//Brings up lodgement interface
String amount = JOptionPane.showInputDialog("Please enter the amount you would like to lodge.");
makeLodgement(accNumber, Double.parseDouble(amount)); // Lodges amount into account.
customerInterface();
}
else if(Integer.parseInt(numOption) == 2)
{
String amount = JOptionPane.showInputDialog("Please enter the amount you wish to withdraw.");
makeWithdrawal(accNumber, Double.parseDouble(amount)); //Call on makeWithdrawl method.
customerInterface();
}
else if(Integer.parseInt(numOption) == 3)
{
displayAccount(accNumber); //Calls on displayAccount method.
customerInterface();
}
else if(Integer.parseInt(numOption) == 4)
{
closeAccount(accNumber); //Call on close account method.
customerInterface();
}
else if(Integer.parseInt(numOption) == 5)
{
return; //Exits system.
}
else if(Integer.parseInt(numOption) > 5 || Integer.parseInt(numOption) < 1) //If number enter is outside of 1-5.
{
JOptionPane.showMessageDialog(null,"Please enter a number between 1-5 and try again.","Error",JOptionPane.ERROR_MESSAGE);
customerInterface();
}
}
}
public void bankInterface()
{
String numOption = JOptionPane.showInputDialog(null,"Please select an option below:\n\n" +
" [1] Display All Accounts:\n\n [2] Display All Active Accounts:\n\n [3] Open a New Account:\n\n" +
" [4] Close an Existing Account:\n\n [5] Run Start of Day:\n\n [6] Run End of Day:\n\n [7] Exit:","MyBank System",JOptionPane.PLAIN_MESSAGE);
if (numOption == null)
{
JOptionPane.showMessageDialog(null,"Goodbye.","MyBank System",JOptionPane.INFORMATION_MESSAGE); //User presses cancel or 'x'.
}
else if(Integer.parseInt(numOption) == 1) //Converts numOption from String to Integer.
{
//Displays all accounts.
listAllAccounts();
bankInterface();
}
else if(Integer.parseInt(numOption) == 2)
{
//Display all active accounts.
listAllActiveAccounts();
bankInterface();
}
else if(Integer.parseInt(numOption) == 3)
{
//Open a new account
String accNum = JOptionPane.showInputDialog("Please allocate an account number:");
String custName = JOptionPane.showInputDialog("Please enter the customers name:");
createAccount (accNum, custName);
bankInterface();
}
else if(Integer.parseInt(numOption) == 4)
{
//Close an existing account.
String accNumber = JOptionPane.showInputDialog("Please enter the account number you would like to close:");
closeAccount(accNumber);
bankInterface();
}
else if(Integer.parseInt(numOption) == 5)
{
//Run start of day file.
fileIn();
bankInterface();
}
else if(Integer.parseInt(numOption) == 6)
{
//Run end of day file.
fileOut();
bankInterface();
}
else if(Integer.parseInt(numOption) == 7)
{
//Exits system.
return;
}
else if(Integer.parseInt(numOption) > 7 ||Integer.parseInt(numOption) < 1) //If user enters number outside of 1-7.
{
JOptionPane.showMessageDialog(null,"Please enter a number between 1-7 and try again.","Error",JOptionPane.ERROR_MESSAGE);
bankInterface();
}
}
public void fileOut()
{
File fileName = new File("BankAccountFiles.txt");
try{
FileWriter fw = new FileWriter(fileName);
Writer output = new BufferedWriter(fw);
int numEntries = bankAccArrayList.size();
for (int i = 0; i < numEntries; i++) {
output.write(bankAccArrayList.get(i).toString() + "\n");
}
output.close();
}
catch(Exception e) {
JOptionPane.showMessageDialog(null,"File cannot be created");
}
}
public void fileIn()
{
ArrayList<BankAccount> aList = new ArrayList<BankAccount>();
String line;
try {
BufferedReader input = new BufferedReader(new FileReader("BankAccountFiles.txt"));
if(!input.ready()) {
throw new IOException();
}
while ((line = input.readLine()) != null) {
aList.add(line);
}
input.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(null,e);
}
}
}
In your fileIn method, you're trying to add a String to an ArrayList of type BankAccount. Instead of aList.add(line), you should use aList.add(new BankAccount(line)).
Assuming your BankAccount constructor takes only a single String parameter, this should work.
Full method:
public void fileIn()
{
List<BankAccount> aList = new ArrayList<BankAccount>();
String line;
try {
BufferedReader input = new BufferedReader(new FileReader("BankAccountFiles.txt"));
if(!input.ready()) {
throw new IOException();
}
while ((line = input.readLine()) != null) {
aList.add(new BankAccount(line));
}
input.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(null,e);
}
aList.forEach(System.out::println); // Java8
}
I've also changed your aList to use the List interface, and added a lambda to print each value in aList at the end.

After 1st try to save data and cant open after close the program

public class internetCalculator extends javax.swing.JFrame {
ArrayList<User> list = new ArrayList<User>();
public internetCalculator() throws IOException {
initComponents();
loadDataFromFile();
jPanel1.hide();
mainMenuJ.show(true);
}
public void saveDataToFile() throws IOException {
//Below is Internet Plan, D for DIGI, M for Maxis....
double D = 0.05, M = 0.10, C = 0.02, R1 = 0.12;
double total = 0, tax = 0; //Plan Tax Rate Per MB
double normal = 30.0, pro = 45.0, superPro = 65.0, ultra = 90;//Package
try {
String name = nameTF.getText();
String phNo = phNoTF.getText();
String usage = usageTF.getText();
String bPlan = planCB.getSelectedItem().toString();
String bPackage = packageCB.getSelectedItem().toString();
double internetUsage = Double.parseDouble(usage);
//First Calculation ***PLAN***
if (planCB.getSelectedItem().toString().equals("Digi Plan")) {
total = internetUsage * D;
} else if (planCB.getSelectedItem().toString().equals("Maxis Plan")) {
total = internetUsage * M;
} else if (planCB.getSelectedItem().toString().equals("Celcom Plan")) {
total = internetUsage * C;
} else if (planCB.getSelectedItem().toString().equals("Red1 Plan")) {
total = internetUsage * R1;
}
if (packageCB.getSelectedItem().toString().equals("Normal")) {
tax = total + normal;
} else if (packageCB.getSelectedItem().toString().equals("Pro")) {
tax = total + pro;
} else if (packageCB.getSelectedItem().toString().equals("SuperPro")) {
tax = total + superPro;
} else if (packageCB.getSelectedItem().toString().equals("UltraHighSpeed")) {
tax = total + ultra;
}
User users = new User(name, phNo, bPlan, bPackage, tax);
list.add(users); //add object s to array
File outFile = new File("Internet_Tax.txt");
FileWriter outFileStream = new FileWriter(outFile, true);
PrintWriter outStream = new PrintWriter(outFileStream);
outStream.println(name);
outStream.println(phNo);
outStream.println(bPlan);
outStream.println(bPackage);
outStream.println(tax);
outStream.close();
//If User Didnt Choose any Plan and Package , Display Error
if ((packageCB.getSelectedItem().toString().equals("Select"))
|| (planCB.getSelectedItem().toString().equals("Select"))) {
throw new Exception("Please Select PLAN or PACKAGE to Perform Calculation !");
}
if (!name.matches("[a-zA-Z]+")) {
throw new Exception("Name With Letter with A - Z ONLY !");
}// name with only Letter
if (!phNo.matches("[0-9]+")) {
throw new Exception("Phone Number with DIGIT number ONLY! ");
}//Phone number only DIGIT
if (!usage.matches("[0-9]+")) {
throw new Exception("Internet Usage with DIGIT number ONLY! ");
}//Internet Usage only DIGIT
} catch (Exception e) {
outputTA.setText(e.getMessage());
}
}//End Save Data To File
public void loadDataFromFile() throws FileNotFoundException, IOException {
File inFile = new File("Internet_Tax.txt");
if (inFile.exists()) {
FileReader fileReader = new FileReader(inFile);
Scanner scanner = new Scanner(inFile);
list.clear();
DefaultTableModel stable = new DefaultTableModel(0, 0);
String header[] = new String[]{"Name", "Phone", "Plan","Package","Total_Tax"};
stable.setColumnIdentifiers(header);
tableT.setModel(stable);
while (scanner.hasNextLine()) {
String name = scanner.nextLine();
String phNo = scanner.nextLine();
String bPlan = scanner.nextLine();
String bPackage = scanner.nextLine();
double tax = scanner.nextDouble();
User users = new User(name, phNo, bPlan, bPackage, tax);
stable.addRow(new Object[]{name, phNo, bPlan, bPackage, tax});
list.add(users);
}
scanner.close();
fileReader.close();
nameTF.setText(""); // name
phNoTF.setText(""); // matric
usageTF.setText(""); // Phone
planCB.setSelectedItem("Select");
packageCB.setSelectedItem("Select");
} else {
DefaultTableModel stable = new DefaultTableModel(0, 0);
String header[] = new String[]{"Name", "Phone", "Plan","Package","Total_Tax"};
stable.setColumnIdentifiers(header);
tableT.setModel(stable);
}
}
During the first try of running this program, the program seems to run well and display the data in table. After I close the program and run the program again, it displays errors. I don't know what is the error inside my code. The Exception error show on the loadDataFromFile():
I think this way will show you where is the problem..
Put your scanning codes in to try catch and add a condition before getting double value.
For example :
while (scanner.hasNextLine()) {
try {
String name = scanner.nextLine();
String phNo = scanner.nextLine();
String bPlan = scanner.nextLine();
String bPackage = scanner.nextLine();
if(scanner.hasNextDouble()){
double tax = scanner.nextDouble();
}else{System.out.println("Value is not Double!")}
} catch (Exception e) {
System.out.println("WARNING : " + e.getMessage());
}finally {
scanner.close();
User users = new User(name, phNo, bPlan, bPackage, tax);
stable.addRow(new Object[]{name, phNo, bPlan, bPackage, tax});
list.add(users);
}
}

Java creating a temp file , deleting a specific string and rename to original

As the topic states im trying to get a specific string that is usually auto generated into the same string and it seems to work because the temp file is created and the string is replaced with "" but its seems that there is an IOException when it comes to renaming to original when deleting , help please?
import java.io.*;
import java.util.Scanner;
/**
* Main class to test the Road and Settlement classes
*
* #author Chris Loftus (add your name and change version number/date)
* #version 1.0 (24th February 2016)
*
*/
public class Application {
private Scanner scan;
private Map map;
private static int setting;
public Application() {
scan = new Scanner(System.in);
map = new Map();
}
private void runMenu() {
setting = scan.nextInt();
scan.nextLine();
}
// STEP 1: ADD PRIVATE UTILITY MENTHODS HERE. askForRoadClassifier, save and
// load provided
private Classification askForRoadClassifier() {
Classification result = null;
boolean valid;
do {
valid = false;
System.out.print("Enter a road classification: ");
for (Classification cls : Classification.values()) {
System.out.print(cls + " ");
}
String choice = scan.nextLine().toUpperCase();
try {
result = Classification.valueOf(choice);
valid = true;
} catch (IllegalArgumentException iae) {
System.out.println(choice + " is not one of the options. Try again.");
}
} while (!valid);
return result;
}
private void deleteSettlement() {
String name;
int p;
SettlementType newSetK = SettlementType.CITY;
int set;
System.out.println("Please type in the name of the settlement");
name = scan.nextLine();
System.out.println("Please type in the population of the settlment");
p = scan.nextInt();
scan.nextLine();
System.out.println("Please type in the number of the type of settlement .");
System.out.println("1: Hamlet");
System.out.println("2: Village");
System.out.println("3: Town");
System.out.println("4: City");
set = scan.nextInt();
scan.nextLine();
if (set == 1) {
newSetK = SettlementType.HAMLET;
}
if (set == 2) {
newSetK = SettlementType.VILLAGE;
}
if (set == 3) {
newSetK = SettlementType.TOWN;
}
if (set == 4) {
newSetK = SettlementType.CITY;
}
String generatedResult = "Name: " + name + " Population: " + p + " SettlementType " + newSetK;
String status = searchAndDestroy(generatedResult);
}
private String searchAndDestroy(String delete) {
File file = new File("C:\\Users\\Pikachu\\workspace\\MiniAssignment2\\settlements.txt");
try {
File temp = File.createTempFile("settlement", ".txt", file.getParentFile());
String charset = "UTF-8";
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(temp), charset));
for (String line; (line = reader.readLine()) != null;) {
line = line.replace(delete, "");
writer.println(line);
}
System.out.println("Deletion complete");
reader.close();
writer.close();
file.delete();
temp.renameTo(file);
}
catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
System.out.println("Sorry! Can't do that! 1");
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("Sorry! Can't do that! 2");
}
}
catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Sorry! Can't do that! , IO Exception error incurred 3");
}
return null;
}
private void save() {
map.save();
}
private void load() {
map.load();
}
public void addSettlement() {
String name;
int p;
SettlementType newSetK = SettlementType.CITY;
int set;
System.out.println("Please type in the name of the settlement");
name = scan.nextLine();
System.out.println("Please type in the population of the settlment");
p = scan.nextInt();
scan.nextLine();
System.out.println("Please type in the number of the type of settlement .");
System.out.println("1: Hamlet");
System.out.println("2: Village");
System.out.println("3: Town");
System.out.println("4: City");
set = scan.nextInt();
scan.nextLine();
if (set == 1) {
newSetK = SettlementType.HAMLET;
}
if (set == 2) {
newSetK = SettlementType.VILLAGE;
}
if (set == 3) {
newSetK = SettlementType.TOWN;
}
if (set == 4) {
newSetK = SettlementType.CITY;
}
new Settlement(name, newSetK, p);
}
private void printMenu() {
System.out.println("Please type in the number of the action that you would like to perform");
System.out.println("1: Create Settlement");
System.out.println("2: Delete Settlement");
System.out.println("3: Create Road");
System.out.println("4: Delete Road");
System.out.println("5:Display Map");
System.out.println("6:Save Map");
}
public static void main(String args[]) {
Application app = new Application();
app.printMenu();
app.runMenu();
System.out.println(setting);
if (setting == 1) {
app.addSettlement();
}
if (setting == 2) {
app.deleteSettlement();
}
app.load();
app.runMenu();
app.save();
}
}
I checked if it was deletable (file.delete throws a boolean exception) so I tried deleting it directly via windows and apparently it was being used by java so I assumed eclipsed glitch and upon closing and booting up eclipse again it worked..... well... that was rather anti-climactic .... Thank you so much for the discussion , I would definitely never had figured it out if not for the discussion :D <3 You are all in my heart

Why does a integer, after put into an array, change values?

SOLVED IT
I've written a program that loads Strings after an equal sign, and has it count how many times its done this. After counting, I tell it to tell me how large the int is. The value I'm looking for is 3, and it tells me, 3. I then change it to an String, the value stays three. Then, I put it into an 4d array, and It tells me the value is 2. What happened?
The Code:
int times=0;
else if (list.equals("Weapon")) {//If the word weapon is before the =
weapon = value; //take the string after the = and put it into String weapon
troopStats[times][1][weaponTimes][0] = weapon;
weaponTimes++;
System.out.println(weaponTimes+"weapontimes"+times);
}
weaponTimesStr = Integer.toString(weaponTimes);
System.out.println(weaponTimesStr+"string");
troopStats[times][1][0][1] = weaponTimesStr;
System.out.println(troopStats[times][1][0][1]+"InArray");
times++
//loops
The Output:
3weapontimes //Counted the equals sign 3 times, Note that this is from the part of the
omitted code
3string // Changed the integer to a string and got 3
2InArray // Put it into an array, and got 2 back
What Is going on?
(I know that I could just add 1 to the value, but I want to use this code for a unknown number of things later on)
To help, I've posted the entire code:
public class TroopLoader {
static String[][][][] troopStats;
static int times = 0;
static int weaponTimes = 0;
static int armorTimes = 0;
static int animalTimes = 0;
static String weaponTimesStr;
static String armorTimesStr;
static String animalTimesStr;
static String troop;
static String weapon;
static String armor;
static String animal;
static String speed;
static int total = 0;
/*
* [][][]
*
* [total number of troops (total)]
*
* [stats] 0= name 1= weapon 2= armor 3= animal 4= speed
*
* [different things within stat]
*/
public void readTroop() {
File file = new File("resources/objects/troops.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
// repeat until all lines is read
while ((text = reader.readLine()) != null) {
StringTokenizer troops = new StringTokenizer(text, "=");
if (troops.countTokens() == 2) {
String list = troops.nextToken();
if (list.equals("Troop")) {
total++;
}
else {
}
} else {
}
}
troopStats = new String[total][5][10][2];
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
File file2 = new File("resources/objects/troops.txt");
BufferedReader reader2 = null;
try {
reader2 = new BufferedReader(new FileReader(file2));
String text = null;
// repeat until all lines is read
while ((text = reader2.readLine()) != null) {
StringTokenizer troops = new StringTokenizer(text, "=");
if (troops.countTokens() == 2) {
String list = troops.nextToken();
String value = troops.nextToken();
if (list.equals("Troop")) {
troop = value;
troopStats[times][0][0][0] = troop;
}
else if (list.equals("Weapon")) {
weapon = value;
troopStats[times][1][weaponTimes][0] = weapon;
weaponTimes++;
System.out.println(weaponTimes+"weapontimes"+times);
}
else if (list.equals("Armor")) {
armor = value;
troopStats[times][2][armorTimes][0] = armor;
armorTimes++;
}
else if (list.equals("Animal")) {
animal = value;
troopStats[times][3][animalTimes][0] = animal;
animalTimes++;
}
else if (list.equals("Speed")) {
speed = value;
troopStats[times][4][0][0] = speed;
}
else if (list.equals("Done")) {
weaponTimesStr = Integer.toString(weaponTimes);
System.out.println(weaponTimesStr+"string");
armorTimesStr = Integer.toString(armorTimes);
animalTimesStr = Integer.toString(animalTimes);
troopStats[times][1][0][1] = weaponTimesStr;
troopStats[times][1][0][1] = armorTimesStr;
troopStats[times][1][0][1] = animalTimesStr;
System.out.println(troopStats[times][1][0][1]+"InArray"+times);
times++;
troop = "";
weapon = "";
armor = "";
animal = "";
speed = "";
weaponTimes = 0;
armorTimes = 0;
animalTimes = 0;
}
else {
}
} else {
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
if (reader2 != null) {
reader2.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
In the earlier part of the code, I had the program store a value in the location on the array with the weaponTimes variable, not storing the weaponTimes variable. My mistake, sorry for wasting your time.
I wrote a SSCCE with what you posted and it prints what you would expect:
public static void main(String[] args) {
String[][][][] troopStats = new String[4][4][4][4];
int times = 2;
int weaponTimes = 3;
String weaponTimesStr = Integer.toString(weaponTimes);
System.out.println(weaponTimesStr + "string"); //prints 3string
troopStats[times][1][0][1] = weaponTimesStr;
System.out.println(troopStats[times][1][0][1] + "InArray"); //prints 3InArray
}
So the problem is most likely something/somewhere else.
The following:
public class Foo {
public static void main(String[] args) {
String[][][][] troopStats = new String[2][2][2][2];
String weaponTimesStr = Integer.toString(3);
System.out.println(weaponTimesStr+"string");
troopStats[0][1][0][1] = weaponTimesStr;
// You said in a comment that 'times' is equal to 0 in this case so have subbed that in
System.out.println(troopStats[0][1][0][1]+"InArray");
}
}
Gives me the expected output:
3string
3InArray
Sorry I've wasted your time, my mistake was because I stored values in the array using the values of weaponTimes, and not storing weaponTimes in the array.
troopStats[times][1][weaponTimes][0] = weapon;
That was the mistake.

Categories