It keeps me looping even though I don't have any loops - java

I don't know what is wrong but it keeps me looping even though I pressed or entered 1 and I want it to call the subclass agent it doesn't but when I press 2 it calls the subclass what is wrong here I've been at it for 5-7hrs I think and my eyes be balling
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;
class Person
{
protected String agentId = "20860132";
protected String password = "20020729" ;
protected String address;
public Person(String agentId,String password, String address)
{
this.agentId = agentId;
this.password = password;
this.address = address;
Scanner input = new Scanner(System.in);
System.out.println("[1]AGENT");
System.out.println("[2]CUSTOMER");
int choice = input.nextInt();
//here is where the code loops it just keeps repeating this lines
"System.out.println("[1]AGENT"); System.out.println("[2]CUSTOMER");"
if(choice == 1)
{
Agent agent = new Agent("Niel", "diko alam", "umay");
}
else if(choice == 2)
{
System.out.println("POTANGINA");
}
}
}
the block of code up here is suppose to call this class
class Agent extends Person
{
public Agent(String agentId, String password, String address)
{
super(agentId, password, address);
Scanner input2 = new Scanner(System.in);
System.out.println("[LOGIN]");
System.out.print("ENTER AGENT ID:");
int id = input2.nextInt();
System.out.print("ENTER PASSWORD:");
int pass = input2.nextInt();
if(id == 20860132 && pass == 20020729)
{
Scanner input = new Scanner(System.in);
System.out.println("[1]ADD CAR");
System.out.println("[2]SCHEDULE");
System.out.println("[3]RECORDS");
int choice2 = input.nextInt();
if(choice2 == 1)
{
boolean stopFlag = false;
do
{
List<String>cars = new ArrayList<String>();
System.out.println("[CARS]");
cars.add("Tayota");
cars.add("Hillux");
cars.add("Bugatti");
System.out.println(cars);
System.out.println("Enter Car:");
String car = input.nextLine();
cars.add(car);
System.out.println("Would you like to add more?");
System.out.println("[1]YES");
System.out.println("[2]NO");
String choice3 = input.nextLine();
addCar(cars);
if(!choice3.equals(1))
stopFlag = true;
}while(!stopFlag);
}
}
else
{
System.out.println("INCORRECT PLEASE TRY AGAIN.");
}
}
public void addCar(List<String> cars)
{
try
{
FileWriter fw = new FileWriter("cars.txt", true);
PrintWriter pw = new PrintWriter(fw);
pw.println(cars);
pw.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void schedule(String schedule)
{
try
{
FileWriter fw = new FileWriter("schedule.txt", true);
PrintWriter pw = new PrintWriter(fw);
pw.println(schedule);
pw.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void records(String record)
{
try
{
FileWriter fw = new FileWriter("records.txt", true);
PrintWriter pw = new PrintWriter(fw);
pw.println(record);
pw.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
class Customer extends Person
{
private String customerId;
public Customer(String agentId, String password, String address, String customerId)
{
super(agentId, password, address);
this.customerId = customerId;
}
public void setCustomerId(String customerId)
{
this.customerId = customerId;
}
public String getCustomerId()
{
return customerId;
}
public void rentCar(String car)
{
try
{
FileWriter fw = new FileWriter("cars.txt", true);
PrintWriter pw = new PrintWriter(fw);
pw.println(car);
pw.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void viewSchedule(String schedule)
{
try
{
FileWriter fw = new FileWriter("schedule.txt", true);
PrintWriter pw = new PrintWriter(fw);
pw.println(schedule);
pw.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void extend(String record)
{
try
{
FileWriter fw = new FileWriter("records.txt", true);
PrintWriter pw = new PrintWriter(fw);
pw.println(record);
pw.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Here is the main method
public class Finals
{
public static void main(String[] args)
{
Person person = new Person("20860132", "h208f32", "San luis");
Agent agent = new Agent("20860132", "h208f32", "San luis");
}
}

First line in the constructor of Agent calls super, which is the constructor of Person that will ask for input 1 and 2 again. That is your 'loop'. When you select 1, it will start creating another Agent object which will do the same thing again. If you keep selecting '1' you will never get past the super call in Agent.
Put the printing/input logic somewhere else, like in your main method. Constructors should be simple. For example, the logic in your Person constructor, move that to a static method in your Finals class (public static void createPerson) with the same arguments as what the constructor now has, and then call that from your main method instead of new Person. There is still much to improve beyond that, but that will probably fix your 'loop'.

Related

Is there a way to access the date added to an ArrayList in a different to change its data?

I have this in the Class: public static ArrayList<String> studentInfo = new ArrayList<String>();I created a method CreateStudent() that basically allows the user to create a student using Scanner, the DisplayStudent() uses ObjectInputStream to open the file and read the data. Now, when the users creates a student, it stores the data into an ArrayList using studentInfo.add(), the idea is that the EditStudent() access the data added into the ArrayList with the info added in CreateStudent() Is there a way to access that list from another method?I would appreciate any ideas, here is my code:
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.io.*;
import java.lang.ClassNotFoundException;
public class MidTermProject extends ObjectOutputStream {
private boolean append;
private boolean initialized;
private DataOutputStream dout;
static AtomicInteger idGenerator = new AtomicInteger(0001);
static int id;
public static String FullName;
public static String address;
public static String city;
public static String state;
public static String className;
public static String instructor;
public static String department;
public static String classNumber;
public static String courseNumber;
public static String year;
public static String semester;
public static String grade;
public static String studentID;
public static String courseID;
public static String enrollmentID;
public static ArrayList<String> studentInfo = new ArrayList<String>();
Scanner keyboard = new Scanner(System.in);
protected MidTermProject(boolean append) throws IOException, SecurityException {
super();
this.append = append;
this.initialized = true;
}
public MidTermProject(OutputStream out, boolean append) throws IOException {
super(out);
this.append = append;
this.initialized = true;
this.dout = new DataOutputStream(out);
this.writeStreamHeader();
}
#Override
protected void writeStreamHeader() throws IOException {
if (!this.initialized || this.append) return;
if (dout != null) {
dout.writeShort(STREAM_MAGIC);
dout.writeShort(STREAM_VERSION);
}
}
public static int getId() {
return id;
}
///Create Student Method
public static void CreateStudent() throws IOException {
File file = new File("StudentInfo.dat");
boolean append = file.exists();
Scanner keyboard = new Scanner(System.in);
try (
FileOutputStream fout = new FileOutputStream(file, append);
MidTermProject oout = new MidTermProject(fout, append);
) {
id = idGenerator.getAndIncrement();
studentID = Integer.toString(getId());
oout.writeObject("Student ID: " + studentID);
System.out.print("\nPlease enter your information bellow.\n" + "\nFull Name: ");
FullName = keyboard.nextLine();
oout.writeObject("Full Name: " + FullName);
System.out.print("Address: ");
address = keyboard.nextLine();
oout.writeObject("Address: " + address);
System.out.print("City: ");
city = keyboard.nextLine();
oout.writeObject("City: " + city);
System.out.print("State: ");
state = keyboard.nextLine();
oout.writeObject("State: " + state + "\n");
studentInfo.add(studentID);
studentInfo.add(FullName);
studentInfo.add(address);
studentInfo.add(city);
studentInfo.add(state);
oout.close();
System.out.println("Done!\n");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
///Edit Student Method
public static void EditStudent() throws IOException {
String editName;
String editaddress;
String editCity;
String editState;
int editID;
String editStudent;
boolean endOfFile = false;
Scanner keyboard = new Scanner(System.in);
System.out.print(studentInfo);
System.out.print("Enter the ID of the student you would like to edit: ");
editID = keyboard.nextInt();
String editingID = Integer.toString(editID);
FileInputStream fstream = new FileInputStream("StudentInfo.dat");
ObjectInputStream inputFile = new ObjectInputStream(fstream);
File file = new File("StudentInfo.dat");
boolean append = file.exists();
while(!endOfFile)
{
try
{
FileOutputStream fout = new FileOutputStream(file, append);
MidTermProject oout = new MidTermProject(fout, append);
editStudent = (String) inputFile.readObject();
if(editingID == oout.studentID) {
System.out.print("\nPlease enter NEW information bellow.\n" + "\nFull Name: ");
editName = keyboard.nextLine();
oout.writeObject("Full Name: " + editName);
System.out.print("Address: ");
editaddress = keyboard.nextLine();
oout.writeObject(editaddress);
System.out.print("City: ");
editCity = keyboard.nextLine();
oout.writeObject(editCity);
System.out.print("State: ");
editState = keyboard.nextLine();
oout.writeObject(editState);
oout.close();
System.out.print("Successfully Edited");
} else {
System.out.print("Error");
}
}
catch (EOFException | ClassNotFoundException e)
{
endOfFile = true;
}
}
}
Display Student Method
public static void DisplayStudent() throws IOException {
FileInputStream fstream = new FileInputStream("StudentInfo.dat");
ObjectInputStream inputFile = new ObjectInputStream(fstream);
String student;
boolean endOfFile = false;
while(!endOfFile)
{
try
{
student = (String) inputFile.readObject();
System.out.print(student + "\n");
}
catch (EOFException | ClassNotFoundException e)
{
endOfFile = true;
}
}
System.out.println("\nDone");
inputFile.close();
}

Print To File in Java

i have a problem in my java exercise.
i need to print a multiply contact information to a file, but when i print more then 1 contact, only 1 contact is displayed in the file..
i tried to debug that but i cant find any mistake
i will put the code of my classes here:
This is Demo Class which i run the code from
public class Demo {
public static void main(String[] args) {
System.out.println("Insert number of Contacts:");
Scanner scanner = new Scanner(System.in);
int val = scanner.nextInt();
Contact[] contacts = new Contact[val];
for(int i = 0 ; i < val; i++) {
System.out.println("Contact #"+(i+1));
System.out.print("Owner: \n");
String owner = scanner.next();
System.out.print("Phone number: \n");
String phoneNum = scanner.next();
System.out.print("Please Select Group:\n"
+ "1 For FRIENDS,\n" +
"2 For FAMILY,\n" +
"3 For WORK,\n" +
"4 For OTHERS");
int enumNum = scanner.nextInt();
Group group;
switch(enumNum) {
case 1:
group=Group.FRIENDS;
break;
case 2:
group=Group.FAMILY;
break;
case 3:
group=Group.WORK;
break;
default:
group=Group.OTHERS;
}//switch end
contacts[i] = new Contact(owner,phoneNum,group);
}//loop end
System.out.println("Insert File name");
String fileName = scanner.next();
File f=null;
for(int i = 0 ; i < val; i++) {
if(i==0) {
f = new File(fileName);
contacts[0].Save(fileName);
}
else {
contacts[i].Save(f);
}
}
}
}
This is Contact Class:
enum Group {
FRIENDS,
FAMILY,
WORK,
OTHERS
};
public class Contact {
private String phoneNumber,owner;
private Group group;
PrintWriter pw = null;
public Contact(String owner ,String phoneNumber,Group group) {
setPhoneNumber(phoneNumber);
setOwner(owner);
setGroup(group);
}
public Contact(String fileName) {
File file = new File(fileName+".txt");
try {
Scanner scanner = new Scanner(file);
phoneNumber=scanner.nextLine();
owner=scanner.nextLine();
String str=scanner.nextLine();
group = Group.valueOf(str);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch(Exception e) {
e.printStackTrace();
}
}
public Contact(File file) {
try {
Scanner scanner = new Scanner(file);
phoneNumber=scanner.nextLine();
owner=scanner.nextLine();
String str=scanner.nextLine();
group = Group.valueOf(str);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch(Exception e) {
e.printStackTrace();
}
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public Group getGroup() {
return group;
}
public void setGroup(Group group) {
this.group = group;
}
public void Save(String fileName) {
File f = new File(fileName+".txt");
try {
if(f.createNewFile()) {
System.out.println("File created");
pw = new PrintWriter(f); //יצירת מדפסת לקובץ
pw.println(phoneNumber+"\n"+owner+"\n"+group+"\n\n\n");
}
} catch (IOException e) {
e.printStackTrace();
}
pw.close();
}
public void Save(File f) {
PrintWriter pw=null;
try {
pw = new PrintWriter(f);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pw.println(phoneNumber+"\n"+owner+"\n"+group);
pw.close();
}
public String toString() {
return phoneNumber+"\n"+owner+"\n"+group;
}
}
Every time you create PrintWriter the file is being overwritten. Since you create a new PrintWriter for each contact, the file contains only the last contact information. What you should do is to create PrintWriter only once and use it for all contacts.
Firstly, let's create a new save method with such signature:
public void save(PrintWriter writer)
I have also used the lowercase name of the method due to Java naming convention.
Now the implementation of save method will look like this:
writer.println(phoneNumber);
writer.println(owner);
writer.println(group + "\n\n\n");
Then we should replace the usage of Save method with the new one. Here is your code:
String fileName = scanner.next();
File f = null;
for (int i = 0; i < val; i++) {
if(i == 0) {
f = new File(fileName);
contacts[0].Save(fileName);
} else {
contacts[i].Save(f);
}
}
In order to fix the issue we can change it like this:
String fileName = scanner.next();
File file = new File(fileName);
try (PrintWriter writer = new PrintWriter(file)) {
for (int i = 0; i < val; i++) {
contacts[i].save(writer);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
I have also used try-with-resources which closes the PrintWriter automatically.
From the Javadoc of the constructor of PrintWriter:
public PrintWriter​(File file)
Parameters: file - The file to use as the destination of this writer. If the file exists then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.
In the Save function you create a PrintWriter everytime. So everytime the file is truncated, and then you lose the contact you saved before.
Since File I/O classes in java use Decorator Design pattern, you can use a FileWriter to take advantage of appending to a file. So you can use this code for Save() method :
public void Save(String fileName) {
File f = new File(fileName+".txt");
try {
//System.out.println("File created"); You don't need to create new file.
FileWriter fw=new FileWriter(f,true):// second argument enables append mode
pw = new PrintWriter(fw); //יצירת מדפסת לקובץ
pw.println(phoneNumber+"\n"+owner+"\n"+group+"\n\n\n");
} catch (IOException e) {
e.printStackTrace();
}
pw.close();
}

Java Cannot instantiate the type Module (Not Abstract Class)

I'm having issues compiling my code. eclipse gives me this error code:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Cannot instantiate the type Module
Cannot instantiate the type Module
at Model.AddModule(Model.java:214)
at Model.loadFromTextFiles(Model.java:129)
at Model.menu(Model.java:98)
at Run.main(Run.java:7)
Here's my model code :
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.*;
import java.util.*;
import com.sun.xml.internal.ws.api.server.Module;
public class Model implements java.io.Serializable {
private Student[] StudentList = new Student[0];
private Module[] ModuleList = new Module[0];
public void runTests() throws FileNotFoundException {
Scanner scan=new Scanner (System.in);
System.out.println("Loading From text files");
scan.nextLine();
loadFromTextFiles();
printReport();
System.out.println("Saving serializable");
scan.nextLine();
saveSer();
System.out.println("Creating a new module(CS12330)");
scan.nextLine();
String[] temp=new String[0];
AddModule("CS12330",temp);
printReport();
System.out.println("Loading from serialixed file");
scan.nextLine();
loadSer();
printReport();
System.out.println("Saving using XML");
scan.nextLine();
saveXML();
System.out.println("Creating a new module(CS15560)");
scan.nextLine();
AddModule("CS15560",temp);
printReport();
System.out.println("Loading from XML file");
scan.nextLine();
loadXML();
printReport();
}
public void menu() throws FileNotFoundException {
while (true) {
System.out.println("Menu");
System.out.println("1-Run Tests");
System.out.println("2-Add Student");
System.out.println("4-Add Module");
System.out.println("5-Add A Student To Module");
System.out.println("6-Save (Text File)");
System.out.println("7-Save (Serialization)");
System.out.println("8-Save (XML)");
System.out.println("9-Load (Text File)");
System.out.println("10-Load (Serialization)");
System.out.println("11-Load (XML)");
Scanner scan=new Scanner (System.in);
String response=scan.nextLine();
if (response.equals("1")){
runTests();
} else if (response.equals("2")) {
System.out.print("Enter UID: ");
String UID=scan.nextLine();
System.out.print("Enter Surname: ");
String surname=scan.nextLine();
System.out.print("Enter First Name: ");
String firstname=scan.nextLine();
System.out.print("Course Code: ");
String courseCode=scan.nextLine();
AddStudent(UID,surname,firstname,courseCode);
} else if (response.equals("4")) {
System.out.print("Enter Module Code: ");
String moduleCode=scan.nextLine();
String[] temp=new String[0];
AddModule(moduleCode,temp);
} else if (response.equals("5")) {
System.out.print("Enter Module Code: ");
String moduleCode=scan.nextLine();
Module m=findAModule(moduleCode);
scan.nextLine();
if(m!=null){
System.out.print("Enter UID: ");
String UID=scan.nextLine();
Student s=findAStudent(UID);
if (s!=null) {
//m.addThisStudent(s);
}else System.out.println("Student Not Found");
}else System.out.println("Module Not Found");
} else if (response.equals("6")) {
saveToTextFiles();
} else if (response.equals("7")) {
saveSer();
} else if (response.equals("8")) {
saveXML();
} else if (response.equals("9")) {
loadFromTextFiles();
} else if (response.equals("10")) {
loadSer();
} else if (response.equals("11")) {
loadXML();
}
}
}
public void loadFromTextFiles() throws FileNotFoundException {
Scanner infile=new Scanner(new InputStreamReader(new FileInputStream("students.txt")));
int num=infile.nextInt();infile.nextLine();
for (int i=0;i<num;i++) {
String u=infile.nextLine();
String sn=infile.nextLine();
String fn=infile.nextLine();
String c=infile.nextLine();
AddStudent(u,sn,fn,c);
}
infile.close();
infile=new Scanner(new InputStreamReader(new FileInputStream("modules.txt")));
num=infile.nextInt();infile.nextLine();
for (int i=0;i<num;i++) {
String c=infile.nextLine();
int numOfStudents=infile.nextInt();infile.nextLine();
String[] students = new String[numOfStudents];
for (int j=0;j<numOfStudents;j++) {
students[j] = infile.nextLine();
}
AddModule(c,students);
}
infile.close();
}
public void saveToTextFiles() {
try {
PrintWriter outfile = new PrintWriter(new OutputStreamWriter (new FileOutputStream("Students.txt")));
outfile.println(StudentList.length);
for(int i=0;i<StudentList.length;i++) {
outfile.println(StudentList[i].getUID());
outfile.println(StudentList[i].getSName());
outfile.println(StudentList[i].getFName());
outfile.println(StudentList[i].getDegree());
}
outfile.close();
outfile = new PrintWriter(new OutputStreamWriter (new FileOutputStream("Modules.txt")));
outfile.println(ModuleList.length);
for(int i=0;i<ModuleList.length;i++) {
outfile.println(ModuleList[i].getCode());
outfile.println(ModuleList[i].getStudents().length);
for (int j=0;j<(ModuleList[i]).getStudents().length;j++) {
outfile.println(ModuleList[i].getStudents()[j]);
}
}
outfile.close();
}
catch(IOException e) {
}
}
public void loadSer() {
Model m =null;
try{
FileInputStream fileIn = new FileInputStream("Model.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
m=(Model) in.readObject();
in.close();
fileIn.close();
}catch (Exception e){}
if (m!=null) {
setStudentList(m.getStudentList());
setModuleList(m.getModuleList());
}
}
public void saveSer() {
try {
FileOutputStream fileOut = new FileOutputStream("Model.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(this);
out.close();
fileOut.close();
} catch(IOException e) {}
}
public void loadXML() {
try {
Model m = null;
XMLDecoder decoder = new XMLDecoder (new BufferedInputStream (new FileInputStream("model.xml")));
m = (Model) decoder.readObject();
decoder.close();
setStudentList(m.getStudentList());
setModuleList(m.getModuleList());
} catch (IOException e) {
e.printStackTrace();
}
}
public void saveXML() {
try {
Model m = null;
XMLEncoder encoder = new XMLEncoder (new BufferedOutputStream (new FileOutputStream("model.xml")));
encoder.writeObject(this);
encoder.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void AddModule(String c, String[] students) {
int length = ModuleList.length;
Module NewArray[]=new Module[length+1];
for (int i=0;i<length+1;i++) {
if (i<length) {
NewArray[i]=new Module(ModuleList[i]);
}
}
NewArray[length]=new Module(c, students);
ModuleList = NewArray.clone();
}
private void AddStudent(String u, String sn, String fn, String c) {
int length = StudentList.length;
Student NewArray[]=new Student[StudentList.length+1];
for (int i=0;i<StudentList.length+1;i++) {
if (i<length) {
NewArray[i]=new Student(StudentList[i]);
}
}
NewArray[length]=new Student(u,sn,fn,c);
StudentList = NewArray.clone();
}
public void printReport() {
for (int i= 0;i<ModuleList.length;i++) {
System.out.println(ModuleList[i].toString(this));
}
}
public Student findAStudent(String UID) {
for(int i=0;i<StudentList.length;i++) {
if (StudentList[i].getUID().compareTo(UID)==0) {
return StudentList[i];
}
}
return null;
}
public Module findAModule(String moduleCode) {
for(int i=0;i<ModuleList.length;i++) {
if (ModuleList[i].getCode().compareTo(moduleCode)==0) {
return ModuleList[i];
}
}
return null;
}
public Module[] getModuleList() {
return ModuleList;
}
public Student[] getStudentList() {
return StudentList;
}
public void setModuleList(Module[] m) {
ModuleList=m.clone();
}
public void setStudentList(Student[] s) {
StudentList=s.clone();
}
}
And here's my module code:
public class Module{
private String Code;
private String[] students = new String[0];
public Module (){};
public Module(String c, String[] s) {
Code=c;
students=s;
}
public Module(Module module) {
Code=module.getCode();
students=module.getStudents();
}
public String[] getStudents() {
return students;
}
public String getCode() {
return Code;
}
public void addThisStudent(Student s) {
AddStudent(s.getUID());
}
public String toString(Model mod) {
String studentString ="";
if (students.length == 0) {
studentString = "\n No Students";
}else {
for (int i=0;i<students.length;i++) {
Student s = mod.findAStudent(students[i]);
if (s!=null) {
studentString += "\n "+s.toString();
}
}
}
return Code + studentString;
}
private void AddStudent(String UIDToAdd) {
int length = students.length;
String NewArray[]=new String[students.length+1];
for (int i=0;i<length;i++) {
NewArray[i] = students[i];
}
NewArray[length] = UIDToAdd;
students = NewArray.clone();
}
}
I honestly have no idea why this is happening. I've googled my error before and I only found issues that involved abstract classes.
You are importing the wrong Module - you are importing:
import com.sun.xml.internal.ws.api.server.Module;
You need to import your own Module.
That's because your imported "com.sun.xml.internal.ws.api.server.Module" in your Model class. Try taking that out and importing your.package.Module instead.

I need to get a file reader to read a text file line by line and format them in Java

I have a text file, formatted as follows:
Han Solo:1000
Harry:100
Ron:10
Yoda:0
I need to make an arrayList of objects which store the player's name (Han Solo) and their score (1000) as attributes. I would like to be able to make this arrayList by reading the file line by line and splitting the string in order to get the desired attributes.
I tried using a Scanner object, but didn't get far. Any help on this would be greatly appreciated, thanks.
You can have a Player class like this:-
class Player { // Class which holds the player data
private String name;
private int score;
public Player(String name, int score) {
this.name = name;
this.score = score;
}
// Getters & Setters
// Overrride toString() - I did this. Its optional though.
}
and you can parse your file which contains the data like this:-
List<Player> players = new ArrayList<Player>();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt"))); // I used BufferedReader instead of a Scanner
String line = null;
while ((line = br.readLine()) != null) {
String[] values = line.split(":"); // Split on ":"
players.add(new Player(values[0], Integer.parseInt(values[1]))); // Create a new Player object with the values extract and add it to the list
}
} catch (IOException ioe) {
// Exception Handling
}
System.out.println(players); // Just printing the list. toString() method of Player class is called.
You can create a Class call player. playerName and score will be the attributes.
public class Player {
private String playerName;
private String score;
// getters and setters
}
Then you can create a List
List<Player> playerList=new ArrayList<>();
Now you can try to do your task.
Additionally, you can read from file and split each line by : and put first part as playerName and second part as score.
List<Player> list=new ArrayList<>();
while (scanner.hasNextLine()){
String line=scanner.nextLine();
Player player=new Player();
player.setPlayerName(line.split(":")[0]);
player.setScore(line.split(":")[1]);
list.add(player);
}
If you have Object:
public class User
{
private String name;
private int score;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getScore()
{
return score;
}
public void setScore(int score)
{
this.score = score;
}
}
Make an Reader class that reads from the file :
public class Reader
{
public static void main(String[] args)
{
List<User> list = new ArrayList<User>();
File file = new File("test.txt");
BufferedReader reader = null;
try
{
reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null)
{
String[] splitedString = line.split(":");
User user = new User();
user.setName(splitedString[0]);
user.setScore(Integer.parseInt(splitedString[1]));
list.add(user);
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if (reader != null)
{
try
{
reader.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
for (User user : list)
{
System.out.println(user.getName()+" "+user.getScore());
}
}
}
The output will be :
Han Solo 1000
Harry 100
Ron 10
Yoda 0
Let's assume you have a class called Player that comprises two data members - name of type String and score of type int.
List<Player> players=new ArrayList<Player>();
BufferedReader br=null;
try{
br=new BufferedReader(new FileReader("filename"));
String record;
String arr[];
while((record=br.readLine())!=null){
arr=record.split(":");
//Player instantiated through two-argument constructor
players.add(new Player(arr[0], Integer.parseInt(arr[1])));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally{
if(br!=null)
try {
br.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
For small files (less than 8kb), you can use this
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class NameScoreReader {
List<Player> readFile(final String fileName) throws IOException
{
final List<Player> retval = new ArrayList<Player>();
final Path path = Paths.get(fileName);
final List<String> source = Files.readAllLines(path, StandardCharsets.UTF_8);
for (final String line : source) {
final String[] array = line.split(":");
if (array.length == 2) {
retval.add(new Player(array[0], Integer.parseInt(array[1])));
} else {
System.out.println("Invalid format: " + array);
}
}
return retval;
}
class Player {
protected Player(final String pName, final int pScore) {
super();
this.name = pName;
this.score = pScore;
}
private String name;
private int score;
public String getName()
{
return this.name;
}
public void setName(final String name)
{
this.name = name;
}
public int getScore()
{
return this.score;
}
public void setScore(final int score)
{
this.score = score;
}
}
}
Read the file and convert it to string and split function you can apply for the result.
public static String getStringFromFile(String fileName) {
BufferedReader reader;
String str = "";
try {
reader = new BufferedReader(new FileReader(fileName));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append("\n");
}
str = stringBuilder.toString();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public static void main(String[] args) {
String stringFromText = getStringFromFile("C:/DBMT/data.txt");
//Split and other logic goes here
}

How to Serialize an ArrayLIst in java without getting errors?

I am just trying to output a previously created ArrayList to serialise it for future storage.
but when I attmept to do so I get the runTime error "notSerialisableException: Department.
Is their a speicial way of serializing an arrayList??
Would someone be able to tell me why I may be getting this error.
This is the code:
import java.awt.*;
import java.util.*;
import java.io.*;
import java.io.Serializable;
public class tester1ArrayListObjectSave
{
private ArrayList <Department> allDeps = new ArrayList<Department>();
private int choice = 0;
private String name;
private String loc;
Department theDepartment;
Scanner scan;
public static void main(String[] args)
{
new tester1ArrayListObjectSave();
}
public tester1ArrayListObjectSave()
{
scan = new Scanner(System.in);
options();
}
public void options()
{
System.out.println("wadya wanna do");
System.out.println("1. create a new department");
System.out.println("2. read from text file");
System.out.println("4. save it to system as a serializable file");
System.out.println(". read from text file");
System.out.println("3. to exit");
choice = scan.nextInt();
workOutOptions();
}
public void workOutOptions()
{
if (choice ==1)
{
createNewEmp();
}
else if (choice ==2)
{
try
{
readTextToSystem();
}
catch (IOException exc)
{
System.out.println("uh oh their was an error: "+exc);
}
}
else if (choice == 3)
{
System.exit(0);
}
else if (choice ==4)
{
try
{
createSerialisable();
}
catch (IOException exc)
{
System.out.println("sorry could not serialise data cause of this:"+exc);
}
}
else
{
System.out.println("do nothing");
}
}
public void createNewEmp()
{
System.out.println("What is the name");
name = scan.next();
System.out.println("what is the chaps loc");
loc = scan.next();
try
{
saveToSystem();
}
catch (IOException exc)
{
// do something here to deal with problems
}
theDepartment = new Department(name,loc);
allDeps.add(theDepartment);
options();
}
public void saveToSystem() throws IOException
{
FileOutputStream fos = new FileOutputStream( "backUp.txt", true );
PrintStream outFile = new PrintStream(fos);
System.out.println("added to system succesfully");
outFile.println(name);
outFile.println(loc);
outFile.close();
options();
}
public void readTextToSystem() throws IOException
{
Scanner inFile = new Scanner ( new File ("backUp.txt") );
while (inFile.hasNextLine())
{
name=inFile.nextLine();
System.out.println("this is the name: "+name);
loc = inFile.nextLine();
System.out.println("this is the location: "+loc);
Department dDepartment = new Department(name,loc);
allDeps.add(dDepartment);
options();
}
System.out.println(allDeps);
}
public void createSerialisable() throws IOException
{
FileOutputStream fileOut = new FileOutputStream("theBkup.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(allDeps);
options();
}
}
ArrayList isn't the problem; your Department object is.
You need to implement the Serializable interface in that object.

Categories

Resources