Reading data from a binary file - java

Hello I am having problem with reading a whole object from a file that i have created ..can anyone please try and test my code... i m a beginer at java.
Students.java
package chapter5.files;
import java.io.*;
import java.util.*;
public class Students
{
/*public static void main(String[] args) {
// TODO Auto-generated method stub
}*/
String name, address;
int roll, age;
float phy, chem, comp, math, bio, eng, nep;
Scanner input = new Scanner(System.in);
public void data_input()
{
System.out.println("Enter the roll no. of the student: ");
roll=input.nextInt();
System.out.println("Enter the name of the student: ");
name=input.nextLine();
System.out.println("Enter the address of the student: ");
address=input.nextLine();
System.out.println("Enter the age of the student: ");
age=input.nextInt();
System.out.println("Enter the marks in Physics: ");
phy=input.nextFloat();
System.out.println("Enter the marks in Chemistry: ");
chem=input.nextFloat();
System.out.println("Enter the marks in Computer: ");
comp=input.nextFloat();
System.out.println("Enter the marks in Mathematics: ");
math=input.nextFloat();
System.out.println("Enter the marks in Biology: ");
bio=input.nextFloat();
System.out.println("Enter the marks in English: ");
eng=input.nextFloat();
}
public float calc_percent()
{
float total=phy+chem+comp+math+bio+eng;
float percent=total/6;
return percent;
}
public void show_individual()
{
System.out.println("Roll: " + roll);
System.out.println("Name: " + name);
System.out.println("Address: " + address);
System.out.println("Age: " + age);
System.out.println("Physics: " + phy);
System.out.println("Chemistry: " + chem);
System.out.println("Computer: " + comp);
System.out.println("Mathematics: " + math);
System.out.println("Biology: " + bio);
System.out.println("English: " + eng);
System.out.println("Percentage: " + calc_percent());
System.out.println(" ");
}
}
StudentsMain.java
package chapter5.files;
import java.util.*;
import java.io.*;
public class StudentsMain extends Students
{
//****************************************Entry of new data*************************************************//
public static void entry() throws IOException
{
Students s = new Students();
s.data_input();
File f = new File("index.dat");
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream foos = new ObjectOutputStream(fos);
foos.writeObject(s);
System.out.println("The data has been stored into the file.");
foos.close();
fos.close();
//?????????????????????Why isn't file f closing??????????????????????????????
}
//****************************************Show individual data*************************************************//
public static void show_individual(int temproll) throws IOException, ClassNotFoundException
{
Scanner input = new Scanner(System.in);
System.out.println("Enter the roll no. of the student you want to display the data of: ");
temproll=input.nextInt();
File f1 = new File("index.dat");
FileInputStream fis = new FileInputStream(f1);
ObjectInputStream fois=new ObjectInputStream(fis);
while(true)
{
Students temp[] = (Students[])is.readObject();//reading in stream..so we have to type cast it in stream.
for(int i=0;i < temp.length;i++)
{
if(temproll==temp[i].roll)
{
temp[i].show_individual();
}
}
}
fis.close();
fois.close();
}
private static void display_tabular() throws IOException
{
/*File f1 = new File("index.dat");
FileInputStream fis = new FileInputStream(f1);
ObjectInputStream fois=new ObjectInputStream(fis);
while(true)
{
Students temp[] = (Students[])is.readObject();//reading in stream..so we have to type cast it in stream.
for(int i=0;i < temp.length;i++)
{
}
}*/
System.out.println("You are now in the display tabular region.");
}
public static void main(String[] args) throws IOException, ClassNotFoundException
{
//Students[] s = new Students[100];
Scanner input = new Scanner(System.in);
System.out.println("*************************MAIN MENU****************************");
System.out.println("Enter any of the following choices: ");
System.out.println("1. Enter a new data" );
System.out.println("2. Display individual data" );
System.out.println("3. Display data in tabular form");
System.out.println("*************************MAIN MENU****************************");
char ch = input.next().charAt(0);
/*File f =new File("index.dat");
FileOutputStream f1 = new FileOutputStream(f);
ObjectOutputStream f3 = new ObjectOutputStream(f3);*/
switch(ch)
{
case '1':
entry();
break;
case '2':
System.out.println("Please enter the roll no. of the student you want to display the rocord of: ");
int temproll=input.nextInt();
show_individual(temproll);
break;
case '3':
display_tabular();
break;
default:
System.out.println("Please Enter a valid choice.");
}
}
}

Related

Error in reading Input from DataInputStream in java

Firstly I have made a folder named juet and then I have made two packages inside that folder. First one is Student package which takes care of all the students in university
package juet.stud;
import java.io.IOException;
import java.io.DataInputStream;
public class Student {
String name;
public int roll_no;
int std;
char grade;
public Student() {
try (DataInputStream in = new DataInputStream(System.in)) {
System.out.println("Enter name of student:");
name = in.readUTF();
System.out.println("Enter roll no.:");
roll_no = in.readInt();
System.out.println("Enter std:");
std = in.readInt();
System.out.println("Enter grade");
grade = in.readChar();
} catch (IOException e) {
System.err.println(e);
}
}
public void showInfo() {
System.out.println("Name of student: " + name);
System.out.println("Roll no.: " + roll_no);
System.out.println("Std: " + std);
System.out.println("Grade: " + grade);
}
}
Another package which I have made is Staff which takes care of all staff in the university
package juet.staff;
import java.io.IOException;
import java.io.DataInputStream;
public class Staff {
public int id;
String name, specialization;
char group;
public Staff() {
try (DataInputStream in = new DataInputStream(System.in)) {
System.out.println("Enter id:");
id = in.readInt();
System.out.println("Enter name:");
name = in.readUTF();
System.out.println("Enter area of specialization:");
specialization = in.readUTF();
System.out.println("Enter group");
group = in.readChar();
} catch (IOException e) {
System.err.println(e);
}
}
public void showInfo() {
System.out.println("ID: " + id);
System.out.println("Name: " + name);
System.out.println("Area of specialization: " + specialization);
System.out.println("Group: " + group);
}
}
And then at the last I have made MyUniversity Class in which I was using both the packages
package juet;
import juet.stud.Student;
import juet.staff.Staff;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.Console;
class University {
Student[] stu;
Staff stf[];
int studCount, staffCount;
University() {
try (DataInputStream in = new DataInputStream(System.in)) {
System.out.println("Enter capacity for students:");
int x = Integer.parseInt(in.readLine());
//stu = new Student[x];
System.out.println("Enter capacity for staff:");
x = Integer.parseInt(in.readLine());
stf = new Staff[x];
studCount = staffCount = 0;
} catch (IOException e) {
System.err.println(e);
}
}
void newStudent() {
stu[studCount] = new Student();
studCount++;
}
void studInfo(int roll
) {
int i;
for (i = 0; i < studCount; i++) {
if (stu[i].roll_no == roll) {
stu[i].showInfo();
return;
}
}
System.out.println("No match found.");
}
void newStaff() {
stf[staffCount] = new Staff();
staffCount++;
}
void staffInfo(int id
) {
int i;
for (i = 0; i < staffCount; i++) {
if (stf[i].id == id) {
stf[i].showInfo();
return;
}
}
System.out.println("No match found.");
}
}
class MyUniversity {
public static void main(String args[]) throws IOException {
University juet = new University();
int ch;
DataInputStream in = new DataInputStream(System.in);
while (true) {
System.out.println("\tMAIN MENU\n");
System.out.println("1. Add student\n2. Add staff member\n3. Display info about specific student\n4. Display info about specific staff member\n0. Exit\n\tEnter your choice");
try {
ch = Integer.parseInt(in.readLine());
switch (ch) {
case 1:
juet.newStudent();
break;
case 2:
juet.newStaff();
break;
case 3:
System.out.println("Enter roll no. of student to display info:");
int roll = in.readInt();
juet.studInfo(roll);
break;
case 4:
System.out.println("Enter ID of staff member to display info:");
int id = in.readInt();
juet.staffInfo(id);
break;
case 0:
return;
default:
System.out.println("Incorrect choice.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Problem is arising when I am calling University object in the main class it is asking for two inputs
1).Enter capacity for students
so I enter 3
and again it ask for
2)Enter capacity for staff
But when I enter the integer there it is running infinite times
and showing error
java.io.Exception:Stream closed
at
java.io.BufferedInputStream.getBufIfopen(BufferedInputStream.java:170)
atjuet.MyUniversity.main(MyUniversity.java:76)
at java.io.DataInputStream.readLine(DataInputStream.java:513)
Please help me Thanks in advance
You are using the wrong class. DataInputStream and the methods readUTF() and readInt() can not be used for reading text from the console. It is designed to read binary content encoded by a different Java program using DataOutputStream.
The following question and answers show you how to do it right:
How can I read input from the console using the Scanner class in Java?

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);
}
}
}

Input 2 names and output the average age

This is for personal knowledge of how this works, is not for school
Program requirements - Enter 2 Names. Have the program find the assigned values with the names and print the average between the two people.
I an not sure how to get the Scanner to take the input and go to the class to make it start processing. For example, in the main method if I sysout print a, it should display the string inside the method getName.
import java.util.Scanner;
public class RainFallApp {
public static void main(String[] args) {
rainfall a = new rainfall();
rainfall b = new rainfall();
System.out.println(a);
// System.out.print("Please enter month one: ");
// Scanner = new Scanner(System.in);
// rain1 = aRain;
// System.out.print("Please enter month two: ");
// Scanner = new Scanner(System.in);
//
// int average = (rain1 + rain2) / 2;
// System.out.println("The average rainfall for " + var +
"and " + var2 +"is: " + average);
}
}
class rainfall {
String rainamt;
String Rain_Amount;
Scanner input = new Scanner(System.in);
String rainMonth = input.nextLine();
String rainAmount(String rainMonth) {
Rain_Amount = getName(rainMonth);
return Rain_Amount;
}
private String getName(String rainMonth) {
if (rainMonth.equals("Jan")) {
rainamt = "3.3";
}
else if (rainMonth.equals("Feb")) {
rainamt = "2.2";
}
else {
System.out.println("Not a valid month name");
}
return rainamt;
}
}
You only need to say Scanner scanner = new Scanner(System.in); once. Then you can use the scanner's nextLine() method to input data. It returns a string, so be sure to store the result in a variable.
I completed my program
import java.util.Scanner;
public class RainFallApp {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter the first month: ");
String aMonth = input.nextLine();
System.out.print("Please enter the second month: ");
String bMonth = input.nextLine();
rainfall aRainfall = new rainfall();
String aName = aRainfall.rainAmount(aMonth);
Double aAmount = Double.parseDouble(aName);
rainfall bRainfall = new rainfall();
String bName = bRainfall.rainAmount(bMonth);
Double bAmount = Double.parseDouble(bName);
double Avg = (aAmount + bAmount) / 2;
System.out.println("\nIn the month of " + aMonth + " it had "
+ aAmount + " inches of rain.");
System.out.println("In the month of " + bMonth + " it had "
+ bAmount + " inches of rain.");
System.out.println("The average rainfall between the two months is: " + Avg);
}
}
class rainfall {
private String Rain_Amount;
String rainAmount(String rainMonth) {
Rain_Amount = getAmount(rainMonth);
return Rain_Amount;
}
private String getAmount(String rainMonth) {
if (rainMonth.equals("Jan")) {
Rain_Amount = "3.3";
}
else if (rainMonth.equals("Feb")) {
Rain_Amount = "2.3";
}
else {
System.out.println("Not a valid month name");
}
return Rain_Amount;
}
}

Updating a double in a text file

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!

Method to display records.

Hey guys just need help on how to finish this up.
Code Snippet:
import java.util.Scanner;
public class CreateLoans implements LoanConstants {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//set the program here
float prime;
float amountOfLoan = 0;
String customerFirstName;
String customerLastName;
String LoanType;
System.out.println("Please Enter the current prime interest rate");
prime = sc.nextInt() / 100f;
//ask for Personal or Business
System.out.println("are you after a business or personal loan? Type business or personal");
LoanType = sc.next();
//enter the Loan amount
System.out.println("Enter the amount of loan");
amountOfLoan = sc.nextInt();
//enter Customer Names
System.out.println("Enter First Name");
customerFirstName = sc.next();
System.out.println("Enter Last Name");
customerLastName = sc.next();
//enter the term
System.out.println("Enter the Type of Loan you want. 1 = short tem , 2 = medium term , 3 = long term");
int t = sc.nextInt();
}
}
I need to display the records I have asked and store the object into an array.
so this where I'm stuck. I need to do this in a loop 5 times and by the end display all records in an array, if that makes sense?
Try this way :
import java.util.Scanner;
public class CreateLoans {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Loan[] loans = new Loan[5];
for(int i=0;i<5;i++) {
loans[i] = new Loan();
System.out.println("Please Enter the current prime interest rate");
float prime = sc.nextInt();
prime = (float)(prime/100f);
loans[i].setPrime(prime);
//ask for Personal or Business
System.out.println("are you after a business or personal loan? Type business or personal");
String loanType = sc.next();
loans[i].setLoanType(loanType);
//enter the Loan amount
System.out.println("Enter the amount of loan");
float amountOfLoan = sc.nextFloat();
loans[i].setAmountOfLoan(amountOfLoan);
//enter Customer Names
System.out.println("Enter First Name");
String customerFirstName = sc.next();
loans[i].setCustomerFirstName(customerFirstName);
System.out.println("Enter Last Name");
String customerLastName = sc.next();
loans[i].setCustomerLastName(customerLastName);
}
//Display details
for(int i=0;i<5;i++) {
System.out.println(loans[i]);
}
}
}
class Loan {
private float prime;
private float amountOfLoan = 0;
private String customerFirstName;
private String customerLastName;
private String LoanType;
public float getPrime() {
return prime;
}
public void setPrime(float prime) {
this.prime = prime;
}
public float getAmountOfLoan() {
return amountOfLoan;
}
public void setAmountOfLoan(float amountOfLoan) {
this.amountOfLoan = amountOfLoan;
}
public String getCustomerFirstName() {
return customerFirstName;
}
public void setCustomerFirstName(String customerFirstName) {
this.customerFirstName = customerFirstName;
}
public String getCustomerLastName() {
return customerLastName;
}
public void setCustomerLastName(String customerLastName) {
this.customerLastName = customerLastName;
}
public String getLoanType() {
return LoanType;
}
public void setLoanType(String loanType) {
LoanType = loanType;
}
#Override
public String toString() {
return "First Name : " + customerFirstName + "\n" +
"Last Name : " + customerLastName + "\n" +
"Amount of Loan : " + amountOfLoan + "\n" +
"Loan type : " + LoanType + "\n" +
"Prime : " + prime + "\n\n";
}
}
Create a Loan class and put all necessary details as private members into it and override toString() method.
Make a ArrayList and add all the variables inside that list
ArrayList arrlist = new ArrayList();
arrlist.add(prime);
arrlist.add(LoanType);
arrlist.add(amountOfLoan);
arrlist.add(customerFirstName );
arrlist.add(customerLastName);
arrlist.add(t);
and display the ArrayList
System.out.println(arrlist);
Example of a loop
int[] nums = new int[5];
String[] names = new String[5];
Scanner input = new Scanner(System.in);
for (int i = 0; i < 5; i++){
System.out.println("Enter a number: ");
int number = input.nextInt();
// insert into array
nums[i] = number;
System.out.println("Enter a name: ");
String name = input.nextLne();
// insert into array
names[i] = name;
}
Everything you want to be looped 5 times, you can put inside the loop. Whatever values you want to store, you can do that in the loop also.

Categories

Resources