Specifically writing from an array of courses to a csv file - java

I'm having trouble using a method from a class that I have written. The following method was added to a class I created named Course. The goal is to write all of the properties of the object on one line as a String.
// method to return properties as a CSV string on one line
public String toCSVString(Course c) {
String record = c.campus + ","
+ c.course + ","
+ c.section + ","
+ c.crn + ","
+ c.credits + ","
+ c.time + ","
+ c.days + "\n";
return record;
} //end toCSVString()
OK, so after adding that method to the Class. I then began to create a method (which is called from the main method) needed to write from a Course array to a CSV File which calls the above method. This is the method I wrote.
// add a method here to write from an array of courses to a CSV file
public static void writeCSV(Course[] courseArray, int count) throws Exception {
//create a File class object and give the file the name employees.csv
java.io.File courseCSV = new java.io.File("courses.csv");
//Create a Printwriter text output stream and link it to the CSV File
java.io.PrintWriter outfile = new java.io.PrintWriter(courseCSV);
//Iterate the elements actually being used
for (int i=0; i < count ; i++) {
outfile.write(courseArray.toCSVString(courseArray[i]));
}//end for
outfile.close();
} //end writeCSV()
I'm having trouble with the line that starts with "outfile.write"
In my code, I am having trouble getting Netbeans to locate the toCSVString method which is defined after the toString method in the Course class. Originally that line in the code looked like this:
outfile.write(toCSVString(courseArray[i]));
But my IDE could not find it so I added the instance of the course object in front of it. However, I am still having trouble.
Does anybody see what I am doing wrong?
EDIT #1
Here is the Course class in my program. I am having issues with the toCSVString method.
class Course implements Serializable {
private String campus; // the campus on which the course is offered
private String course; // the course number, such as CSCI 111
private String section; // the section number
private String crn; // the CRN for this section
private int credits; // the number od credits for the course
private String time; // the time the course is offered, such as 8:00 to 10:00 A.M.
private String days; // the Days the course is offered, suhc as MW
// constructors
Course() {
}
Course(String course, String section, String crn, int credits) {
this.course = course;
this.section = section;
this.crn = crn;
this.credits = credits;
} // end Course() initalizing
// muatator methods
public void setCampus(String cmp) {
this.campus = cmp;
}// end setCampus()
public void setCourse(String crse) {
this.course = crse;
}// end setCourse()
public void setSection(String sect) {
this.section = sect;
} // end setSection()
public void setCRN(String crn) {
this.crn = crn;
} // end setCRN()
public void setCredits(int cr) {
this.credits = cr;
} // end setCredits()
public void setTime(String tm) {
this.time = tm;
}// end setTime()
public void setDays(String days) {
this.days = days;
}// end setDays()
// accessor methods
public String getCampus() {
return campus;
} // end getCampus()
public String getCourse() {
return course;
} // end Course()
public String getSection() {
return section;
} // end getSection()
public String getCRN() {
return crn;
} // end getCRN()
public int getCredits() {
return credits;
} // end getCredits()
public String getTime() {
return time;
} // end getTime()
public String getDays() {
return days;
} // end getDays()
// method to compare by CRN using the String class compareTo()
public int compareTo(Course other) {
return this.crn.compareTo(other.getCRN());
} // end compareTO()
// method to return properties as a string
public String toString() {
return campus + " "
+ course + " "
+ section + " "
+ crn + " "
+ credits + " "
+ time + " "
+ days;
} // end toString()
// method to return properties as a CSV string on one line
//public String toCSVString(Course c){
public String toCSVString (Course c){
String record = campus + ","
+ course + ","
+ section + ","
+ crn + ","
+ credits + ","
+ time + ","
+ days + "\n";
return record;
} //end toCSVString()
}// end class Course

You have:
outfile.write(courseArray.toCSVString(courseArray[i]));
You mean:
outfile.write(courseArray[i].toCSVString(courseArray[i]));
As toCSVString is a member of Course, not of Course[] (courseArray is a Course[] and you are attempting to call .toCSVString() on the array itself, which is not valid).
Also note that in this form, it is redundant to pass the Course as a parameter, as you are not using it and you also would want this instead of some other Course anyways. I recommend either ditching that parameter entirely (since it is unused):
public String toCSVString () { // <- c wasn't actually used
String record = campus + "," // <- and this. is implied here
+ course + ","
+ section + ","
+ crn + ","
+ credits + ","
+ time + ","
+ days + "\n";
return record;
}
And you simply call it as:
outfile.write(courseArray[i].toCSVString());
Or, if you prefer you can make the method static and use the parameter (although that does not get you any particular benefit in this situation):
public static String toCSVString (Course c) {
String record = c.campus + ","
+ c.course + ","
+ c.section + ","
+ c.crn + ","
+ c.credits + ","
+ c.time + ","
+ c.days + "\n";
return record;
}
If you choose the static approach then you call it as:
outfile.write(Course.toCSVString(courseArray[i]));

Related

Finding diff between two lists and adding plus and minus a more efficient way

I have two lists with with the same data except the first list might have slightly different wording.
I am making sure the fields dont match. If they dont, then i add a plus to the first word in the array and a minus to the second word in the second array.
I am just iterating over the list and i have a ton of ifs. There are other data points i will need to do also and the ifs can get very long. Is there a more efficient way of doing this?
I am not good with java 8+ and streams. Would it be better to do it with streams and if so how would i do this? Could you please do an example?
Thank you in advance!!! I really need help but i am expecting to get my heart broken!
List<ExteriorColor> f1 = vinResponseOne.getResult().getExteriorColors();
List<ExteriorColor> f2 = vinResponseTwo.getResult().getExteriorColors();
first = vinResponseOne.getResult().getExteriorColors();
second = vinResponseTwo.getResult().getExteriorColors();
private void compareExteriorColors(List<ExteriorColor> f1, List<ExteriorColor> f2){
for(int i =0; i< f1.size(); i++) {
if (!f1.get(i).getDescription().equals(f2.get(i).getDescription())) {
final String added = "+ " + f1.get(i).getDescription();
final String original = "- " + f2.get(i).getDescription();
first.get(i).setDescription(added);
second.get(i).setDescription(original);
}
if (!f1.get(i).getGenericDesc().equals(f2.get(i).getGenericDesc())) {
final String added = "+ " + f1.get(i).getGenericDesc();
final String original = "- " + f2.get(i).getGenericDesc();
first.get(i).setGenericDesc(added);
second.get(i).setGenericDesc(original);
}
if (!f1.get(i).getColorCode().equals(f2.get(i).getColorCode())) {
final String added = "+ " + f1.get(i).getColorCode();
final String original = "- " + f2.get(i).getColorCode();
f1.get(i).setColorCode(added);
f2.get(i).setColorCode(original);
}
if (f1.get(i).getInstallCause() != null) {
if (!f1.get(i).getInstallCause().equals(f2.get(i).getInstallCause())) {
final String added = "+ " + f1.get(i).getInstallCause();
final String original = "- " + f2.get(i).getInstallCause();
first.get(i).setInstallCause(added);
second.get(i).setInstallCause(original);
}
}
if (!f1.get(i).getPrimary().equals(f2.get(i).getPrimary())) {
final String added = "+ " + f1.get(i).getPrimary();
final String original = "- " + f2.get(i).getPrimary();
first.get(i).setPrimary(added);
second.get(i).setPrimary(original);
}
if (!f1.get(i).getRgbValue().equals(f2.get(i).getRgbValue())) {
final String added = "+ " + f1.get(i).getRgbValue();
final String original = "- " + f2.get(i).getRgbValue();
first.get(i).setRgbValue(added);
second.get(i).setRgbValue(original);
}
if (!f1.get(i).getStyles().equals(f2.get(i).getStyles())) {
List<String> styleFirst = new ArrayList<>();
List<String> styleSecond = new ArrayList<>();
final String added = "+ " + f1.get(i).getStyles();
final String original = "- " + f2.get(i).getStyles();
styleFirst.add(added);
styleSecond.add(original);
first.get(i).setStyles(styleFirst);
second.get(i).setStyles(styleSecond);
}
if (!f1.get(i).getType().equals(f2.get(i).getType())) {
String added = "+ " + f1.get(i).getType();
String original = "- " + f2.get(i).getType();
first.get(i).setType(added);
second.get(i).setType(original);
}
}
}
What it ends up looking like.
I will later convert to json.
class User { //Considering a simple class with only 2 fields for brevity
private String userName;
private String password;
User(String userName, String password) {
this.userName = userName;
this.password = password;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public String toString() {
return "User{" + "userName='" + userName + '\'' + ", password='" + password + '\'' + '}';
}
}
public class S14 {
public static void main(String[] args) {
User user1 = new User("Anees", "pwd");
User user2 = new User("Anees1", "pwd");
List<User> userList1 = new ArrayList<>(Arrays.asList(user1, user2));
User user3 = new User("Anees2", "pwd");
User user4 = new User("Anees3", "pwd");
List<User> userList2 = new ArrayList<>(Arrays.asList(user3, user4));
// Assuming both Lists are of same size
IntStream.range(0, userList1.size())
.forEach(
i -> {
User firstListUser = userList1.get(i);
User secondListUser = userList2.get(i);
//HERE GOES THE MAIN PART
compareStringsAndProcessElement(
firstListUser::getUserName,
secondListUser::getUserName,
(s, s2) -> !s.equals(s2),
firstListUser::setUserName,
secondListUser::setUserName);
compareStringsAndProcessElement(
firstListUser::getPassword,
secondListUser::getPassword,
(s, s2) -> !s.equals(s2),
firstListUser::setPassword,
secondListUser::setPassword);
//AND SO ON!
});
System.out.println(userList1);
System.out.println(userList2);
}
private static void compareStringsAndProcessElement(
Supplier<String> element1,
Supplier<String> element2,
BiPredicate<String, String> stringStringBiPredicate,
Consumer<String> u1,
Consumer<String> u2) {
String e1 = element1.get();
String e2 = element2.get();
if (stringStringBiPredicate.test(e1, e2)) {
e1 = "+" + e1;
e2 = "-" + e2;
u1.accept(e1);
u2.accept(e2);
}
}
}
Hope this helps! This has nothing fancy with Streams, but uses Functional approach for a problem instead of your declarative one. This could be written with Normal loops too instead of IntStream.
PS: As far as performance goes, this might be even slower than declarative implementation since it involves multiple method calls. But, saving off some nanoseconds is not a good trade-off than code maintainability.

Java: Why does my toString method print wrong information?

I have an abstract superclass that has two attributes: int and string. I have overridden the toString method in it as well as in its subclass that has one extra attribute (LocalDate). However, for some reason that I don't understand, when I print the subclass toSring info, the int value changes.
This is what I have in the superclass:
public abstract class File {
private int id;
private String text;
public File(int newId, String newText) throws IllegalArgumentException {
id(newId);
text(newText);
}
public int id() {
return id;
}
public void id(int e) throws IllegalArgumentException {
if (e <= 0) {
throw new IllegalArgumentException();
}
else {
id = e;
}
}
public String text() {
return text;
}
public void text(String aText) throws IllegalArgumentException {
if (aText == null || aText.length() == 0) {
throw new IllegalArgumentException();
}
else {
text = aText;
}
}
#Override
public String toString() {
return '"' + id() + " - " + text() + '"';
}
Then in the subclass I have this:
public class DatedFile extends File {
private LocalDate date;
public DatedFile (int newId, LocalDate newDate, String newText) throws IllegalArgumentException {
super(newId, newText);
date(newDate);
}
public LocalDate date() {
return date;
}
public void date(LocalDate aDate) throws IllegalArgumentException {
if (aDate == null) {
throw new IllegalArgumentException();
}
else {
date = aDate;
}
}
#Override
public String toString() {
return '"' + id() + " - " + date + " - " + text() + '"';
}
I tested it like this:
public static void main(String[] args) {
LocalDate when = LocalDate.of(2020, 1, 1);
DatedFile datedFile1 = new DatedFile(999, when, "Insert text here");
System.out.println(datedFile1);
It printed: "1033 - 2020-01-01 - Insert text here"
However, if i use the following code
System.out.println(datedFile1.id());
it prints the correct id (999). So I assume that something with the toString messes it up, but I have no idea where the problem is.
PS. I'm a beginner and I'm sorry if I included too much code but as I don't know what is the problem, I really don't know what is relevant and what isn't.
Your problem is here:
return '"' + id() + " - " + date + " - " + text() + '"';
id() returns an int, and '"' is a char, which is a numeric type. So '"' + 999 is 1033, not "999.
To fix the problem, use a String instead of a character:
return "\"" + id() + " - " + date + " - " + text() + "\"";
Change your toString() method from '"' to " \"".
'"' is a character (which is stored internally as an Integer), so adding it with id() produces the result you're seeing.
or using string interpolation:
return '\" ${id()} - ${date} - ${text()} \"';

java string toString with condition

I have to write a PhonePlan object that will represent the type of plan that a customer has for his/her phone. So the object must keep track of the minutesAllowed (int), minutes used (int), dataAllowed (int), data used (int) and planType (boolean):
public class PhonePlan {
int minutesAllowed;
int minutesUsed;
int dataAllowed;
int dataUsed;
boolean planType;
}
I needed to write a constructor which has minutesAllowed, dataAllowed, and the planType as arguments which I did:
public PhonePlan (int ma, int da, boolean pt){
this.minutesAllowed = ma;
this.planType = pt;
this.dataAllowed = da;
}
And finally I have to write a string method that displays the plan depending on the type of plan.
I also have to test my code with the following test program;
public class PlanTestProgram {
public static void main(String args[]) {
System.out.println(new PhonePlan(200, 2500000, false));
System.out.println(new PhonePlan(250, 500000, true));
System.out.println(new PhonePlan(300, 5000000, false));
System.out.println(new PhonePlan(60, 1000000, false));
System.out.println(new PhonePlan(30, 0, true));
}
The first element being the minutesAllowed, the second one being the amount of dataAllowed and the third one is stating if planType is true of false.
I tried many different things but I am not able to construct a toString() method that take into account if my planType is either true or false...
My Attempt:
public String toString(){
return ( "Regular(" + minutesAllowed + " minute," + dataAllowed
+ "GB data) Monthly Plan with "
+ getMinutesRemaining() + " minutes remaining and "
+ getDataRemaining() + "KB remaining");
}
You can easily update return in your suggested (attempt) toString method, by using the shorthand if/else, into the following:
return ("Regular(" + minutesAllowed + " minute," + dataAllowed
+ "GB data) " + ((PlanType)? "Monthly": "Annual") + " Plan with "
+ getMinutesRemaining() + " minutes remaining and "
+ getDataRemaining() + "KB remaining");
Metod toString() should never be used to showcase the value of the object properties. For the overrides you can use commons library
public String toString() {
return new ToStringBuilder(this).
append("minutesAllowed", minutesAllowed).
append("minutesUsed", minutesUsed).
append("dataAllowed", dataAllowed).
append("dataUsed", dataUsed).
append("planType", planType).
toString();
}
you could implement the toString method as described in the following code
public class PhonePlan {
int minutesAllowed;
int minutesUsed;
int dataAllowed;
int dataUsed;
boolean planType;
public PhonePlan (int ma, int da, boolean pt){
this.minutesAllowed = ma;
this.planType = pt;
this.dataAllowed = da;
}
#Override
public String toString() {
return planType ? getPlanTypeBasedString("Weekly Plan") : getPlanTypeBasedString("Monthly Plan");
}
public String getPlanTypeBasedString(String planType){
return ( "Regular(" + minutesAllowed + " minute," + dataAllowed
+ "GB data) "+planType+" with "
+ getMinutesRemaining() + " minutes remaining and "
+ getDataRemaining() + "KB remaining");
}

How do I change a Variable, in a Java Class

I have to be able to convert some variables in my class. I have a boolean variable, WaGa (Stands for Workstation/Gaming computer), and if it's true, I want to convert String WorGam
I have to do this through service and support methods, and I keep trying, but I constenly fail. It just prints out what's in the driver. HELP.
public class Graphics
//instance data
{
private int Ram;
private String Brand;
private int Res;
private int BiWi;
private int BaCl;
private boolean K4;
private boolean WaGa;
private String WorGam;
//boolean WaGa, boolean K4, int BaCl, int BiWi, int Res, String Brand, int Ram
public Graphics (int R, String B, int Re, int Bi, int Ba, boolean K4, boolean Wa, String Wor ) // constructor
{
Ram = R;
Brand = B;
Res = Re;
BiWi = Bi;
BaCl = Ba;
K4 = K4;
WaGa = Wa;
Wor = WorGam;
}
public int get_Ram() //Accessor Method - there are 3 of them
{
return Ram;
}
public String get_Brand() //Accessor Method - there are 3 of them
{
return Brand;
}
public int get_Res() //Accessor Method - there are 3 of them
{
return Res;
}
public int get_BiWi() //Accessor Method - there are 3 of them
{
return BiWi;
}
public int get_BaCl()
{
return BaCl;
}
public boolean get_K4()
{
return K4;
}
public String WorGam(boolean WaGa)
{
String WorGam;
if ( WaGa == true) {
return WorGam = "Workstation";
} else {
return WorGam = "True";
}
}
public String toString()
{
return ("Ram" + " " + Ram + ". " + "Brand:" + " " + Brand + ". " + "Resolution" + " " + Res + ". " + "Processer" + " " + BiWi + "." + " " + "Base Clock" + " " + BaCl+ " " + "K4?" + " " + K4+ " " +WorGam);
}
}
public class Graphicse_Driver
{
public static void main(String [] args)
{
Graphics unique=new Graphics(4, "Nvinda", 6, 7, 9, false, false, "sdf" );
System.out.println(unique);
You may need to reread you code to make sure there aren't any other mistakes in your code, but this is the root of your problem.
In order to access the WarGam getter, you need to call:
System.out.println(unique.WarGam());
When you do System.out.println(unique), you are trying to print out the entire Graphics object instead of just the WarGam string.
You then should change your WarGam() method to look like the following:
public String WorGam()
{
if (WaGa) {
return "Workstation";
}
return "Gaming";
}
Here is a more in depth explanation of the changes:
WaGa is a private variable of your Graphics class. Since the WarGam() method is in the same Graphics class, it already had access to the WaGa variable, so you do not need to pass it in.
if(WaGa == true) is just a wordier way of writing if(WaGa).
Instead of creating a String WorGam variable, you can just return the string you want directly.
The else surrounding the second return is unnessary since that code will only be hit if the first return is skipped.
After these changes, the private String WarGam variable is really not necessary either.
public String worGam(boolean waGa) {
if (waGa)
return "Workstation";
else
return "Gaming";
}
You need to correct your worGam() function:
public String worGam(boolean waGa) {
if (waGa == true)
return "Workstation";
else
return "True";
}
And the main() function:
public static void main(String [] args) {
Graphics unique = new Graphics(4, "Nnn", 6, 7, 9, false, false, "xxx");
System.out.println(unique.WorGam(false));
}

How to compare parameter values of two objects in Java?

Right now I'm working on a method for comparing the scores of athletes in the olympics. So far I've had little trouble, however now I've reached a point where i need to compare two objects (athletes) scores and I'm not sure how to do it. This is my code for the Olympic class:
// A program using the Athlete class
public class Olympics {
public static void main(String args[]) {
System.out.println("The leader is " + Athlete.leader() +
", with a score of " + Athlete.leadingScore());
Athlete meryl = new Athlete("Meryl Davis", "U.S.");
meryl.addScore(75);
System.out.println(meryl);
Athlete tessa = new Athlete("Tessa Virtue", "Canada");
System.out.println(tessa);
System.out.println(); // blank line
tessa.addScore(50);
System.out.println(tessa);
System.out.println(meryl);
System.out.println("The leader is " + Athlete.leader() +
", with a score of " + Athlete.leadingScore());
System.out.println(); // blank line
tessa.addScore(100);
meryl.addScore(65);
System.out.println(tessa);
System.out.println(meryl);
System.out.println("The leader is " + Athlete.leader() +
", with a score of " + Athlete.leadingScore());
System.out.println(); // blank line
tessa.addScore(20);
System.out.println("Tessa's final score is " + tessa.getScore());
meryl.move("France");
System.out.println(meryl);
} // end main
} // end class Olympics
And this is the constructor class "Athlete":
public class Athlete {
private String name;
private String country;
protected int score;
public static int leadScore;
public Athlete(String athName, String athCountry) {
this.name = athName;
this.country = athCountry;
score = 0;
if (score < 1) {
System.out.println("Score cannot be lower than 1");
}
}
public int addScore(int athScore) {
score += athScore;
return score;
}
public static String leader(){
//TODO
}
public static int leadingScore() {
//MUST COMPARE BOTH ATHLETES
}
public int getScore(){
return score;
}
public void move(String newCountry) {
country = newCountry;
}
public String toString() {
return name + ": " + "from " + country + ", current score " + score;
}
}
So what I'm trying to do is have the program check Meryl's score compared to Tessa's and return that Athlete's score in leadingScore() and, using that athlete, return a leader(). Any help is appreciated! Thanks.
The function must take the two Athletes you're comparing as the parameters for this to work
public static int leadingScore(Athlete a1, Athlete a2) {
if (a1.getScore() < a2.getScore()) {
// do stuff
}
}
The lead score should not be in the athlete class, but rather in main () because one instance of an Athlete class would not know of other instances unless you put a self-referential list inside the class. Similarly, leadingScore should be in main ().
It or main can call each athlete and compare:
int merylScore = meryl.getScore ();
int tessaScore = tessa.getScore ();
int leadingScore = 0;
String leaderName = "";
if (merylScore > tessaScore) {
leadingScore = merylScore;
leaderName = meryl.getName ();
} else if (tessaScore > merylScore) {
leadingScore = tessaScore;
leaderName = tessa.getName ();
} else {
leadingScore = merylScore;
leaderName = "a tie between Meryl and Tessa";
}
System.out.println ("The leader is " + leaderName + ", with a score of " + leadingScore);
You should consider using a "collection". Use an array, a list ... or even a sorted list.
Stored your individual objects in the collection, then traverse the collection to find the highest score.
For example:
// Create athlete objects; add each to list
ArrayList<Athlete> athletes = new ArrayList<Athlete>();
Athlete meryl = new Athlete("Meryl Davis", "U.S.");
meryl.addScore(75);
...
athletes.add(meryl);
Athlete tessa = new Athlete("Tessa Virtue", "Canada");
...
athletes.add(tessa );
// Go through the list and find the high scorer
Athlete highScorer = ...;
for (Athlete a : athletes) {
if (highScorer.getScore() < a.getScore())
highScorer = a;
...
}
System.out.println("High score=" + highScorer.getScore());
Here's a good tutorial:
http://www.vogella.com/tutorials/JavaCollections/article.html

Categories