How to sort a file by grade? - java

This is a complete program that sorts the file by ID. However, I would like to sort it by grade. I modified it several times but it doesn't seem to work. Could someone please direct me where to change the ID to grade. Also, do you think this code can be simplified or are there any other code simpler than this code.
Sorry for the bad indentation, this source code can also be found here.
student.txt file:
4 A 87 A
5 B 99 A+
1 C 75 A
2 D 55 C
3 E 68 B
source:
import java.io.*;
import java.util.*;
class ShowData implements Comparable {
int id;
String name;
int marks;
String grade;
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setMarks(int marks) {
this.marks = marks;
}
public int getMarks() {
return marks;
}
public void setGrade(String grade) {
this.grade = grade;
}
public String getGrade() {
return grade;
}
public int compareTo(Object Student) throws ClassCastException {
if (!(Student instanceof ShowData))
throw new ClassCastException("Error");
int ide = ((ShowData) Student).getId();
return this.id - ide;
}
}
public class SortFile {
SortFile() {
int j = 0;
ShowData data[] = new ShowData[5];
try {
FileInputStream fstream = new FileInputStream("C:/student.txt");
// Use DataInputStream to read binary NOT text.
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
ArrayList list = new ArrayList();
while ((strLine = br.readLine()) != null) {
list.add(strLine);
}
Iterator itr;
for (itr = list.iterator(); itr.hasNext();) {
String str = itr.next().toString();
String[] splitSt = str.split(" ");
String id = "", name = "", marks = "", grade = "";
for (int i = 0; i < splitSt.length; i++) {
id = splitSt[0];
name = splitSt[1];
marks = splitSt[2];
grade = splitSt[3];
}
data[j] = new ShowData();
data[j].setId(Integer.parseInt(id));
data[j].setName(name);
data[j].setMarks(Integer.parseInt(marks));
data[j].setGrade(grade);
j++;
}
Arrays.sort(data);
File file = new File("C:/new.txt");
FileWriter fw = new FileWriter(file, true);
BufferedWriter out = new BufferedWriter(fw);
System.out.println("********Sorted by id********");
String strVal = "";
for (int i = 0; i < 5; i++) {
ShowData show = data[i];
int no = show.getId();
String name = show.getName();
int marks = show.getMarks();
String grade = show.getGrade();
System.out.println(no + " " + name + " " + marks + " " + grade);
String d = no + " " + name + " " + marks + " " + grade;
ArrayList al = new ArrayList();
al.add(d + "\n");
Iterator itr1 = al.iterator();
while (itr1.hasNext()) {
out.write(itr1.next().toString());
out.newLine();
}
}
out.close();
} catch (Exception e) {
}
}
public static void main(String[] args) {
SortFile data = new SortFile();
}
}

The compareTo() method is currently comparing the IDs, not the grades. Try compare the
marks instead.

Related

why is updateStocks() not changing price?

I have a method to read a text file of five stocks using Scanner and delimiter. I also have a method which should take a double multiplier and an array of stock objects and change the price with that multiplier. The method which reads the stock file functions correctly, however, when I attempt to change the stock objects that have been assigned values with the filereading method, it does not change the price. After I use method updateStocks(), I test stock[1] to see if the value has changed and it has not.
After I run this:
public class Main {
public static void main (String args[]) {
// stock object with which to call methods
Stock theStock = new Stock("", "", 0);
// this array holds the stocks to be read
Stock[] stocks = new Stock[100];
// here is the multiplier I am attempting to use
double multiplier = 1/3;
// first I read in the stocks file
theStock.readStocksWithScanner(stocks);
// then I call the updateStockPrices method
theStock.updateStockPrices(multiplier,stocks);
// lastly, I test to see if the method has functioned correctly
System.out.println(stocks[1]);
}
}
This is my output:
Apple AAPLE 152.70
Alphabet GOOGLE 873.96
IBM IBM 194.37
Microsoft MSFT 65.67
Oracle ORCLE 62.82
Company name: Apple Stock symbol: AAPLE Stock Price: 152.7
Press any key to continue . . .
Here is the method updateStockPrices:
// this is the method which does not seem to function as intended
public void updateStockPrices(double multiplier, Stock[] objects)
{
// I loop to the length of the array in the parameter
for(int i = 1; i < objects.length; i++)
{
// try to manipulate the stock
try{
double subtractThis = stocks[i].getPrice() * multiplier;
objects[i].setPrice(stocks[i].getPrice() - subtractThis);
}// and catch any null objects
catch(NullPointerException e){
// if null I then increment the counter
i++;}
// Is code missing in order for this to function as intended? or have I made a mistake?
}
}
and here is stocks.java:
import java.util.Scanner ;
import java.util.InputMismatchException ;
import java.io.FileInputStream ;
import java.io.IOException ;
import java.io.FileNotFoundException ;
import java.io.PrintWriter ;
public class Stock {
private static final double MULTIPLIER = (1/3);
public static final String FILE_NAME = "stocks1.txt";
public String newFile = "stocks2.txt";
public static final String FORMAT = "%-10s%6s\t%.2f%n";
private PrintWriter writer = null;
private String name = "";
private String symbol = "";
private double price = 0;
protected Stock stocks[] = new Stock[100];
FileInputStream inputStream = null;
String workingDirectory = System.getProperty("user.dir");
String absolutePath = workingDirectory + "\\" + FILE_NAME;
public Stock(String aName, String aSymbol, double aPrice)
{
this.name = aName;
this.symbol = aSymbol;
this.price = aPrice;
}
// the fileReading method reads the stocks in
public void readStocksWithScanner(Stock[] stocks)
{
this.stocks = stocks;
String workingDirectory = System.getProperty("user.dir");
String absolutePath = workingDirectory + "\\" + FILE_NAME;
FileInputStream inputStream = null;
try{
inputStream = new FileInputStream(absolutePath);
}
catch (FileNotFoundException e)
{
System.out.println("File not found: " + FILE_NAME);
System.out.println("Exiting program.");
System.exit(0) ;
}
Scanner inputFile = new Scanner(inputStream);
int lineNumber = 1;
try{
while(inputFile.hasNextLine())
{
inputFile.useDelimiter(",");
String name = inputFile.next();
inputFile.useDelimiter(",");
String symbol = inputFile.next();
inputFile.useDelimiter("[,\\s]") ;
Double thePrice = inputFile.nextDouble();
inputFile.nextLine();
// here the stocks are given the values found in the text file and initialized above
stocks[lineNumber] = new Stock(name, symbol, thePrice);
// I print them out using a format constant, in order to ensure the method has functioned correcly
System.out.printf(FORMAT, name, symbol, thePrice);
// then I increment the lineNumber
lineNumber++;
}
// I close the stream and should be left with a partially filled array of stock items
inputStream.close();
}catch (IOException e) {
System.out.println("Error reading line " + lineNumber + " from file " + FILE_NAME) ;
System.exit(0) ;
}
catch(InputMismatchException e) {
System.out.println("Couldn't convert price to a number on line " + lineNumber) ;
System.exit(0) ;}
}
public void setName(String name)
{
this.name = name;
}
public void setSymbol(String symbol)
{
this.symbol = symbol;
}
public void setPrice(double aPrice)
{
this.price = aPrice;
}
public String getName()
{
return name;
}
public String getSymbol()
{
return symbol;
}
public double getPrice()
{
return price;
}
public boolean equals(Object other)
{
if(other.getClass() != getClass() || other == null )
{
return false;
}
Stock stock = (Stock) other;
{
if(stock.getName() == getName() && stock.getSymbol() == getSymbol() && stock.getPrice() == getPrice())
{
return true;
}
return false;
}
}
public String toString()
{
return "Company name: " + getName() + " Stock symbol: " + getSymbol() + " Stock Price: " + getPrice();
}
// this is the method which does not seem to function as intended
public void updateStockPrices(double multiplier, Stock[] objects)
{
// I loop to the length of the array in the parameter
for(int i = 1; i < objects.length; i++)
{
// try to manipulate the stock
try{
double subtractThis = stocks[i].getPrice() * multiplier;
objects[i].setPrice(stocks[i].getPrice() - subtractThis);
}// and catch any null objects
catch(NullPointerException e){
// if null I then increment the counter
i++;}
// Is code missing in order for this to function as intended? or have I made a mistake?
}
}
public void createStocks(int stockAmount)
{
Stock[] stocks = new Stock[stockAmount];
}
public void writeStocks(String fileName, Stock[] objects)
{
try{
writer = new PrintWriter(fileName);
}
catch(FileNotFoundException e){
System.out.println("Couldn't create file " + fileName);
System.exit(0);
}
for(Stock s: objects)
{
writer.printf(FORMAT, getName(), getSymbol(), getPrice());
if(objects == null)
writer.close() ;
}
}
public Stock[] getStocks()
{
return stocks;
}
}
simple test
double multiplier = 1/3;
System.out.println(multiplier);
compared to
double multiplier = 1/3f;
System.out.println(multiplier);

Finding Max of Array of Objects/Writing To File

I am trying to find the max score from the array of objects. The code for that is everything below the int maxValue = -1; line of code. I am also trying to write that bands information to an external file:
import java.io.FileWriter;
public class App {
public static void main(String[] args) {
Bands[] bands = new Bands[5];
bands[0] = new Bands("Joe", "Rick", "Nick", "Dalton", "Doylestown, PA", "RockOn", 4000.50 , "Rock");
bands[1] = new Bands("Luke", "Bill", "Ian", "Matt", "State College, PA", "Blink182", 3500.50 , "Alternative");
bands[2] = new Bands("Corey", "Noah", "Jon", "Kaleb", "Philadelphia, PA", "Rise Against", 10000.50 , "Rock");
bands[3] = new Bands("Jake", "Joey", "Mike", "Mac", "New York, NY", "Thousand Foot Krutch", 2000.50 , "Rock");
bands[4] = new Bands("Bob", "Jeff", "Dom", "Mark", "King of Prussia, PA", "Skillet", 5500.50 , "Rock");
bands[0].compete();
bands[1].compete();
bands[2].compete();
bands[3].compete();
bands[4].compete();
for (int i = 0; i < 5; i++) {
String bandInfo = bands[i].getInfo();
System.out.println(bandInfo);
}
System.out.println("");
//DOESNT WORK BEYOND THIS POINT
int maxValue = -1;
for (int i = 0; i < bands.length; i++) {
if (bands[i].compete() > maxValue) {
maxValue = bands[i].compete();
}
}
try {
FileWriter fw = new FileWriter("src/winners.txt", true);
fw.write(bandInfo + "\n");
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
And then here is my Bands class code:
import java.util.Random;
public class Bands {
private String singerName;
private String guitarName;
private String bassistName;
private String drummerName;
private String Hometown;
private String bandName;
private double income;
private String genre;
private int score;
private int winningBand;
public Bands(String singerName, String guitarName, String bassistName, String drummerName, String Hometown, String bandName, double income, String genre)
{
this.singerName = singerName;
this.guitarName = guitarName;
this.bassistName = bassistName;
this.drummerName = drummerName;
this.bandName = bandName;
this.Hometown = Hometown;
this.income = income;
this.genre = genre;
this.score = -1;
this.winningBand = -1;
}
public void compete()
{
Random rand = new Random();
this.score = rand.nextInt(20);
}
public int getScore()
{
return this.score;
}
public String getInfo()
{
String bandInfo = "Band: " + this.bandName + ", Singer: " + this.singerName + ", Guitarist: " + this.guitarName + ", Bassist: " + this.bassistName +
", Drummer: " + this.drummerName + ", Hometown: " + this.Hometown + ", Income: " + this.income + ", Genre: " +
this.genre + ", Final Score: " + this.score;
return bandInfo;
}
}
As for your question about only printing band with highest score info:
Create a global variable (In this case I called it winningBand as an Integer)
Then edit your loop:
for (int i = 0; i < bands.length; i++) {
if (bands[i].getScore() > maxValue) {
maxValue = bands[i].getScore();
winningBand = i;
}
}
Then when you write to the file, only write the winningBand:
try {
FileWriter fw = new FileWriter("src/winners.txt", true);
fw.write(band[winningBand].getInfo);
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
You are trying to find the highest score? Well in your code below
for (int i = 0; i < bands.length; i++) {
if (bands[i].compete() > maxValue) {
maxValue = bands[i].compete();
}
}
When you say .compete(), this does nothing. It assigns a random score in the Bands class. Instead it should look like this if you want to compare scores.
for (int i = 0; i < bands.length; i++) {
if (bands[i].getScore() > maxValue) {
maxValue = bands[i].getScore();
}
}
NOTE: You need to write a getScore() method in the band class that returns the score like the one below:
public Integer getScore(){
return score;
}
As for your question about writing to the file, this should work:
try {
FileWriter fw = new FileWriter("src/winners.txt", true);
for(int i = 0; i <= 4; i++){
fw.write(band[i].getInfo + "\n");
}
fw.close();
} catch (Exception e) {
e.printStackTrace();
}

How do I export the ArrayList to a CSV file

I have this code, it gets the average grade, but I need to export the arraylist Hell to a CSV file. How do I do this?
import java.util.*;
import java.io.*;
import java.io.PrintWriter;
import java.text.*;
public class hello3 {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.printf("Please enter the name of the input file: ");
String input_name = in.next();
System.out.printf("Please enter the name of the output CSV file: ");
String csv_name = in.next();
System.out.printf("Please enter the name of the output pretty-print file: ");
String pretty_name = in.next();
processGrades(input_name, csv_name, pretty_name);
System.out.printf("\nExiting...\n");
}
public static void processGrades (String input_name, String csv_name, String pretty_name)
{
PrintWriter csv = null;
PrintWriter pretty = null;
String[][] data = readSpreadsheet(input_name);
boolean resultb = sanityCheck(data);
int length = data.length;
ArrayList<String> test_avg = new ArrayList<String>();
ArrayList<String> HW_avg = new ArrayList<String>();
ArrayList<String> NAME = new ArrayList<String>();
ArrayList<String> ColN = new ArrayList<String>();
ArrayList<String> Hell = new ArrayList<String>();
for(int row = 1; row<length; row++)
{
String name = data[row][0];
String name2 = data[row][1];
String Name = name+" "+name2;
int test1 = Integer.parseInt(data[row][2]);
int test2 = Integer.parseInt(data[row][3]);
int test3 = Integer.parseInt(data[row][4]);
int Test = (test1+test2+test3)/3;
String Testav = Integer.toString(Test);
int hw1 = Integer.parseInt(data[row][5]);
int hw2 = Integer.parseInt(data[row][6]);
int hw3 = Integer.parseInt(data[row][7]);
int hw4 = Integer.parseInt(data[row][8]);
int hw5 = Integer.parseInt(data[row][9]);
int hw6 = Integer.parseInt(data[row][10]);
int hw7 = Integer.parseInt(data[row][11]);
int HW = (hw1+hw2+hw3+hw4+hw5+hw6+hw7)/7;
int[] trying = {Test, HW};
int low = find_min(trying);
String grade = null;
if(low>=90)
{
grade ="A";
}
if(low < 90&& low>= 80)
{
grade = "B";
}
if(low <80&&low>=70)
{
grade ="C";
}
if(low<70&&low>=60)
{
grade="D";
}
if(low<60)
{
grade = "F";
}
String Lows = Integer.toString(low);
String HWav = Integer.toString(HW);
test_avg.add(Testav);
HW_avg.add(HWav);
NAME.add(Name);
Hell.add(Name);
Hell.add(Testav);
Hell.add(HWav);
Hell.add(Lows);
Hell.add(grade);
System.out.println(Hell);
System.out.printf("\n");
}
}
public static int find_min(int[] values)
{
int result = values[0];
for(int i = 0; i<values.length; i++)
{
if(values[i]<result)
{
result = values[i];
}
}
return result;
}
public static boolean sanityCheck(String[][] data)
{
if (data == null)
{
System.out.printf("Sanity check: nul data\n");
return false;
}
if(data.length<3)
{
System.out.printf("Sanity check: %d rows\n",data.length);
return false;
}
int cols= data[0].length;
for(int row = 0; row<data.length; row++)
{
int current_cols = data[row].length;
if(current_cols!=cols)
{
System.out.printf("Sanity Check: %d columns at rows%d\n", current_cols, row);
return false;
}
}
return true;
}
public static String[][] readSpreadsheet(String filename)
{
ArrayList<String> lines = readFile(filename);
if (lines == null)
{
return null;
}
int rows = lines.size();
String[][] result = new String[rows][];
for (int i = 0; i < rows; i++)
{
String line = lines.get(i);
String[] values = line.split(",");
result[i] = values;
}
return result;
}
public static ArrayList<String> readFile(String filename)
{
File temp = new File(filename);
Scanner input_file;
try
{
input_file = new Scanner(temp);
} catch (Exception e)
{
System.out.printf("Failed to open file %s\n",
filename);
return null;
}
ArrayList<String> result = new ArrayList<String>();
while (input_file.hasNextLine())
{
String line = input_file.nextLine();
result.add(line);
}
input_file.close();
return result;
}
}
Any help would be appreciated. thank you.
Broadly, you need to open a file with the name you require, and a writer in a loop - like this:
File csvFile = new File(csvName);
try (PrintWriter csvWriter = new PrintWriter(new FileWriter(csvFile));){
for(String item : list){
csvWriter.println(item);
}
} catch (IOException e) {
//Handle exception
e.printStackTrace();
}
Obviously you will have to print some commas as required

How to copy by reference and deserialize a list of objects in java?

So I am a beginner in Java and my professor has us doing this assignment and I've been looking around but I can't seem to find the right answer for my type of code. We had to create a class file and then a public class file to test it.
import java.io.Serializable;
public class Person implements Serializable {
String Fname = new String();
String MI = new String();
String Lname = new String();
String age = new String();
String gpa = new String();
// int age = 20;
// double gpa = 0.0;
String Major = new String();
String answer;
//***********************************************
// The methods declared will go below
// The first method is for the first name
public String getFname() {
return Fname;
}
public void setFname(String Fname) {
this.Fname = Fname;
}
// This method is for the Middle Initial
public String getMI() {
return MI;
}
public void setMI(String MI) {
this.MI = MI;
}
// This method is for the Last name
public String getLname() {
return Lname;
}
public void setLname(String Lname) {
this.Lname = Lname;
}
// This method is for the Age
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
// This method is for the GPA
public String getGpa() {
return gpa;
}
public void setGpa(String gpa) {
this.gpa = gpa;
}
// This method is for the Major
public String getMajor() {
return Major;
}
public void setMajor(String Major) {
this.Major = Major;
}
}
The Person.java code is Serializable is supposed to be written to a fhm file and then Deserialized in order to print the contents of the file into terminal (Unix). Below is the main code which is the TestPerson code that will read the class Person code.
import java.util.Scanner;
import java.io.*;
public class TestPerson {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Person[] Peeps = new Person[3];
Peeps[0] = new Person();
Peeps[1] = new Person();
Peeps[2] = new Person();
Scanner scan = new Scanner(System.in);
String Answer = new String();
String age1 = new String();
String gpa1 = new String();
for (int i = 0; i < Peeps.length - 1; i++) {
// for (int i = 0; i < 3; i++) {
System.out.print("What is the First Name? ");
Answer = scan.nextLine();
Peeps[i].setFname(Answer);
System.out.print("What is MI? ");
Answer = scan.nextLine();
Peeps[i].setMI(Answer);
System.out.print(" What is Last Name? ");
Answer = scan.nextLine();
Peeps[i].setLname(Answer);
System.out.print(" What is the Age? ");
age1 = scan.nextLine();
int age = Integer.parseInt(age1);
// age = scan.nextInt();
Peeps[i].setAge(age1);
System.out.print(" What is the GPA? ");
gpa1 = scan.nextLine();
double gpa = Double.parseDouble(gpa1);
Peeps[i].setGpa(gpa1);
System.out.print(" What is the Major? ");
Answer = scan.nextLine();
Peeps[i].setMajor(Answer);
}
for (int i = 0; i < 3; i++) {
System.out.print(Peeps[i]);
}
try {
FileOutputStream fileOut = new FileOutputStream("Peeps.fhm");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(Peeps);
out.close();
fileOut.close();
System.out.println("\nSerialization Successful\n");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fileIn = new FileInputStream("Peeps.fhm");
ObjectInputStream in = new ObjectInputStream(fileIn);
System.out.println("Deserialized Data: \n" + in.readObject().toString());
in.close();
fileIn.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
My professor wants me to prompt the user to enter data for two of the Person objects at the Terminal and then copy the reference to one of two populated Persons to the last Person. Then the program will write all three Persons to a disk file with the extension of ".fhm" (Which I have completed). My question is how do I copy the reference? My second question is also how do I properly deserialize the file because when I run it, it works but the issue that pops up is that it tells me this:
Deserialized Data:
[LPerson;#5e481248
He wants it to print the information that was inputted by the user. I checked the fhm file that it writes to and it gathers all the information so I'm not sure what I'm doing wrong. Any help would be appreciated guys, sorry the post is kind of long. Thanks in advance.
I'm not sure what you meant by the "copy the reference" part.
The deserialization seems to be working well.
But in your code you're effectively just calling .toString() to print an array, which is probably not what you want.
You probably want to iterate over the items and print them one by one:
FileInputStream fileIn = new FileInputStream("Peeps.fhm");
ObjectInputStream in = new ObjectInputStream(fileIn);
Person[] peeps = in.readObject();
System.out.println("Deserialized Data:");
for (Person person : peeps) {
System.out.printf("First Name: %s MI: %s Last Name: %s%n",
person.getFname(), person.getMI(), person.getLname());
}
Your object is basically a Java array. To print it out, you could use:
System.out.println("Deserialized Data: \n" + Arrays.toString(in.readObject()));

EOFException using random access files

I'm using random access files to write a raf using an arrayList store. I do not know if it can be done, but I'm giving it a try because it is the best solution for me to create this application.
Here is the run-time error that I am getting:
Exception in thread "main" java.io.EOFException
at java.io.RandomAccessFile.readChar(Unknown Source)
at Student.read(Student.java:93)
at MainApp.start(MainApp.java:60)
at MainApp.main(MainApp.java:17)
And here is my code:
MainApp
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
public class MainApp
{
public static void main(String[] args) throws Exception
{
new MainApp().start();
}
public void start()throws Exception
{
StudentStore details = new StudentStore();
//Student a = new Student("Becky O'Brien", "DKIT26", "0876126944", "bexo#hotmail.com");
//details.print();
RandomAccessFile raf = new RandomAccessFile("ContactDetails.txt", "rw");
Student a = new Student("Becky O'Brien", "DKIT26", "0876126944", "bexo#hotmail.com");
Student b = new Student("Fabio Borini", "DKIT28", "0876136944", "fabioborini#gmail.com");
Student c = new Student("Gaston Ramirez", "DKIT29", "0419834501", "gramirez#webmail.com");
Student d = new Student("Luis Suarez", "DKIT7", "0868989878", "luissuarez#yahoo.com");
Student e = new Student("Andy Carroll", "DKIT9", "0853456788", "carroll123#hotmail.com");
details.add(a);
details.add(b);
details.add(c);
details.add(d);
details.add(e);
for (int i = 0; i < details.size(); i++)
{
//a.setStudentName(a[i]);
//a.setLastName(lnames[i]);
// a.setAddress(addresses[i]);
// a.setAge(ages[i]);
// a.setSalary(salaries[i]);
a.write(raf);
}
raf = new RandomAccessFile("employee.dat", "rw");
// er = new Student();
int numRecords = (int) raf.length() / details.size();
for (int i = 0; i < numRecords; i++) {
a.read(raf);
System.out.print(a.getStudentName() + " ");
System.out.print(a.getStudentId() + " ");
System.out.print(a.getStudentEmail() + " ");
System.out.print(a.getStudentTelephoneNumber() + " ");
}
raf.seek(0);
for (int i = 0; i < numRecords; i++)
{
a.read(raf);
raf.seek(raf.getFilePointer() - details.size());
a.write(raf);
raf.seek(raf.getFilePointer() - details.size());
a.read(raf);
}
System.out.print(a.getStudentName() + " ");
System.out.print(a.getStudentId() + " ");
System.out.print(a.getStudentEmail() + " ");
System.out.print(a.getStudentTelephoneNumber() + " ");
}
}
Student
import java.io.IOException;
import java.io.RandomAccessFile;
public class Student
{
//---------------------------------------------------------------------------
// Class Variables.
//---------------------------------------------------------------------------
private String studentName;
private String studentId;
private String studentTelephoneNumber;
private String studentEmail;
//---------------------------------------------------------------------------
// Constructor.
//---------------------------------------------------------------------------
public Student(String studentName, String studentId,String studentTelephoneNumber, String studentEmail)
{
this.studentName = studentName;
this.studentId = studentId;
this.studentTelephoneNumber = studentTelephoneNumber;
this.studentEmail = studentEmail;
}
//---------------------------------------------------------------------------
// Getters.
//---------------------------------------------------------------------------
public String getStudentName()
{
return studentName;
}
public String getStudentId()
{
return studentId;
}
public String getStudentTelephoneNumber()
{
return studentTelephoneNumber;
}
public String getStudentEmail()
{
return studentEmail;
}
//---------------------------------------------------------------------------
// Setters.
//---------------------------------------------------------------------------
public void setStudentName(String studentName)
{
this.studentName = studentName;
}
public void setStudentId(String studentId)
{
this.studentId = studentId;
}
public void setStudentTelephoneNumber(String studentTelephoneNumber)
{
this.studentTelephoneNumber = studentTelephoneNumber;
}
public void setStudentEmail(String studentEmail)
{
this.studentEmail = studentEmail;
}
//---------------------------------------------------------------------------
// toString.
//---------------------------------------------------------------------------
public String toString()
{
return "---------------------------Student--------------------------- " +
"\nStudent Name:" + studentName +
"\nStudent Id:"+ studentId +
"\nStudent Telephone Number:"+ studentTelephoneNumber +
"\nStudent Email:" + studentEmail;
}
void read(RandomAccessFile raf) throws IOException
{
char[] temp = new char[15];
for (int i = 0; i < temp.length; i++)
temp[i] = raf.readChar();
studentName = new String(temp);
temp = new char[15];
for (int i = 0; i < temp.length; i++)
temp[i] = raf.readChar();
studentId = new String(temp);
temp = new char[30];
for (int i = 0; i < temp.length; i++)
temp[i] = raf.readChar();
studentEmail = new String(temp);
temp = new char[30];
for (int i = 0; i < temp.length; i++)
temp[i] = raf.readChar();
studentTelephoneNumber = new String(temp);
temp = new char[30];
for (int i = 0; i < temp.length; i++)
temp[i] = raf.readChar();
}
void write(RandomAccessFile raf) throws IOException
{
StringBuffer sb;
if (studentName != null)
sb = new StringBuffer(studentName);
else
sb = new StringBuffer();
sb.setLength(15);
raf.writeChars(sb.toString());
if (studentId != null)
sb = new StringBuffer(studentId);
else
sb = new StringBuffer();
sb.setLength(15);
raf.writeChars(sb.toString());
if (studentEmail != null)
sb = new StringBuffer(studentEmail);
else
sb = new StringBuffer();
sb.setLength(30);
raf.writeChars(sb.toString());
if (studentTelephoneNumber != null)
sb = new StringBuffer(studentTelephoneNumber);
else
sb = new StringBuffer();
sb.setLength(30);
raf.writeChars(sb.toString());
}
}
You are reading beyond the end of the file. Reading data that isn't there.
The basic problem is that you are reading more data than you are writing.
You are reading 30 char at the end of each record which you didn't write. Given you discard them it appears you don't need to be doing this. I would delete the code which reads after studentTelephoneNumber
If load just one detail do you get the problem? I think your problem is that you are reading off the end of the file. Your read function which reads 15/30 characters seem dangerous because you may not have written that much. Why not read until you get a comma or some other separator? (eg tab)
It's this sort of thing that looks dangerous
char[] temp = new char[15];
for (int i = 0; i < temp.length; i++)
temp[i] = raf.readChar();
Where does the 15 come from?
Try and break it down with just one detail and bulid up from there. You should find the error. I would personally read until you find a particular separator.

Categories