How to write a LinkedList to a .txt file - java

Super simple program. Loop asking for student data (name, address, gpa) which is stored in a linked list. Output the data to a regular text file that can be opened in notepad.
I'm so close, but cannot figure out how to get my data written into the txt file. To start, here's my classes:
public class Student {
private String name;
private String address;
private double gpa;
public Student(String name, String address, double gpa) {
this.name = name;
this.address = address;
this.gpa = gpa;
}
public String getName() {
return this.name;
}
public String getAddress() {
return this.address;
}
public double getGpa() {
return this.gpa;
}
public String toString() {
return this.name + ", " + this.address + ", " + this.gpa;
}
public class WriteFile {
private String path;
private boolean append_to_file = false;
public WriteFile(String file_path) {
path = file_path;
}
public WriteFile(String file_path, boolean append_value) {
path = file_path;
append_to_file = append_value;
}
public void writeToFile(String textLine)throws IOException {
FileWriter write = new FileWriter(path, append_to_file);
PrintWriter print_line = new PrintWriter(write);
print_line.printf("%s" + "%n", textLine);
print_line.close();
}
}
public class ReadFile {
private String path;
public ReadFile(String file_path) {
path = file_path;
}
public String[] OpenFile() throws IOException {
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
int numberOfLines = 3;
String[] textData = new String[numberOfLines];
int i;
for (i=0; i < numberOfLines; i++) {
textData[i] = textReader.readLine();
}
textReader.close();
return textData;
}
int readLines() throws IOException {
FileReader file_to_read = new FileReader(path);
BufferedReader bf = new BufferedReader(file_to_read);
String aLine;
int numberOfLines = 0;
while ((aLine = bf.readLine()) != null) {
numberOfLines++;
}
bf.close();
return numberOfLines;
}
}
In main I can get it to write the "Text to be written to file" into my .txt file, but I still can't figure out how to write studentData into that file.
public class Main {
public static void main(String[] args) throws IOException {
LinkedList < Student > studentData = new LinkedList < > ();
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter(System.lineSeparator());
while (true) {
System.out.println("Student name: ");
String name = scanner.next();
if (name.isEmpty()) {
break;
}
System.out.println("Student address: ");
String address = scanner.next();
System.out.println("Student GPA: ");
double gpa = scanner.nextDouble();
studentData.add(new Student(name, address, gpa));
}
studentData.sort(Comparator.comparing(Student::getName));
for (Student info: studentData) {
System.out.println(info.getName() + "," + info.getAddress() + "," + info.getGpa());
}
String file_name = "C:\\Users\\hidden\\OneDrive - hidden\\Desktop\\Portfolio_Project.txt";
try {
ReadFile file = new ReadFile(file_name);
String[] aryLines = file.OpenFile();
int i;
for (i = 0; i < aryLines.length; i++) {
System.out.println(aryLines[1]);
}
} catch (IOException e) {
System.out.println("Error. Please try again.");
}
// Write to a file
WriteFile data = new WriteFile(file_name);
data.writeToFile("Text to be written to file");
System.out.println("Text File Written To Portfolio_Project.txt on Desktop");
}
}

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

Get data from file - Buffered Reader

I would just have the id, the content and the hashtag and time of every tweet in a text file, and I dont know how to store infomration in lists of tweet,
I created a tweet class as follows:
public class Tweet {
private String type;
private String origin;
private String tweetText;
private String url;
private String tweetID;
private String tweetDate;
private int retCount;
private String favourit;
private String mEntities;
private String hashtags;
public Tweet(String tweetID,String origin) {
this.tweetID = tweetID;
this.origin = origin;
}
public Tweet(String type, String origin, String tweetText, String url, String tweetID, String tweetDate, int retCount, String favourit, String mEntities, String hashtags) {
this.type = type;
this.origin = origin;
this.tweetText = tweetText;
this.url = url;
this.tweetID = tweetID;
this.tweetDate = tweetDate;
this.retCount = retCount;
this.favourit = favourit;
this.mEntities = mEntities;
this.hashtags = hashtags;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getOrigin() {
return origin;
}
public void setOrigin(String origin) {
this.origin = origin;
}
public String getTweetText() {
return tweetText;
}
public void setTweetText(String tweetText) {
this.tweetText = tweetText;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getTweetID() {
return tweetID;
}
public void setTweetID(String tweetID) {
this.tweetID = tweetID;
}
public String getTweetDate() {
return tweetDate;
}
public void setTweetDate(String tweetDate) {
this.tweetDate = tweetDate;
}
public int getRetCount() {
return retCount;
}
public void setRetCount(int retCount) {
this.retCount = retCount;
}
public String getFavourit() {
return favourit;
}
public void setFavourit(String favourit) {
this.favourit = favourit;
}
public String getmEntities() {
return mEntities;
}
public void setmEntities(String mEntities) {
this.mEntities = mEntities;
}
public String getHashtags() {
return hashtags;
}
public void setHashtags(String hashtags) {
this.hashtags = hashtags;
}
and my data file has the following format:
***
***
Type:status
Origin: Here's link to listen live to our discussion of #debtceiling #politics :
Text: Here's link to listen live to our discussion of :
URL:
ID: 96944336150867968
Time: Fri Jul 29 09:05:05 CDT 2011
RetCount: 0
Favorite: false
MentionedEntities:
Hashtags: debtceiling politics
***
***
Type:status
Origin: Now we're talking #debtceiling w/ Dick Polman #NewsWorksWHYY #PhillyInquirer & Bill Galston #BrookingsInst #NoLabelsOrg
Text: Now we're talking w/ Dick Polman & Bill Galston
URL:
ID: 96943803600089088
Time: Fri Jul 29 09:02:58 CDT 2011
RetCount: 1
Favorite: false
MentionedEntities: 136337303 151106990 14495726 15161791
Hashtags: debtceiling
***
***
I want to read this file and stock information into lists, i begin with this code, but i dont know how to solve that
public static List<String> readTweets(File file) throws IOException {
List<String> tweets = new ArrayList<String>();
//logger.info("Read tweets from {}", file.getAbsolutePath());
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
String[] fields;
while ((line = reader.readLine()) != null) {
fields = line.split(",");
if (fields.length > 1)
tweets.add(fields[1]);
}
return tweets;
}
By the looks of the code you are experimenting with, this is what I would do:
public static List<String> readTweets(File file) throws IOException {
List<String> tweets = new ArrayList<String>();
List<String> lines = Files.readAllLines(file.toPath());
for(int i = 0; i < lines.length(); i++){
String line = lines.get(i);
String[] part = line.split(",");
if(part.length < 1) tweets.add(part[i]);
}
}
But, if I wrote an application that was purely for printing the contents of tweets into the console, here's how I'd do it:
TweetReader.java
package Testers;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
public class TweetReader {
public static List<Tweet> readTweets(File file) throws IOException {
boolean processEnd = false;
String type = "";
String origin = "";
String tweetText = "";
String url = "";
String tweetID = "";
String tweetDate = "";
int retCount = 0;
String favourite = "";
String mEntities = "";
String hashTags = "";
List<Tweet> tweets = new ArrayList<Tweet>();
List<String> lines = Files.readAllLines(file.toPath());
for(int i = 0; i < lines.size(); i++){
String line = lines.get(i);
line = line.trim();
if(line.equals("***")){
if(processEnd){
Tweet tweet = new Tweet(type, origin, tweetText, url, tweetID, tweetDate, retCount, favourite, mEntities, hashTags);
tweets.add(tweet);
processEnd = false;
}else processEnd = true;
}else{
if(line.contains(":")){
String header = line.substring(0, line.indexOf(":"));
//System.out.println(header); //You can uncomment this for troubleshooting
if(header.equals("Type")) type = line.substring(line.length() > 5 ? 5 : line.length());
else if(header.equals("Origin")) origin = line.substring(line.length() > 8 ? 8 : line.length());
else if(header.equals("Text")) tweetText = line.substring(line.length() > 6 ? 6 : line.length());
else if(header.equals("URL")) url = line.substring(line.length() > 5 ? 5 : line.length());
else if(header.equals("ID")) tweetID = line.substring(line.length() > 4 ? 4 : line.length());
else if(header.equals("Time")) tweetDate = line.substring(line.length() > 6 ? 6 : line.length());
else if(header.equals("RetCount")) retCount = Integer.parseInt(line.substring(line.length() > 10 ? 10 : line.length()));
else if(header.equals("Favorite")) favourite = line.substring(line.length() > 11 ? 11 : line.length());
else if(header.equals("MentionedEntities")) mEntities = line.substring(line.length() > 19 ? 19 : line.length());
else if(header.equals("Hashtags")) hashTags = line.substring(line.length() > 10 ? 10 : line.length());
else throw new IOException("Line cannot be identified as part of a tweet:" + line);
}else throw new IOException("Line cannot be processed:" + line);
}
}
return tweets;
}
public static void main(String[] args){
File log = new File("log.txt");
List<Tweet> tweets = new ArrayList<Tweet>();
try {
File f = new File(".").getAbsoluteFile();
File[] array = f.listFiles();
for(int i = 0; i < array.length; i++){
File tweet = array[i];
if(tweet.isFile() && !tweet.getName().contains("log.txt") && !tweet.getName().contains(".jar")){
log("Reading file: " + tweet.getAbsolutePath(), log);
List<Tweet> tweetlist = readTweets(tweet);
tweets.addAll(tweetlist);
}
}
System.out.println("Reading tweets now");
for(int i = 0; i < tweets.size(); i++){
Tweet t = tweets.get(i);
log("Type = " + t.getType(), log);
log("Origin = " + t.getOrigin(), log);
log("Text = " + t.getTweetText(), log);
log("URL = " + t.getURL(), log);
log("ID = " + t.getTweetID(), log);
log("Date = " + t.getTweetDate(), log);
log("Ret count = " + t.getRetCount(), log);
log("Favourite = " + t.getFavourite(), log);
log("Mentioned entities = " + t.getMentionedEntities(), log);
log("Hashtags = " + t.getHashtags(), log);
log("Tweet finished", log);
}
} catch (IOException e) {
log(e, log);
}
log("Finished reading tweets.", log);
}
private static void log(IOException e, File log) {
log(e.getMessage(), log);
StackTraceElement[] array = e.getStackTrace();
for(int i = 0; i < array.length; i++){
log(" " + array[i], log);
}
}
private static void log(String string, File log) {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(log, true));
writer.write(string);
writer.newLine();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Tweet.java
package Testers;
public class Tweet {
private String type;
private String origin;
private String tweetText;
private String url;
private String tweetID;
private String tweetDate;
private int retCount;
private String favourit;
private String mEntities;
private String hashtags;
public Tweet(String tweetID,String origin) {
this.tweetID = tweetID;
this.origin = origin;
}
public Tweet(String type, String origin, String tweetText, String url, String tweetID, String tweetDate, int retCount, String favourit, String mEntities, String hashtags) {
this.type = type;
this.origin = origin;
this.tweetText = tweetText;
this.url = url;
this.tweetID = tweetID;
this.tweetDate = tweetDate;
this.retCount = retCount;
this.favourit = favourit;
this.mEntities = mEntities;
this.hashtags = hashtags;
}
public String getType() {
return type;
}
public String getOrigin(){
return origin;
}
public String getTweetText(){
return tweetText;
}
public String getURL(){
return url;
}
public String getTweetID(){
return tweetID;
}
public String getTweetDate(){
return tweetDate;
}
public int getRetCount(){
return retCount;
}
public String getFavourite(){
return favourit;
}
public String getMentionedEntities(){
return mEntities;
}
public String getHashtags(){
return hashtags;
}
}
//global attribute
List<Tweet> tweetList = new ArrayList<>();
String line = "";
String[] fields;
while (line != null) {
line = reader.readLine();
line = reader.readLine();
//these two are for ***
for(int i = 0;i<10;i++){
line = reader.readLine();
tweets.add(line);
// these are for the other data
}
Tweet tweet = createTweetFromList(tweets);
tweetList.add(tweet);
}

Reading textfile with multiple elements into arraylist (set and get)

I am trying to read from a text file of the type (Artist, Title, Genre, Recordcompany, Release year, Number of songs, Playtime):
The Beatles, Abbey Road, Rock, Apple Records, 1969, 17, 47.16
Sia, 1000 Forms of Fear, Pop, Intertia, 2014, 12, 48.41
Taylor Swift, Speak Now
I have created a CD class:
package q;
public class CD {
//
private String artist;
private String titel;
private String genre;
private String recordcompany;
private int year; //
private int songs; //
private double playtime; //
public CD() { //
}
public CD(String newArtist, String newTitel) {
artist = newArtist;
titel = newTitel;
}
public CD(String newArtist, String newTitel, String newGenre, String newRecordcompany, int newYear, int newSongs, double newPlaytime) {
artist = newArtist;
titel = newTitel;
genre = newGenre;
recordcompany = newRecordcompany;
year = newYear;
songs = newSongs;
playtime = newPlaytime;
}
public String getArtist() { //
return artist;
}
public String getTitel() {
return titel;
}
public String getGenre() {
return genre;
}
public String getRecordcompany() {
return recordcompany;
}
public int getYear() {
return year;
}
public int getsong() {
return songs;
}
public double getPlaytime() {
return playtime;
}
public void setArtist(String newArtist) { //
artist = newArtist;
}
public void setTitel(String newTitel) {
titel = newTitel;
}
public void setGenre(String newGenre) {
genre = newGenre;
}
public void setRecordcompany(String newRecordcompany) {
recordcompany = newRecordcompany;
}
public void setYear(int newYear) {
year = newYear;
}
public void setSongs(int newSongs) {
songs = newSongs;
}
public void setplaytime(double newPlaytime) {
playtime = newPlaytime;
}
#
Override public String toString() { //
return ("Artist " + artist + System.lineSeparator() + "Titel: " + titel + System.lineSeparator() + "Genre: " + genre + System.lineSeparator() + "Recordcompany: " + recordcompany + System.lineSeparator() + "Year: " + year + System.lineSeparator() + "Songs: " + songs + System.lineSeparator() + "Playtime: " + playtime + System.lineSeparator());
}
}
I am trying to read from the text file and then convert it into a arraylist. I know I have overcomplicated it by first conerting the text file to a string array and then converting it to an arraylist. I would like to use set and get methods when I create the array, if it is possible. I wonder if any of you have any tips for me for how I can make the code less complicated and include set and get methods if possible, thank you.
package q;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
public class Q {
public static void main(String[] args) throws FileNotFoundException {
String artist = "";
String titel = "";
String genre = "";
String recordcompany = "";
String year = "";
String songs = "";
String playtime = "";
try {
BufferedReader br = new BufferedReader(new FileReader("nej.txt"));
String line = null;
while ((line = br.readLine()) != null) {
String tmp[] = line.split(",");
artist = tmp[0];
titel = tmp[1];
if (tmp.length > 2) {
genre = tmp[2];
recordcompany = tmp[3];
year = (tmp[4]);
songs = (tmp[5]);
playtime = (tmp[6]);
} else {
genre = "";
recordcompany = "";
year = "";
songs = "";
playtime = "";
}
List < String > unsorted = Arrays.asList(tmp);
for (String e: unsorted) {
System.out.println(e);
}
}
br.close();
} catch (IOException e) {
System.out.println(e);
}
}
}
EDITED
package q;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Q {
public static void main(String[] args) throws FileNotFoundException {
String artist = "";
String titel = "";
String genre = "";
String recordcompany = "";
int year = 0;
int songs = 0;
double playtime = 0.0;
try {
BufferedReader br = new BufferedReader(new FileReader("nej.txt"));
String line = null;
List < CD > cdsList = new ArrayList < > ();
while ((line = br.readLine()) != null) {
CD cd = new CD();
String tmp[] = line.split(",");
cd.setArtist(tmp[0]);
cd.setTitel(tmp[1]);
if (tmp.length > 2) {
cd.setGenre(tmp[2]);
cd.setRecordcompany(tmp[3]);
cd.setYear(Integer.parseInt(tmp[4].trim()));
cd.setSongs(Integer.parseInt(tmp[5].trim()));
cd.setplaytime(Double.parseDouble(tmp[6].trim()));
}
System.out.println(cdsList);
}
br.close();
} catch (IOException e) {
System.out.println(e);
}
}
}
Something like below.
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader("nej.txt"));
String line = null;
List < CD > cdsList = new ArrayList < > ();
while ((line = br.readLine()) != null) {
CD cd = new CD();
String tmp[] = line.split(",");
cd.setArtist(tmp[0]);
cd.setTitel(tmp[1]);
if (tmp.length > 2) {
cd.setGenre(tmp[2]);
cd.setRecordcompany(tmp[3]);
cd.setYear(Integer.parseInt(tmp[4].trim()));
cd.setSongs(Integer.parseInt(tmp[5].trim()));
cd.setplaytime(Double.parseDouble(tmp[6].trim()));
}
cdsList.add(cd);
}
System.out.println(cdsList);
br.close();
} catch (IOException e) {
System.out.println(e);
}
}

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.

Using Bubble sort to sort file by surname?

In this program iam able to read a file into an array and split the array. Then i have got an array method to sort the file by surname using bubble sort. However, i get an error. Can someone assist me please.
Error:
error: method BubbleCountry in class StudentSort cannot be applied to given types;
StudentSort.txt
Bren Ramal
Casi Ron
Alba Jordi
SortData file
import java.io.*;
import java.util.*;
class ShowSort implements Comparable {
private String name;
private String surname;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getSurname() {
return surname;
}
public int compareTo(Object Student) throws ClassCastException {
if (!(Student instanceof ShowSort))
throw new ClassCastException("Error");
String surn = ((ShowSort) Student).getSurname();
return this.surname.compareTo(surn);
}
}
StudentSort file
import java.io.*;
import java.util.*;
public class StudentSort {
StudentSort() {
int j = 0;
ShowSort data[] = new ShowSort[3];
try {
FileInputStream fstream = new FileInputStream("StudentSort.txt");
// Use DataInputStream to read binary NOT text.
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String line;
ArrayList list = new ArrayList();
while ((line = br.readLine()) != null) {
list.add(line);
}
Iterator itr;
for (itr = list.iterator(); itr.hasNext();) {
String str = itr.next().toString();
String[] splitSt = str.split("\t");
String name = "", surname = "";
for (int i = 0; i < splitSt.length; i++) {
name = splitSt[0];
surname = splitSt[1];
}
BubbleCountry(surname);//This is the issue.
data[j] = new ShowSort();
data[j].setName(name);
data[j].setSurname(surname);
j++;
}
for (int i = 0; i < 3; i++) {
ShowSort show = data[i];
String name = show.getName();
String surname = show.getSurname();
System.out.println(name + "\t" + surname);
}
} catch (Exception e) {
}
}
private static void BubbleCountry(String[] myarray) {
String ctry;
for(int i=0; i<myarray.length; i++) {
for(int j=0; j<myarray.length-1-i; j++) {
if(myarray[j].compareTo(myarray[j+1])>0) {
ctry= myarray[j];
myarray[j] = myarray[j+1];
myarray[j+1] = ctry;
}
}
}
}
public static void main(String[] args) {
StudentSort data = new StudentSort();
}
}
You are calling BubbleCountry(surname); but its prototype shows
private static void BubbleCountry(String[] myarray)
So the difference is here. The function requires an array of string as argument but while calling you are passing a string rather than string array.
import java.io.*;
import java.util.*;
public class StudentSort
{
StudentSort()
{
int j = 0;
ShowSort data[] = new ShowSort[3];
try
{
FileInputStream fstream = new FileInputStream("StudentSort.txt");
// Use DataInputStream to read binary NOT text.
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String line;
ArrayList<String> list = new ArrayList<String>();
while ((line = br.readLine()) != null)
{
list.add(line);
}
Iterator<String> itr = list.iterator();
int k = 0;
for (itr = list.iterator(); itr.hasNext();itr.next())
{
String str = itr.toString();
String[] splitSt = str.split("\t");
data[k].setName(splitSt[0]);
data[k].setName(splitSt[1]);
k++;
}
BubbleCountry(data);//This is the issue.
for (int i = 0; i < 3; i++)
{
ShowSort show = data[i];
String name1 = show.getName();
String surname1 = show.getSurname();
System.out.println(name1 + "\t" + surname1);
}
}
catch (Exception e)
{
}
}
private static void BubbleCountry(ShowSort[] myarray)
{
ShowSort ctry;
for(int i=0; i<myarray.length; i++)
{
for(int j=0; j<myarray.length-1-i; j++)
{
if(myarray[j].compareTo(myarray[j+1])>0)
{
ctry= myarray[j];
myarray[j] = myarray[j+1];
myarray[j+1] = ctry;
}
}
}
}
public static void main(String[] args)
{
StudentSort data = new StudentSort();
}
}

Categories

Resources