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);
}
}
}
Related
if I want to read file from text file and store it in an array,each line goes to correct array
this is the text file
111111,34,24.5,first line
222222,53,22.0,second line
333333,,32.0,third line
44444,22,12.6,
if line is empty through exception saying "title is missing" or something like that.
a code has been made if the array length==4 then display lines in order but if length less than 4 and line is missing throw exception but when I want to put last array[3] gives me error. have a look if you can seethe error that would help
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Itry {
public static void main(String[] args) {
// TODO Auto-generated method stub
String [] splitArray = new String[4];
String line = "";
String array1, description;
int number;
double price;
// Total sales
double total = 0;
Scanner keyboard = new Scanner (System.in);
// Allow the user to enter the name of text file that the data is stored in
System.out.println("This program will try to read data from a text file ");
System.out.print("Enter the file name: ");
String filename = keyboard.nextLine();
Scanner fileReader = null;
try {
File Fileobject = new File (filename);
fileReader = new Scanner (Fileobject);
System.out.println("\nTransactions");
System.out.println("================");
while(fileReader.hasNext())
{
// Contains stock code,Quantity,Price,Description
line = fileReader.nextLine();// Read a line of data from text file
splitArray = line.split(",");
// check to make sure there are 4 parts in splitArray
if(splitArray.length == 4)
{
// remove spaces
splitArray[0] = splitArray[0].trim();
splitArray[1] = splitArray[1].trim();
splitArray[2] = splitArray[2].trim();
splitArray[3] = splitArray[3].trim();
// Extract each item into an appropriate
// variable
try {
array1 = splitArray[0];
number = Integer.parseInt(splitArray[1]);
price = Double.parseDouble(splitArray[2]);
description = splitArray[3];
// Output item
System.out.println("Sold "+String.format("%-5d", number) +
String.format("%-12s", description )+ " at "+"£"+
String.format("%-5.2f", price));
// Compute total
total += number * price;
} // end of try
catch(NumberFormatException e)
{
System.out.println("Error: Cannot convert to number");
}
} //end of if
else if (splitArray[0].length()<1) {
try { splitArray[0] = splitArray[0].trim();
System.out.println(" Title is missing "+" "+splitArray[1] +""+splitArray[2]+"");
}
catch(NumberFormatException e)
{
System.out.println("Error: Cannot convert to number");
}
}
else if (splitArray[1].length()<=1) {
try { splitArray[1] = splitArray[1].trim();
System.out.println(splitArray[0]+" "+" here is missing " +""+splitArray[2] );
}
catch(NumberFormatException e)
{
System.out.println("Error: Cannot convert to number");
}}
else if (splitArray[2].length()<=1) {
try { splitArray[2] = splitArray[2].trim();
System.out.println(splitArray[0]+" "+splitArray[1] +""+" here is missing "+splitArray[3]);
}
catch(NumberFormatException e)
{
System.out.println("Error: Cannot convert to number");
}}
else if (splitArray[3].length()<=1) {
try { splitArray[3] = splitArray[3].trim();
System.out.println(splitArray[0]+" "+splitArray[1] +""+splitArray[2]+"title is missing");
}
catch(NumberFormatException e)
{
System.out.println("Error: Cannot convert to number");
}}
}//end of while
System.out.printf("\nTotal sales: £"+String.format("%-6.2f", total));
}// end of try block
catch (FileNotFoundException e)
{
System.out.println("Error - File does not exist");
}
}
}
You can do it as follows:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] splitArray = new String[4];
String line = "";
String array1, description;
int number;
double price;
// Total sales
double total = 0;
Scanner keyboard = new Scanner(System.in);
// Allow the user to enter the name of text file that the data is stored in
System.out.println("This program will try to read data from a text file ");
System.out.print("Enter the file name: ");
String filename = keyboard.nextLine();
Scanner fileReader = null;
try {
File Fileobject = new File(filename);
fileReader = new Scanner(Fileobject);
System.out.println("\nTransactions");
System.out.println("================");
int count = 1;
while (fileReader.hasNext()) {
// Contains stock code,Quantity,Price,Description
line = fileReader.nextLine();// Read a line of data from text file
try {
if (line != null && line.length() > 0) {
splitArray = line.split(",");
// check to make sure there are 4 parts in splitArray
if (splitArray.length == 4) {
// remove spaces
splitArray[0] = splitArray[0].trim();
splitArray[1] = splitArray[1].trim();
splitArray[2] = splitArray[2].trim();
splitArray[3] = splitArray[3].trim();
// Extract each item into an appropriate variable
try {
array1 = splitArray[0];
number = Integer.parseInt(splitArray[1]);
price = Double.parseDouble(splitArray[2]);
description = splitArray[3];
// Output item
System.out.println(
"Sold " + String.format("%-5d", number) + String.format("%-12s", description)
+ " at " + "£" + String.format("%-5.2f", price));
// Compute total
total += number * price;
} catch (NumberFormatException e) {
System.out.println("Error in line#" + count + ": insufficient/invalid data");
}
} else {
throw new IllegalArgumentException(
"Error in line#" + count + ": insufficient/invalid data");
}
} else {
throw new IllegalArgumentException("Line#" + count + " is empty");
}
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
count++;
} // end of while
System.out.printf("\nTotal sales: £" + String.format("%-6.2f", total));
} catch (FileNotFoundException e) {
System.out.println("Error - File does not exist");
}
}
}
A sample run:
This program will try to read data from a text file
Enter the file name: data2.txt
Transactions
================
Sold 34 Apple at £24.50
Line#2 is empty
Sold 53 Mango at £22.00
Line#4 is empty
Error in line#5: insufficient/invalid data
Line#6 is empty
Error in line#7: insufficient/invalid data
Total sales: £1999.00
Content of data2.txt:
111111,34,24.5,Apple
222222,53,22.0,Mango
333333,,32.0,Orange
44444,22,12.6,
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.");
}
}
}
My program is running. My problem is when I redirect input form a file, the input did not show in the console.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import java.util.List;
public class ReservationSystem{
public void printMenu() {
System.out.print("Add [P]assenger, Add [G]roup, "
+ "[C]ancel Reservations, \nPrint Seating "
+ "[A]vailability Chart, Print [M]anifest, [Q]uit\n");
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
ReservationSystem rs = new ReservationSystem();
First fc = new First();
Economy ec = new Economy();
boolean done = false;
do
{
String option = new String();
rs.printMenu();
option = in.nextLine();
option = option.toUpperCase();
while(!((option.equals("P")) || (option.equals("G"))||
(option.equals("C")) || (option.equals("A"))||
(option.equals("M")) || (option.equals("Q"))))
{
System.out.print("Please enter again: ");
option = in.nextLine();
option = option.toUpperCase();
}
if(option.equals("P"))
{
String name = new String();
String serviceClass = new String();
String SeatPreference = new String();
System.out.print("Name: ");
name = in.nextLine();
System.out.print("Service Class: ");
serviceClass = in.nextLine();
serviceClass = serviceClass.toUpperCase();
System.out.print("Seat Preference: ");
SeatPreference = in.nextLine();
SeatPreference = SeatPreference.toUpperCase();
if(serviceClass.equals("FIRST")) fc.addPassenger(name, SeatPreference);
if(serviceClass.equals("ECONOMY")) ec.addPassenger(name, SeatPreference);
}
else if(option.equals("G"))
{
List<String> list = new ArrayList<String>();
String groupName = new String();
String name = new String();
String serviceClass = new String();
System.out.print("Group Name: ");
groupName = in.nextLine();
System.out.print("Names: ");
name = in.nextLine();
list = Arrays.asList(name.split(","));
for(int i=0; i<list.size();i++)
{
list.set(i, list.get(i).trim());
}
System.out.print("Service Class: ");
serviceClass = in.nextLine();
serviceClass = serviceClass.toUpperCase();
if(serviceClass.equals("FIRST")) fc.addGroup(list, groupName);
if(serviceClass.equals("ECONOMY")) ec.addGroup(list, groupName);
}
else if(option.equals("C"))
{
String option1 = new String();
System.out.print("Cancel [I]ndividual or [G]roup? ");
option1 = in.nextLine();
option1 = option1.toUpperCase();
if(option1.equals("I"))
{
System.out.print("Name: ");
String name = in.nextLine();
fc.cancelIndividualReservation(name);
ec.cancelIndividualReservation(name);
}
if(option.equals("G"))
{
System.out.print("Group Name: ");
String groupName = in.nextLine();
fc.cancelGroupReservation(groupName);
ec.cancelGroupReservation(groupName);
}
}
else if(option.equals("A"))
{
System.out.print("Service Class: ");
String serviceClass = new String();
serviceClass = in.nextLine();
serviceClass = serviceClass.toUpperCase();
if(serviceClass.equals("FIRST"))
{
fc.printAvailbilityList();
}
if(serviceClass.equals("ECONOMY"))
{
ec.printAvailbilityList();
}
}
else if(option.equals("M"))
{
System.out.print("Service Class: ");
String serviceClass = new String();
serviceClass = in.nextLine();
serviceClass = serviceClass.toUpperCase();
if(serviceClass.equals("FIRST")){fc.printManifest();}
if(serviceClass.equals("ECONOMY")){ec.printManifest();}
}
else{done = true;}
}while(done==false);
in.close();
}
}
Except to see the interaction between user and the program
Add [P]assenger, Add [G]roup, [C]ancel Reservations,
Print Seating [A]vailability Chart, Print [M]anifest, [Q]uit
P
Name: John Smith
Service Class: First
Seat Preference: W
Add [P]assenger, Add [G]roup, [C]ancel Reservations,
Print Seating [A]vailability Chart, Print [M]anifest, [Q]uit
Q
But when I enter java Reservation < input.txt, all inputs did not show up.
Add [P]assenger, Add [G]roup, [C]ancel Reservations,
Print Seating [A]vailability Chart, Print [M]anifest, [Q]uit
Name: Service Class: Seat Preference: Add [P]assenger, Add [G]roup, [C]ancel
Reservations, Print Seating [A]vailability Chart, Print [M]anifest, [Q]uit
see this sample found at http://pages.cs.wisc.edu/~cs302-2/resources/w13/TestArgs.txt
to see how to pass a filename argument to a scanner
public class TestArgs3 {
public static void main( String [] args )
throws FileNotFoundException
{
if ( args.length < 1 ) {
System.out.println( usage() );
}
for ( int i=0; i < args.length; i++ ) {
String filename = args[i];
System.out.println("Scanning file " + filename + " ...");
File file = new File( filename );
Scanner filescanner = new Scanner( file );
String line = filescanner.nextLine();
System.out.println( line );
filescanner.close();
}
}
public static String usage() {
return "Usage: java TestArgs filename1 filename2 filename3 ...";
}
}
So my code currently has the user specify the name of the file that they want to load within the code itself but how would I make it so that when the program is run then the user will enter the location of the file that they want to load?
import java.io.*;
import java.util.*;
public class reader {
static int validresults = 0;
static int invalidresults = 0;
//used to count the number of invalid and valid matches
public static boolean verifyFormat(String[] words) {
boolean valid = true;
if (words.length != 4) {
valid = false;
} else if (words[0].isEmpty() || words[0].matches("\\s+")) {
valid = false;
} else if ( words[1].isEmpty() || words[1].matches("\\s+")) {
valid = false;
}
return valid && isInteger(words[2]) && isInteger(words[3]);}
//checks to see that the number of items in the file are equal to the four needed and the last 2 are integers
//also checks to make sure that there are no results that are just whitespace
public static boolean isInteger( String input ) {
try {
Integer.parseInt( input );
return true;
}
catch( Exception e ) {
return false;
}
}
//checks to make sure that the data is an integer
public static void main(String[] args) throws FileNotFoundException {
String hteam;
String ateam;
int hscore;
int ascore;
int totgoals = 0;
Scanner s = new Scanner(new BufferedReader(
new FileReader("fbscores.txt"))).useDelimiter("\\s*:\\s*|\\s*\\n\\s*");
while (s.hasNext()) {
String line = s.nextLine();
String[] words = line.split("\\s*:\\s*");
//splits the file at colons
if(verifyFormat(words)) {
hteam = words[0]; // read the home team
ateam = words[1]; // read the away team
hscore = Integer.parseInt(words[2]); //read the home team score
totgoals = totgoals + hscore;
ascore = Integer.parseInt(words[3]); //read the away team score
totgoals = totgoals + ascore;
validresults = validresults + 1;
System.out.println(hteam + " " + "[" + hscore + "]" + " " + ateam + " " + "[" + ascore + "]");
//output the data from the file in the format requested
}
else{
invalidresults = invalidresults + 1;
}
}
System.out.println("Total number of goals scored was " + totgoals);
//displays the the total number of goals
System.out.println("Valid number of games is " + validresults);
System.out.println("Invalid number of games is " + invalidresults);
System.out.println("EOF");
}
}
One approach would be to use a main loop asking for a file name and quitting program execution when no input is given.
Therefore I'd refactor most code of your main method into another function e.g. processFile(String fileName).
Then your main only deals with user input
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
while(true){ //keep running till we break
System.out.println("Enter filename or return blank line to quit");
String fileName = sc.nextLine();
if(fileName != null && !fileName.isEmpty()){
processFile(fileName)
}else{
break; //no user input => exit
}
}
System.out.println("bye");
}
private static processFile(String fileName){
String hteam;
String ateam;
int hscore;
int ascore;
int totgoals = 0;
Scanner s = new Scanner(new BufferedReader(
new FileReader(fileName))).useDelimiter("\\s*:\\s*|\\s*\\n\\s*");
while (s.hasNext()) {
… //rest of your original code
}
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!