Updating a double in a text file - java

I have an ArrayList with user accounts stored into a text file, each account represents a virtual bank account.
What is the most efficient way for me to update the balance of an account, after a user decides to add, or withdraw money?
I have successfully retrieved the balance, just need to save it.
Here is what I have so far, most of the magic happens in the ATM and Bank classes
ATM CLASS
public class ATM {
public static void main(String[] args) throws IOException {
Bank bank = new Bank();
double balance = 0;
// Welcome screen
String dash = "-------------------\n";
System.out.print(dash);
System.out.print("Welcome to the Bank\n");
System.out.print(dash);
System.out.println("Do you have an account with us? (y/n) ");
Scanner scanner = new Scanner(System.in);
String answer = scanner.nextLine();
while (true) {
if (answer.equalsIgnoreCase("y")) {
System.out.println("Username: ");
String userName = scanner.next();
System.out.println("PIN: ");
int pin = scanner.nextInt();
bank.hasUser(userName, pin);
if (bank.hasUser(userName, pin)) {
User.balance = bank.getBalance(userName, pin, balance);
bank.menu();
break;
} else if (!bank.hasUser(userName, pin)) {
System.out.println("\n** Incorrect username or password, please try again**\n");
}
} else if (answer.equalsIgnoreCase("n")) {
Bank.newUser();
break;
} else {
System.out.println("\nThat's not an option, do you have an account with us?");
}
}
}
}
BANK CLASS
public class Bank {
public static void newUser() {
// new user is created
String dash = "-------------------\n";
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your full name below (e.g. John M Smith): ");
String name = scanner.nextLine();
System.out.println("Create a username: ");
String userName = scanner.nextLine();
System.out.println("Enter your starting deposit amount: ");
double balance = scanner.nextDouble();
System.out.print(dash);
System.out.print("Generating your information...\n");
System.out.print(dash);
int pin = PIN();
String accountNum = Bank.accountNum();
User user = new User(name, userName, pin, accountNum, balance);
// new user gets added to the array list
Bank.users.add(user);
try {
File file = new File("users.text");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
bw.append(String.valueOf(Bank.users + "\n"));
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void menu() {
while (true) {
System.out.print("\n1");
System.out.print(" - Acount Summary ");
System.out.print("3");
System.out.print(" - Deposit Money\n");
System.out.print("2");
System.out.print(" - Withdraw Money ");
System.out.print("4");
System.out.print(" - Exit\n\n");
System.out.print("I would like to: \n");
Scanner bscanner = new Scanner(System.in);
int mc = bscanner.nextInt();
if (mc == 1) {
System.out.print("Your current balance is: $"
+ User.getBalance() + "\n");
} else if (mc == 2) {
System.out.print("Enter withdrawl amount: ");
double wd = bscanner.nextDouble();
User.balance -= wd;
System.out.println("\n$" + User.getBalance()
+ " is your new account balance.");
} else if (mc == 3) {
System.out.print("Enter deposit amount: ");
double dp = bscanner.nextDouble();
User.balance += dp;
System.out.println("\n$" + User.getBalance()
+ " is your new account balance.");
} else if (mc == 4) {
System.exit(0);
} else {
System.out
.print("\nThat's not an option, please select an option listed below!\n");
}
}
}
public boolean hasUser(String userName, int pin) {
try {
BufferedReader reader = new BufferedReader(new FileReader(
"users.text"));
String line;
while ((line = reader.readLine()) != null) {
line = line.replaceAll("[\\[\\]]", "");
String[] tokens = line.split(",");
if (userName.equals(tokens[1])
&& pin == Integer.parseInt(tokens[3])) {
return true;
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return false;
}
public double getBalance(String userName, int pin, double balance) {
boolean r = false;
try {
BufferedReader br = new BufferedReader(new FileReader("users.text"));
String line;
while ((line = br.readLine())!= null) {
line = line.replaceAll("[\\[\\]]", "");
String[] num = line.split(",");
if (userName.equals(num[1]) && pin == Integer.parseInt(num[3])) {
r = true;
}
if (r) {
balance = Double.parseDouble(num[4]);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return balance;
}
// array list for users
static ArrayList users = new ArrayList();
{
};
}

A good way to do this would be to keep the accounts in ArrayList (as you are doing) and then just save the whole text file again. If you are dealing with small amounts of data it would not take very long. (A better way to think about optimizing is not re-opening the file every time you need to access it's data, just keep it in an array list).
Also, you may not need to save the file after every change. If you are the only app using the file try just saving it when you get closed.
If you want really good performance you will need a data base.

You have to write to the file i dont see any of that...
File fileWriter = new File("user.txt"); //recall it or whatever
PrintWriter writer = new PrintWriter(new FileWriter(fileWriter, true)); //APPEND
writer.println(balance, name, eg...);
writer.close();
}
Printwriter is more effective than filewriter, and filewriter is needed anyhow but this will work, also if you want to do multiples people then just for loop it, and dont forget to close!
for (int i = 0; i < users; i++) { //the for loop
if you still have issues then ask again i've done dbms and the other answer is wayyy off. Hope this helps!

Related

second buffered writer won't work

I have a little problem with my simple I/O inventory program. It's a program that writes the output that the user entered into a text file that serves as an "inventory". I was able to do it. However, when I tried to create and append on a different text file on the same file folder, it wouldn't write the input into the new text file. I know I really lack the experience to explain properly my concern. But I'm trying my best though, so basically, I would just like to print the information I entered as "sales" into the second text.file on the same path folder. I hope you can get some ideas if you check and run my code. The code is working but, like I said, the only problem is the input/output on a different text file. I would really appreciate your help. Thanks.
Carl
Here's my code:
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.*;
import static java.nio.file.StandardOpenOption.*;
import java.text.*;
import java.util.*;
public class Inventorypos {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
String File ="D:\\Copro2\\Inventory.txt";
String File2 ="D:\\Copro2\\Sales.txt";
Path file = Paths.get("D:\\Copro2\\Inventory.txt");
Path salefile = Paths.get("D:\\Copro2\\Sales.txt");
String st = " ";
String sH = " ";
String sF = " ";
String sS = " ";
String delimeter = "................ ";
int itemnum;
int itemname;
String H="Hamburger";
String F="French Fries";
String S="Softdrinks";
int menu;
long menu2 = 0;
final long QUIT = 5;{
{
try{
Runtime rt=Runtime.getRuntime();
OutputStream invent = new BufferedOutputStream(Files.newOutputStream(file, CREATE));
BufferedWriter writer = new
BufferedWriter(new OutputStreamWriter(invent));
//so here is my problem here, I couldn't make this work
OutputStream sale = new BufferedOutputStream(Files.newOutputStream(salefile, CREATE,StandardOpenOption.APPEND));
BufferedWriter writer2 = new
BufferedWriter(new OutputStreamWriter(sale));
String sa= "---- Sales ----";
writer2.write(sa);
writer2.newLine();
String in= "---- Inventory ----";
writer.write(in);
writer.newLine();
System.out.println("---- Page Menu ----");
System.out.println("1. Add Inventory \n2. Sell \n3. View Inventory \n4. View Sales \n5. Exit ");
System.out.print("Enter selection: ");
menu= input.nextInt();
while(menu2 != QUIT){
if(menu==1) {
System.out.println("Add Inventory: " );
System.out.print("1.) Hamburger \n2.)French Fries \n3.)Softdrinks\n");
System.out.println("Enter Item: " );
itemname= input.nextInt();
if (itemname == 1){
System.out.print("How many do you want to store? ");
itemnum = input.nextInt();
sH = H + delimeter + itemnum;
writer.write(sH, 0, sH.length());
writer.newLine();
}
else if (itemname == 2){
System.out.print("How many do you want to store? ");
itemnum = input.nextInt();
sF = F + delimeter + itemnum;
writer.write(sF, 0, sF.length());
writer.newLine();
}
else if (itemname == 3){
System.out.print("How many do you want to store? ");
itemnum = input.nextInt();
sS = S + delimeter + itemnum;
writer.write(sS, 0, sS.length());
writer.newLine();
}
else{
System.out.println("Invalid input!");
menu=1;
}
System.out.print("Enter 1 to store another item, 2 to view inventory, 3 sell,4 to quit: ");
menu2 = input.nextLong();
if (menu2==1){
menu=1;
}
else if (menu2==2){
menu=3;
}
else if (menu2==3){
menu=6;
}
else if (menu2==4){
menu2=QUIT;
}
else{
System.out.println("Invalid Input!");
}
}
if(menu==2){
System.out.print("---- Food Menu ----");
System.out.println("\n1.) Hamburger P25 \n2.) French Fries P25 \n3.) Softdrinks P25");
System.out.println("Enter your order: ");
int ord = input.nextInt();
if (ord==1){
System.out.println("How many?");
int hm = input.nextInt();
int totph = hm*25;
/*String intwo = "---- Updated inventory ----";
writer.write(intwo);
writer.newLine();
/*int left =
String nI = H+delimeter+*/
st = H+hm+ delimeter+ totph;
writer2.write(st,0,st.length());
writer2.newLine();
System.out.println("You purchased "+hm+" "+H+"s with the total price of "+totph+".");
}
else if (ord==2){
System.out.println("How many?");
int hm = input.nextInt();
int totph = hm*25;
/*String intwo = "---- Updated inventory ----";
writer.write(intwo);
writer.newLine();
/*int left =
String nI = H+delimeter+*/
st = F + hm + delimeter + totph;
writer2.write(st, 0, st.length());
writer2.newLine();
System.out.println("You purchased "+hm+" "+F+" with the total price of "+totph+".");
}
else if (ord==3){
System.out.println("How many?");
int hm = input.nextInt();
int totph = hm*25;
/*String intwo = "---- Updated inventory ----";
writer.write(intwo);
writer.newLine();
/*int left =
String nI = H+delimeter+*/
st = S+hm+ delimeter+ totph;
writer2.write(st,0,st.length());
writer2.newLine();
System.out.println("You purchased "+hm+" "+S+"s with the total price of "+totph+".");
}
else{
System.out.println("Invalid input!");
menu=2;
}
System.out.print("Enter 1 to go back to the food menu, 2 to view sales, 3 to go back to the main option or 4 to quit: ");
menu2 = input.nextInt();
if (menu2==1){
menu=2;
}
else if (menu2==2){
menu=4;
}else if (menu2==4){
menu2=QUIT;
}
else if (menu2==3){
menu=6;
}
else{
System.out.println("Invalid Input!");
}
}
if(menu==3){
{
menu2 = QUIT;
writer.close();
Process p=rt.exec("notepad "+File);
System.out.println("Do you want to continue? y for yes, n for no");
String con = input.next();
if (con.equalsIgnoreCase("y")){
main(null);
}
else if(con.equalsIgnoreCase("n")){
menu2=QUIT;
}
}
}
if (menu==4){
{
menu2 = QUIT;
writer.close();
Process p=rt.exec("notepad "+File2);
System.out.println("Do you want to continue? y for yes, n for no");
String con = input.next();
if (con.equalsIgnoreCase("y")){
main(null);
}
else if(con.equalsIgnoreCase("n")){
menu2=QUIT;
}
}
}
if (menu==5){
System.exit(0);
}
else if (menu ==6){
main(null);
}
else{
System.out.println("Invalid Input!");
}
}
}catch (Exception e){
System.out.println("Message: " +e);
}
}
}
}
}
That's the special thing about BufferedWriter objects. To improve efficiency, they store information in "buffers" or temporary heaps of information and then when the buffer exceeds a certain size, it "flushes" the data or writes it to the file. Flushing the data is done when the flush() method or close() method is called. In your code, I don't believe you called close() on your writer which you actually do regardless of the type.
You can call it using this:
writer.close();
Or if you simply want to save the data without closing the writer yet, you can call:
writer.flush();

How to perform arithmetic operation between the objects written in a file?

In my program, users enter values and those get stored in arrayList. ArryList objects are written into a file. I have used file-i/o, object-i/o stream for writing and readin in file.Now I want to perform addition and subtraction among the objects (int or double). That is withdrawing money from one account should be added with another account, and their value must be subtracted and added with the particular acount's amount. And finally I want that value must be updated so that it can print out and show the current status. How could I do that?
This is the main class:
public class BankApp_Assignment {
//static int numOfAcc = 0;
public static void main(String[] args) {
System.out.println("WELCOME TO OUR BANK!\n\n");
List<BankAccount> bankAccounts = new ArrayList<BankAccount>();
List<BankAccount> bankAccounts2 = new ArrayList<BankAccount>();
ReaderWriter rw=new ReaderWriter();
while (true) {
System.out.println("Choose your option:\n"
+ "1. Create new account\n"
+ "2. Deposit/withdraw\n"
+ "3. View One account\n"
+ "4. Deleting an account\n"
+ "5. View all the accounts\n"
+ "6. Return to menu\n");
System.out.println("*************\n"
+ "************");
option1 = sc.nextInt();
sc.nextLine();
//switch-case starts
switch (option1) {
case 1:
//create account
BankAccount bankAcc = new BankAccount();
System.out.println("Enter Full Name:");
bankAcc.setName(sc.nextLine());
System.out.println("Choose an Account Number:");
bankAcc.setAccNum(sc.nextInt());
System.out.println("Choose the initial amount:");
bankAcc.setInitiateAmount(sc.nextDouble());
//adding those into the arrayList
bankAccounts.add(bankAcc);
rw.writeToFile(bankAccounts);
System.out.println("-------------\n"
+ "-------------");
break;
case 2:
bankAccounts2=(List<BankAccount>)rw.readFromFile();
//First displaying the current accouns info
System.out.println("Name \tAccount No \tInitial Amount");
for (BankAccount bankAccount : bankAccounts2) {
System.out.println(bankAccount);
}
System.out.println("\t\t.........\n"
+ "\t\t.........");
System.out.println("To transfer money within the bank accounts enter 1\n"
+ "To deposit/withdraw money in the same account enter 2");
option2 = sc.nextInt();
sc.nextLine();
//inner switch-case starts
switch (option2) {
case 1:
/*
BankAccount is the class for setter and getter
bankAccounts2 is the arrayList for reading objects from file
*/
bankAccounts2 = (List<BankAccount>) rw.readFromFile();
BankAccount fromAcc = null;
BankAccount toAcc = null;
System.out.println("Enter the account number you want to withdraw from:");
withdraw_accNum = sc.nextInt();
System.out.println("Enter the amount you want to withdraw:");
withdraw_amount = sc.nextDouble();
System.out.println("Enter the account number you want to deposit to:");
deposit_accNum = sc.nextInt();//the deposit amount is alwyas the same as withdraw_amount
//find the matching acc number:withdraw_accNum
for (BankAccount listItemsFirst : bankAccounts2) {
//if the withdraw acc num matches with the given one
if (listItemsFirst.getAccNum() == withdraw_accNum) {
//store it
fromAcc = listItemsFirst;
break;
}
}
//find the matching acc number: deposit_accNum
for (BankAccount listItemsSec : bankAccounts2) {
//if the withdraw acc num matches with the given one
if (listItemsSec.getAccNum() == deposit_accNum) {
//store it
toAcc = listItemsSec;
break;
}
}
//if the withdraw amount is bigger than the current balance
if (withdraw_amount > fromAcc.getInitialAmount()) {
System.out.println("Withdrawing Amount was bigger than the Initial amount.\nChoose the menu again. .");
break;
}
//subtracting and adding the withdrawn amount
fromAcc.setInitiateAmount(fromAcc.getInitialAmount() - withdraw_amount);
toAcc.setInitiateAmount(toAcc.getInitialAmount() + withdraw_amount);
System.out.println("DONE!\t print them out to see the current status.");
System.out.println("");
break;
case 2://deposit/withdraw money in the same accounts
bankAccounts2=(List<BankAccount>)rw.readFromFile();
BankAccount fromAcc_SameAcc = null;
BankAccount toAcc_SameAcc = null;
System.out.println("Enter the account number you want to deposit or withdraw from:");
//read the accNum
depOrWithAccountNum = sc.nextInt();
System.out.println("Enter the amount (To withdraw enter a negative value)");
//read the amount
depOrWithAmount = sc.nextDouble();
//checking the matching account number in arrayList
for (BankAccount listItemsThird : bankAccounts2) {
if (listItemsThird.getAccNum() == depOrWithAccountNum) {
fromAcc_SameAcc = listItemsThird;
break;
}
}
if (depOrWithAmount - 1 < fromAcc_SameAcc.getInitialAmount()) {
System.out.println("Withdraw amount is bigger than the current amount.\nChoose the menu again. .");
break;
}
if (depOrWithAmount < 0) {//the amount is negative
fromAcc_SameAcc.setInitiateAmount(fromAcc_SameAcc.getInitialAmount() + depOrWithAmount);
} else {
fromAcc_SameAcc.setInitiateAmount(fromAcc_SameAcc.getInitialAmount() + depOrWithAmount);
}
break;
}
//inner switch-case ends
System.out.println("\n\n");
break;
case 3:
//View One account
bankAccounts2=(List<BankAccount>)rw.readFromFile();
BankAccount viewOneAccountNum = null;
System.out.println("Enter the account number you want to see:");
viewOneAcc = sc.nextInt();
System.out.println("Name\tAccount No\tInitial Amount");
for (BankAccount viewOneAccountProperty : bankAccounts2) {
if (viewOneAccountProperty.getAccNum() == viewOneAcc) {
//viewOneAccountNum=viewOneAccountProperty;
viewOneAccountNum = viewOneAccountProperty;
System.out.println(viewOneAccountNum);
}
System.out.println("");
}
break;
case 4:
bankAccounts2=(List<BankAccount>)rw.readFromFile();
//BankAccount AccToDel = null;
//Deleting an account
Iterator<BankAccount> it = bankAccounts2.iterator();
System.out.println("Enter the account you want to delete:");
deleteAcc = sc.nextInt();
while (it.hasNext()) {
BankAccount next = it.next();
if (next.getAccNum() == deleteAcc) {
it.remove();
}
}
rw.writeToFile(bankAccounts2);
break;
case 5:
//View all the accounts/printing them out
bankAccounts2=(List<BankAccount>)rw.readFromFile();
System.out.println("Name\tAccount No\tInitial Amount");
for (BankAccount bankAccount : bankAccounts2) {
System.out.println(bankAccount);
}
System.out.println("\n\n");
break;
case 6:
//Quit
return;
}
//switch-case ends
}
}
}
ReaderWriter:
public class ReaderWriter{
public void writeToFile(List<BankAccount> accounts){
try {
FileOutputStream fos=new FileOutputStream("C:\\Users\\Documents\\NetBeansProjects\\BankFile_assignment.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(accounts);//take the arrayList
oos.flush();
oos.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public List<BankAccount> readFromFile(){
List<BankAccount>readData=null;
try {
FileInputStream fis=new FileInputStream("C:\\Users\Documents\\NetBeansProjects\\BankFile_assignment.txt");
ObjectInputStream ois=new ObjectInputStream(fis);
//make an arrayList to get those object back
//arrayList
readData=(List<BankAccount>)ois.readObject();
ois.close();
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
//return readData;
return readData;
}
}
BankAccount:
package bankapp_assignment;
import java.io.Serializable;
public class BankAccount implements Serializable{
private String name;
private int accNum;
private double initiateAmount;
//constructor
public BankAccount() {
this.name = null;
this.accNum = 0;
this.initiateAmount = 0;
}
public void setName(String name) {
this.name = name;
}
public void setAccNum(int accNum) {
this.accNum = accNum;
}
public String getName(String name){
return name;
}
public int getAccNum() {
return accNum;
}
public void setInitiateAmount(double initiateAmount) {
this.initiateAmount = initiateAmount;
}
public double getInitialAmount(){
return initiateAmount;
}
#Override
public String toString() {
return name + "\t\t" + accNum + "\t\t" + initiateAmount;
}
}
you should refactor whole main method. If I were you, I would use
main only to lunch program, rest process in other methods. This way you would be able to use class fields all over program, and divide code into many methods.
You should divide main beetween other methods, to at least method
per action, exemple:
case 1:
createAccount();
break;
(...)
public void createAccount(){
code from your swich case 1
}
etc. You can still use swich control, but should replece logic code to another method.
When i run your code, input/output didn't work. Were you able to
save/load file? I had to chage:
File file = new File("//file path");
FileOutputStream fos = new FileOutputStream(file);
ObjectOutput oos = new ObjectOutputStream(fos);
Same with input. Then it worked.
Now, we will try to deal with operation on BankAccounts from files. I change a little bit your code from case2/case2: deposit/withdraw, lets look at it:
bankAccounts2 = rw.readFromFile(); // loading list from file
BankAccount edited = new BankAccount(); // creating new object
System.out.println("Enter the account number you want to deposit or withdraw from:");
double input = sc.nextInt(); // you don't need to create new variable every time you take input form user
for(BankAccount account : bankAccounts2){ // every account in list
if(account.getAccNum() == input) edited = account; // if acccNum match, give edited reference to chosen account
}
System.out.println("Enter the amount (To withdraw enter a negative value)");
input = sc.nextDouble();
double result = edited.getInitialAmount() + input; // result of operation
if(result < 0){ // check if there is enough money on account
System.out.println("Withdraw amount is bigger than the current amount.\nChoose the menu again. .");
break;
}else{
edited.setInitiateAmount(result); // if there is, set new value
}
rw.writeToFile(bankAccounts2); // save file
You can implement another operation in similar style. But still, you should consider dividing main into other methods, adding class fields, etc.
EDIT:
For question in comments.
Because you use positive numbers for deposit, and negative numbers for withdraw, the operation on initialAmount will be always the same: initialAmount + input (if negative, is will subtract from amount), so you can treat it like an one case in your code. In your code you use this line twice:
fromAcc_SameAcc.setInitiateAmount(fromAcc_SameAcc.getInitialAmount() + depOrWithAmount);
so you already could merge both cases into one, to avoid unnecessary repetitions. So only case when action will differ, is when there is not enough money on a account, you check it by:
if (depOrWithAmount - 1 < fromAcc_SameAcc.getInitialAmount())
but i think i will not work, because in withdraw operation depOrWithAmount is in negative numbers, so it will always be smaller than fromAcc_SameAcc.getInitialAmount(). You can use:
if (depOrWithAmount < 1 - fromAcc_SameAcc.getInitialAmount())
(but i think it is not too readable) or:
if (Math.abs(depOrWithAmount) > fromAcc_SameAcc.getInitialAmount()){}
to compare absolute value of input with initialAmout. However i used:
double result = edited.getInitialAmount() + input;
if(result < 0){...}
because it gives me result variable, which I can reuse if there is enough money, to gives new value to initialAmount. And if result is negative, it means that withdraw amount was bigger than initialAmount, so ther is no enough monay to withdraw.
I hope you found something useful in my post.

Undetectable error in BlueJ

import java.io.*;
public class Test
{
private final String Name;
private final int AccNo;
private String AccTyp;
private double Bal;
private double BalNew;
private int c=0;
private final int x=0;
private int t;
InputStreamReader isr = new InputStreamReader (System.in);
BufferedReader br = new BufferedReader (isr);
Test()throws IOException
{
System.out.println("Enter Name:");
Name = br.readLine();
System.out.println("Enter Account Number:");
AccNo = Integer.parseInt(br.readLine());
t = AccNo;
{
while(t>0)
{
c++;
t = t/10;
}
}
if(c!=10)
{
System.out.println("Invalid Account Number!");
System.exit(0);
}
else
{
System.out.println("Enter Account Type (Recurring, Savings, Current, Fixed):");
AccTyp = br.readLine();
if(AccTyp.equals("Recurring") || AccTyp.equals("Savings") || AccTyp.equals("Current") || AccTyp.equals("Fixed"))
{
System.out.println("Enter Balance:");
Bal = Double.parseDouble(br.readLine());
}
else
{
System.out.println("Invalid Account Type!");
System.exit(0);
}
}
}
public void display()
{
System.out.println("Depositor's Name: " +Name);
System.out.println("Account No.: " +AccNo);
System.out.println("Account Type: " +AccTyp);
System.out.println("Balance: " +Bal);
}
public void calculation()throws IOException
{
System.out.println("Enter amount to withdraw:");
double n = Double.parseDouble(br.readLine());
if(n>Bal)
{
System.out.println("Not Enough Balance!");
System.exit(0);
}
else
{
BalNew = Bal-n;
}
}
public void New()
{
System.out.println("New Balance is: " +BalNew);
System.out.println("Thank you for your Transaction!");
System.out.println("Please Visit Again!");
}
public static void main(String args[])throws IOException
{`enter code here`
Test obj = new Test();
obj.display();
obj.calculation();
obj.New();
}
}
There is some error showing on my BlueJ.
I ran your code in eclipse and it worked fine.
Here's the output
Enter Name:
xyz
Enter Account Number:
1234567891
Enter Account Type (Recurring, Savings, Current, Fixed):
Recurring
Enter Balance:
30000
Depositor's Name: xyz
Account No.: 1234567891
Account Type: Recurring
Balance: 30000.0
Enter amount to withdraw:
10000
New Balance is: 20000.0
Thank you for your Transaction!
Please Visit Again!
I ran your code in BlueJ the error was that, in the main function, the line enter code here is a useless line. Therefore if we remove the line the program runs absolutely fine :).
i ran my code in Net Beans and it gives so many errors.
1> in the above program, you typed:
private final int AccNo;
then you said:
AccNo = Integer.parseInt(br.readLine());
After declaring a variable "final", you cannot initialise it after it has been declared. So don't declare it a final.
Thats the only thing i got. Will inform you if there are any more errors

Loading/reading a .txt file

My last assignment in my intro to Java class asked us to:
Write a console-based (AKA command line based) menu for your user to interact with.
Include the following commands in the menu (you must write code for each):
Input a list of students, use the menu from ArrayDemo: Display, Add, Remove, etc.
Save the list of students to a file using a filename provided by your user
Load the list of students from a file using a filename provided by your user.
I have already done 1-3. How can I get my program to load the info in a .txt file? (Honestly I am not sure if this is what my teacher means when he says loading, because i feel like this may be a bit more complicated than what we have gone over)
I have been able to get my program to open the .txt file with Notepad but I have no idea how to get it to read the whole file and/or save the text info into my program.
import java.util.*;
import java.util.Scanner;
import java.io.*;
public class ArrayDemo_File {
private static Student[] StudentList = new Student[10];
private static FileWriter file;
private static PrintWriter output;
private static FileReader fr;
public static void StudentIndex() {
int index = 0;
while (index < StudentList.length) {
if(StudentList[index] != null) {
System.out.println(index + ": " + StudentList[index].getLName() + ", "
+ StudentList[index].getFName());
}
else {
return;
}
index++;
}
}
// View detailed data for Students listed in the index
public static void IndexData() {
int index = 0;
while (index < StudentList.length) {
if(StudentList[index] !=null) {
System.out.println(index + ": " + StudentList[index].getLName() + ", " + StudentList[index].getFName());
System.out.println("A Number: \t" + StudentList[index].getANum());
System.out.println("Address: \t" + StudentList[index].getAddress());
System.out.println();
}
else {
return;
}
index++;
}
}
// ADD STUDENT
public static void AddStudent() throws IOException {
// Memory
Student student = new Student();
Address address = new Address();
Scanner kb = new Scanner(System.in);
String last;
String frst;
int num;
int house;
String Street;
String City;
String State;
int Zip;
String Line2;
// Student Name and ID
System.out.println();
System.out.print("Last Name:\t");
last = kb.nextLine();
System.out.println();
System.out.print("First Name:\t");
frst = kb.nextLine();
System.out.println();
System.out.print("A Number:\tA");
num = kb.nextInt();
//Address
System.out.println();
System.out.print("What is your house number?\t");
house = kb.nextInt();
kb.nextLine();
System.out.println();
System.out.print("What is your Street's name?\t");
Street = kb.nextLine();
System.out.println();
System.out.print("What is your city?\t");
City = kb.nextLine();
System.out.println();
System.out.print("What is your State?\t");
State = kb.nextLine();
System.out.println();
System.out.print("What is your zip code?\t");
Zip = kb.nextInt();
kb.nextLine();
System.out.println();
System.out.print("Line 2: \t");
Line2 = kb.nextLine();
System.out.println("");
// Processing
address = new Address( house, Street, City, State, Zip, Line2 );
student = new Student(last, frst, num, address);
int index = 0;
while( index < StudentList.length ) {
if( StudentList[index] == null ) break;
index++;
}
StudentList[index] = student;
}
// REMOVE STUDENT
public static void RemoveStudent() {
System.out.println("Remove student");
int index = 0;
while (index < StudentList.length) {
if (StudentList[index] !=null) {
System.out.println(index + ": " + StudentList[index].getLName() + " " + StudentList[index].getFName());
}
index++;
}
Scanner kb = new Scanner(System.in);
int response;
System.out.println(" Please enter student number to remove or -1 to cancel removal");
System.out.print("\nInput: ");
response = Integer.parseInt(kb.nextLine());
if (response != -1) {
StudentList[response] = null;
}
Student[] StudentListTemp = new Student[10];
int nulls = 0;
for(int x = 0; x < StudentList.length; x++) {
if (StudentList[x] == null) {
nulls++;
}
else {
StudentListTemp[x - nulls] = StudentList[x];
}
}
StudentList = StudentListTemp;
}
public static void WriteFile() throws IOException {
String fileName;
Scanner kb = new Scanner(System.in);
System.out.println("Please enter a name for your file: ");
fileName = kb.nextLine();
output = new PrintWriter(fileName + ".txt");
for( int x = 0; x < StudentList.length; x++ ) {
if( StudentList[x] == null )
continue;
output.println( "[" + x + "]" );
output.println( StudentList[x].getFName() );
output.println( StudentList[x].getLName() );
output.println( StudentList[x].getAddress() );
}
output.close();
System.out.println("\n\tFile saved successfully!");
}
public static void loadFile() throws IOException {
Student student = new Student();
String fileName;
Scanner kb = new Scanner(System.in);
System.out.println("Please enter the name of the file: ");
fileName = kb.nextLine();
File file = new File(fileName + ".txt");
if(!file.exists()) {
System.err.println("\n\tError(404)): File Not Found!");
}
else {
System.out.println("\n\tFile found! It will now open!");
//FileReader fr = new FileReader(fileName + ".txt");
//System.out.println(fr);
ProcessBuilder pb = new ProcessBuilder("Notepad.exe", fileName + ".txt");
pb.start();
}
}
//CONSOLE MENU
public static void Menu() throws IOException {
Scanner kb = new Scanner(System.in);
int response;
boolean run = true;
while(run) {
System.out.println("--------------------------" );
System.out.println(" OPTIONS: ");
System.out.println(" 0) View Student Names ");
System.out.println(" 1) View Student details ");
System.out.println(" 2) Add Student ");
System.out.println(" 3) Remove Student ");
System.out.println(" 4) Save to File ");
System.out.println(" 5) Load File ");
System.out.println(" 6) Close Program ");
System.out.println("-------------------------- ");
System.out.print(" Choose an option: ");
response = Integer.parseInt(kb.nextLine());
System.out.println();
switch(response) {
case 0:
StudentIndex();
break;
case 1:
IndexData();
break;
case 2:
AddStudent();
break;
case 3:
RemoveStudent();
break;
case 4:
WriteFile();
break;
case 5:
loadFile();
break;
case 6:
run = false;
break;
default:
System.out.println(" ERROR: "+ response + " ! ");
}
}
System.out.println( "Have a nice day!" );
}
public static void main(String[] args) throws IOException {
// StudentList[0] = new Student("Doe", "Jon", 0000, new Address(00, "Road", "City", "State", 37343, "000"));
// StudentList[1] = new Student("Ricketts", "Caleb", 0001, new Address(000, "000", "000", "0000", 000, "000"));
// StudentList[2] = new Student("Smith", "Amanda", 2222, new Address(000, "000", "000", "000", 000, "000"));
// StudentList[3] = new Student("Wilson", "Judy", 3333, new Address(000, "000", "000", "000", 000, "000"));
Menu();
}
}
I tried using the filereader to read the file but it doesn't output anything. Not sure what I am doing wrong.
Use these code you can write a text file in SDCard along with you need to set permission in android manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
before writing files also check whether your SDCard is Mounted & your external storage state is writable
Environment.getExternalStorageState()
Cod:
public void generateNoteOnSD(String sFileName, String sBody){
try
{
File root = new File(Environment.getExternalStorageDirectory(), "Notes");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
e.printStackTrace();
importError = e.getMessage();
iError();
}
}
Check the http://developer.android.com/guide/topics/data/data-storage.html
Scanner does a good job of reading .txt files. Use another Scanner object to read through the file, one line at a time. After the code completes, each line of the file will be stored in list, with each line at the corresponding index (ex: list.get(0) will return the first line, list.get(1) the second, etc).
public static void loadFile()
{
Student student = new Student();
String fileName;
Scanner kb = new Scanner(System.in);
Scanner read;
ArrayList<String> list = new ArrayList<String>();
System.out.println("Please enter the name of the file: ");
fileName = kb.nextLine();
File file = new File(fileName + ".txt");
if(!file.exists())
{
System.err.println("\n\tError(404)): File Not Found!");
} else {
System.out.println("\n\tFile found! It will now open!");
read = new Scanner(file);
//FileReader fr = new FileReader(fileName + ".txt");
//System.out.println(fr);
//ProcessBuilder pb = new ProcessBuilder("Notepad.exe", fileName + ".txt");
//pb.start();
while(read.hasNextLine()) {
String currentLine = read.nextLine();
list.add(currentLine);
}
}
}

Displaying Information Within Random Access File

I have created an application that allows the user to enter their account number, balance(no more than 99999), and last name. The program will take this information and insert it into a .txt file at a location corresponding to the account number(acct). Here is the code for that:
import java.io.*;
public class NationalBank {
public static void main(String[] args) throws Exception{
InputStreamReader temp = null;
BufferedReader input = null;
try {
temp = new InputStreamReader(System.in);
input = new BufferedReader(temp);
int acct;
double amount;
String name;
RandomAccessFile file = new RandomAccessFile("bank.txt", "rw");
while(true) {
// Asks for input
System.out.println("Enter Account Number (0-9999): ");
acct = Integer.parseInt(input.readLine());
System.out.println("Enter Last Name: ");
name = input.readLine();
System.out.println("Enter Balance ");
amount = Double.parseDouble(input.readLine());
// Making sure account numbers are between 0 and 9999
if(acct >=0 && acct <= 9999) {
file.seek(acct*17);
file.write(truncateName(name));
file.writeBytes(" " +amount);
}
else {
continue;
}
// Asks user if more entries are needed
System.out.println("Enter More? (y/n)");
if (input.readLine().toLowerCase().equals("n"))
break;
}
file.close();
}
catch (Exception e) {
}
}
// Truncate/adding spaces to name until 8 characters
public static byte[] truncateName (String name) {
byte[] result = new byte[8];
for (int i = 0; i < 8; i++)
result [i] = i < name.length () ? (byte)name.charAt (i) : (byte)' ';
return result;
}
}
Now, I am trying to make an application that will write back all of the accounts that have information within them(with last name and balance). I need to display the account number, balance, and last name of those accounts. So far, I have:
import java.io.*;
public class DisplayBank {
public static void main(String[] args) throws IOException {
FileInputStream input = new FileInputStream ("bank.txt");
try {
byte[] record = new byte[17];
while (input.read(record) == 17) {
String name = new String(record, 0, 8);
long bits = 0;
for (int i = 8; i < 17; i++) {
bits <<= 8;
bits |= record[i] & 0xFF;
}
double amount = Double.longBitsToDouble(bits);
System.out.println("Account Number: " + record + " Name: " + name + ", amount: " + amount);
}
}
catch (IOException e) {
}
finally {
input.close();
}
}
}
This currently displays only the name correctly. The balance is incorrect, and I don't know how to get the account number. In order to get the account number, I would need to get the position of name. In order to get the amount, I would need to seek name, offset 9 bytes, then read the next 8 bytes...
If you want to parse a text file that contains last names and amounts similar what you provided:
example provided
LastName 93942.12
What I would do is to try something like the following
public void read_file(){
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("C:\\Users\\Alos\\Desktop\\test.txt");
// Use DataInputStream to read binary NOT text.
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
int record = 0;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
String[] splits = strLine.split("\t");
String LastName = splits[0];
String Amount = splits[1];
System.out.println("Account Number: " + record + " Name: " + LastName + ", amount: " + Amount);
record++;
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
This might not be exactly what you're looking for but please take a look and update your question if you would like something different.
I it's not a homework, I would strongly recommend to use some RDBMS like Derby or MySQL.

Categories

Resources