Simple database on Java - java

I've got a task to make a simple database on a topic "basketball team" with functionality such as: deleting by ID, inserting new data, modification of information, printing all data from a file. All information should be written in a file.
I've already created createTeam() method that makes a kind of template of my default data that writes in a file.
Basically, after that, I've got trouble in deleteByID() method with deleting exact data that I need, so I'm asking you for a help
My code:
import java.io.*;
public class ChicagoBulls {
static class Player{
private int Id;
private int Age;
private String Name;
private String Surname;
private int Height;
private int Salary;
private String KPI;
private String Shoes;
private int Goals;
Player(int id, int age, String name, String surname, int height,
int salary, String kpi, String shoes, int goals) {
Goals = goals;
Id = id;
Age = age;
Name = name;
Surname = surname;
Height = height;
Salary = salary;
KPI = kpi;
Shoes = shoes;
}
public String getShoes() {
return Shoes;
}
public void setShoes(String shoes) {
Shoes = shoes;
}
public int getSalary() {
return Salary;
}
public void setSalary(int salary) {
Salary = salary;
}
public String getKPI() {
return KPI;
}
public void setKPI(String KPI) {
this.KPI = KPI;
}
public int getHeight() {
return Height;
}
public void setHeight(int height) {
Height = height;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getSurname() {
return Surname;
}
public void setSurname(String surname) {
Surname = surname;
}
public int getAge() {
return Age;
}
public void setAge(int age) {
Age = age;
}
public int getId() {
return Id;
}
public void setId(int id) {
Id = id;
}
public int getGoals() {
return Goals;
}
public void setGoals(int goals) {
Goals = goals;
}
}
public void createTeam(int quantity) throws Exception {
File newFile = new File("NewFile.txt");
FileWriter newFileReader = new FileWriter(newFile);
BufferedWriter bufferedWriter = new BufferedWriter(newFileReader);
bufferedWriter.write("|ID|\t"
+ "| AGE |\t"
+ "| NAME |\t"
+ "| SURNAME |\t"
+ "| HEIGHT |\t"
+ "| SALARY |\t"
+ "| KPI |\t"
+ "| SHOES |\t"
+ "| Goals |\t\n");
int counter = quantity;
for (int i = 0; i <= quantity; i++) {
Player defaultPlayer = new Player(i, 19, "DefName", "DefSurname", 180, 6000, "Good", "Nike", 0);
if (defaultPlayer.getId()<=9) {
bufferedWriter.write("|0" + defaultPlayer.getId() + "|\t");
bufferedWriter.write("|" + defaultPlayer.getAge() + " |\t");
bufferedWriter.write("|" + defaultPlayer.getName() + " |\t");
bufferedWriter.write("|" + defaultPlayer.getSurname() + " |\t");
bufferedWriter.write("|" + defaultPlayer.getHeight() + " |\t");
bufferedWriter.write("|" + defaultPlayer.getSalary() + " |\t");
bufferedWriter.write( "|" + defaultPlayer.getKPI() + " |\t");
bufferedWriter.write( "|" + defaultPlayer.getShoes() + " |\t");
bufferedWriter.write( "|" + defaultPlayer.getGoals() + " |\t");
}else{
bufferedWriter.write("|" + defaultPlayer.getId() + "|\t");
bufferedWriter.write("|" + defaultPlayer.getAge() + " |\t");
bufferedWriter.write("|" + defaultPlayer.getName() + " |\t");
bufferedWriter.write("|" + defaultPlayer.getSurname() + " |\t");
bufferedWriter.write("|" + defaultPlayer.getHeight() + " |\t");
bufferedWriter.write("|" + defaultPlayer.getSalary() + " |\t");
bufferedWriter.write( "|" + defaultPlayer.getKPI() + " |\t");
bufferedWriter.write( "|" + defaultPlayer.getShoes() + " |\t");
bufferedWriter.write( "|" + defaultPlayer.getGoals() + " |\t");
}
bufferedWriter.newLine();
}
bufferedWriter.close();
newFileReader.close();
}
public void deleteByID(int id) throws Exception {
FileReader file = new FileReader("NewFile.txt");
BufferedReader bufferedReader = new BufferedReader(file);
String idLine = bufferedReader.readLine();
int idIndex = idLine.indexOf(id);
int nextIdIndex = idLine.indexOf(id + 1);
}
}
Main
public class Main {
public static void main(String[] args) throws Exception {
ChicagoBulls team = new ChicagoBulls();
team.createTeam(30);
}
}
Thank you in advance.

I think the logic behind your execution is a bit too complicated to be understood without further explanations on your part. From what i gathered on your needs, i would suggest creating multiple constructors for the Player class - one requiring no input and returning a "Default" player with default characteristics, the other one with the ability to specify goals, shoes, etc.
After that, each of your teams can be represented as a Set<> of players. This would make iterating for each of the elements (players) easier, as well as provide a natural way of removing players from the team. You can read more about the implementation of this structure in the Java documentation here.

Related

Having trouble using the compareTo method

Hey all I've recently been trying to learn the compareTo method but this is extremely confusing.
The goal of this program was to hardcode information into a array of objects and sort it by the test score. The problem is compareTo method which I'm having trouble creating since the book I'm using doesn't go in to detail about this method. Here is the code so far.
public class janesj_Lab7 {
public static void main(String[] args) {
CS_UnderGradStudent no1 = new CS_UnderGradStudent(101,"Nancy","Brown","abc#kean.edu",70.0);
CS_UnderGradStudent no2 = new CS_UnderGradStudent(102,"John", "May","def#kean.edu",90);
CS_GradStudent no3 = new CS_GradStudent(103,"William","Smith","xyz#kean.edu",70,"Database");
Object[] arrays = new Object[3];
arrays[0] = no1;
arrays[1] = no2;
arrays[2] = no3;
int x = (int)Student.getGrade();
Arrays.sort(arrays,0,3);
for(int i = 0;i<arrays.length;i++) {
System.out.println(arrays[i].toString());
}
}
public static abstract class Student implements Comparable<Student>{
public static int studentId;
public static String firstName;
public static String lastName;
public static String email;
public static double testScore;
public static String STUDENT_TYPE;
public static double getGrade(){
return testScore;
}
public static String getStudent() {
return STUDENT_TYPE;
}
public Student(int id,String fname, String lname, String email, double testScore){
this.studentId = id;
this.firstName = fname;
this.lastName = lname;
this.email =email;
this.testScore = testScore;
}
#Override
public String toString() {
String x = Double.toString(testScore);
return "\tStudent ID: " + studentId + " name: "+ firstName + ","+ lastName + " Email: " + email + " testScore: " + x;
}
public abstract String computeGrade();
}
public static class CS_UnderGradStudent extends Student implements Comparable<Student>{
String STUDENT_TYPE ="CS_UnderGradStudent";
public CS_UnderGradStudent(int id,String fname, String lname, String email, double testScore) {
super(id,fname,lname,email,testScore);
}
public String computeGrade() {
if( testScore>=70) {
return "Pass";
}
else {
return "Fail";
}
}
public String toString(){
String x = Double.toString(testScore);
return"student type: " + STUDENT_TYPE + "\n" + super.toString() + "\n\t" + "Grade: " + computeGrade();
}
}
public static class CS_GradStudent extends Student implements Comparable<Student>{
String STUDENT_TYPE = "CS_GradStudent";
String researchTopic;
public CS_GradStudent(int id,String fname, String lname, String email, double testScore,String r) {
super(id,fname,lname,email,testScore);
researchTopic = r;
}
public String computeGrade() {
if(testScore>= 80) {
return "Pass";
}
else {
return "Fail";
}
}
public String toString() {
String x = Double.toString(testScore);
return"student type: " + STUDENT_TYPE + "\n" + super.toString() + "\n" + "Grade: " + computeGrade() + "\nResearch Topic: " + researchTopic;
}
}
}
```

overriding tostring() method and passing object reference without getting hash

I'm trying to override the toString() method and print without the hash. When I use my tostring() method when trying to print it requires me to create another object like asset server = new asset();. When I do this and use just server it returns the default constructor or it gives an error when I use server[i]. The code I have written returns this:
`ant -f C:\\Users\\kalle\\Documents\\NetBeansProjects\\assign7 -
Dnb.internal.action.name=run run
init:
Deleting: C:\Users\kalle\Documents\NetBeansProjects\assign7\build\built-
jar.properties
deps-jar:
Updating property file:
C:\Users\kalle\Documents\NetBeansProjects\assign7\build\built-
jar.properties
compile:
run:
server switch etc.
0
vendor model number
serial number
1
driver.asset#15db9742
server
server0
10
a1
1
driver.asset#15db9742
server
server1
20
a2
1
BUILD SUCCESSFUL (total time: 0 seconds)`
Here is my code:`
package driver;
public class Driver {
public static void main(String[] args) {
int i;
asset basic = new asset();
asset[] server = new asset[2];
server[0]= new asset("server", 10, "server0", "a1", 1);
server[1]= new asset("server", 20, "server1", "a2",1);
for (i=0;i<server.length;i++){
System.out.println(basic);
System.out.println(server[i].Type);
System.out.println(server[i].Name);
System.out.println(server[i].ID);
System.out.println(server[i].Serial);
System.out.println(server[i].PID);
}
}
}
public class asset {
String Type;
int ID;
String Name;
String Serial;
int PID;
int i;
public String getType(){
return Type;
}
public void setType(String Type){
this.Type = Type;
}
public int getID(){
return ID;
}
public void setID(int getid){
Integer.toString(ID);
this.ID= ID;
}
public String getName(){
return Name;
}
public void setName(String Name){
this.Name = Name;
}
public String getSerial(){
return Serial;
}
public void setSerial(String Serial){
this.Serial = Serial;
}
public int getPID() {
return PID;
}
public void setPID(int getPID) {
Integer.toString(PID);
this.PID= PID;
}
public asset(){
Name ="vendor model number";
ID =0;
Serial ="serial number";
Type ="server switch etc.";
PID =1;
System.out.println( Type + "\n " + ID + "\n " + Name + "\n " + Serial + "\n " + PID + "\n ");}
asset(String Type, int ID, String Name, String Serial, int PID){
this.Type= Type;
this.Name= Name;
this.PID= PID;
this.Serial= Serial;
this.ID= ID;
}
public String toString (asset[] a){
getType();
getID();
setID(ID);
getName();
getSerial();
getPID();
setPID(PID);
return this.Type + " " + this.ID + " " + this.Name + " " + this.Serial + " " + this.PID + " ";
}
}
How do i get rid of the "driver.asset#15db9742".
The correct way to override the toString method is to have the following structure :
public String toString(){
// return String type
}
For you (call getXY() does nothing alone) :
public String toString (){
return this.Type + " " + this.ID + " " + this.Name + " " + this.Serial + " " + this.PID + " ";
}
Also, to follow conventions, you'd better :
name classes in CamelCase : asset -> Asset
name attributs (&parameter&variables) follow camelCase : type, id, name, pid
Try this:
int i;
asset basic = new asset();
asset[] server = new asset[2];
server[0]= new asset("server", 10, "server0", "a1", 1);
server[1]= new asset("server", 20, "server1", "a2",1);
System.out.println(basic); // just delete this line.
for (i=0;i<server.length;i++)
{
System.out.println(server[i].Type);
System.out.println(server[i].Name);
System.out.println(server[i].ID);
System.out.println(server[i].Serial);
System.out.println(server[i].PID);}
}
You kept printing out the value of basic, that's probably why it churned out the the string hash name instead of the actual stored value. Just take the System.out.println(basic); out of the for loop? Even better, delete the line altogether!

Avoiding recursion in toString method

this is my huge mindblowing problem with a Java exercise. So, we've got this:
public class CyclicEmployee {
private int age;
private String name;
private CyclicEmployee boss;
private List<CyclicEmployee> subordinate
}
and our goal is to overwrite toString method by cutting fields which may lead to recursive infinity. Finally it's supposed to look like a printed object with a name, age, boss and subordinate.
Employee[age=30,name='Mike',boss=Employee[age=45,name='Ann'], subordinate=[Employee[age=25,name='Jimmy']]]
Well, I tried and found that i have no clue how to deal with toString overriding:
import java.util.ArrayList;
import java.util.List;
public class CyclicEmployee {
private int age;
private String name;
private CyclicEmployee boss;
private List<CyclicEmployee> subordinate ;
public CyclicEmployee(int age, String name) {
this.age=age;
this.name=name;
}
public static void main(String[] args) {
CyclicEmployee Mike = new CyclicEmployee(33,"Mike");
Mike.boss = new CyclicEmployee(44,"Ann");
Mike.subordinate = new ArrayList<CyclicEmployee>();
Mike.subordinate.add(new CyclicEmployee(24,"Jim"));
System.out.println(Mike.toString());
}
#Override
public String toString() {
return "CyclicEmployee{" +
"age=" + age +
", name='" + name + '\'' +
", boss=" + boss +
", subordinate=" + subordinate +
'}';
}
}CyclicEmployee{age=33, name='Mike', boss=CyclicEmployee{age=44, name='Ann', boss=null, subordinate=null}, subordinate=[CyclicEmployee{age=24, name='Jim', boss=null, subordinate=null}]}
It seems like I should cut all the "null" fields here, but I can't find the way out.
If I understand correctly, you do not want to print null CyclicEmployee objects. You can check if boss and subordinates are null and then if they are skip them in toString(). Since all of them are same type, this method will work for all of them.
#Override
public String toString() {
String str = "";
str = "CyclicEmployee{" +
"age=" + age +
", name='" + name + '\'';
if (boss != null) {
str += ", boss=" + boss;
}
if (subordinate.size() != 0) {
str += ", subordinate=" + subordinate;
}
str += '}';
return str;
}
Consider using existing data structure like this or this instead.
But if you really want to use your code, you can create a NonCyclicEmployee class
private static class NonCyclicEmployee {
private int age;
private String name;
public NonCyclicEmployee(int age, String name) {
this.age=age;
this.name=name;
}
#Override
public String toString() {
return "CyclicEmployee{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
}
And use it in your toString() of CyclicEmployee.
private CyclicEmployee boss;
private List<CyclicEmployee> subordinate ;
private NonCyclicEmployee ncBoss;
private List<NonCyclicEmployee> ncSubordinate ;
#Override
public String toString() {
return "CyclicEmployee{" +
"age=" + age +
", name='" + name + '\'' +
", boss=" + ncBoss +
", subordinate=" + ncSubordinate +
'}';
}
And create a method addBoss() and addSubordinate() to create both bosses (boss and ncBoss) and both subordinate at the same time.

Java custom toString function error

I'm trying to make a student class to take in and print some values about a student, but I get a "Invalid Method Declaration" error on line 29 and I have no idea why.
I am trying to contain student creation data inside one method, and a tostring() method in another method.
public class Student {
int ID;
int Age;
String Name;
double AvgLogin;
public Student(int ID,int Age,String Name,double AvgLogin)
{
this.ID = ID;
this.Age = Age;
this.Name = Name;
this.AvgLogin = AvgLogin;
}
public printer(int ID,string Name,int Age,double AvgLogin) {
System.out.println("Age : " + Age + " Average Login time : " + AvgLogin + "ID :" + ID +" Name : " + Name);
} //end method
public int getID() {
return ID;
}
public String getName() {
return Name;
}
public int getAge() {
return Age;
}
public void setAge(int Age) {
this.Age = Age;
}
public double getAvgLogin() {
return AvgLogin;
}
public void setAvgLogin(double AvgLogin) {
this.AvgLogin = AvgLogin;
}
}
//Student John = new Student(ID,Age,Name,AvgLogin)
you just missed the return type for your printer method. You should use the following code for your printer method.
public void printer(int ID,String Name,int Age,double AvgLogin) {
System.out.println("Age : " + Age + " Average Login time : " + AvgLogin + "ID :" + ID +" Name : " + Name);
}
You have two errors in your method. One of them is lack of the return type. Second one is typing string instead of String. Thirdly, it looks nice if you start variable name from lower case. You should also format code before making a question.
public void printer(int id, String name, int age, double avgLogin) {
System.out.println("Age: " + age + ", average login time: " + avgLogin + ", ID: " + id + ", name: " + name);
}

How to print contents of a class object by field?

I have a POJO class, Location that is used to map a JSON file to a class using Jackson. The current implementation can print out every Location object in the class by calling,Location's toString() but I'm wondering how I can print for example, just the location with id= "2", which would be name="Desert"
At the moment, I use a toString method like this to print all the contents of Location:
public String toString() {
return "Location [location=" + Arrays.toString(location) + ", id=" + id
+ ", description=" + description + ", weight=" + weight
+ ", name=" + name + ", exit=" + Arrays.toString(exit)
+"]";
}
Does anyone know how I can print specific locations within the Location object based on a field id?
This is an example of what is stored in the Location class when I call toString() on it:
http://hastebin.com/eruxateduz.vhdl
An example of one of the Locations within the Location object:
[Location [location=null, id=1, description=You are in the city of Tiberius. You see a long street with high buildings and a castle.You see an exit to the south., weight=100, name=Tiberius, exit=[Exit [title=Desert, direction=South]]]
This is the POJO location class I use to map the JSON fields to the class:
public class Location {
private Location[] location;
private int id;
private String description;
private String weight;
private String name;
private Exit[] exit;
private boolean visited = false;
private boolean goalLocation;
private int approximateDistanceFromGoal = 0;
private Location parent;
public Location[] getLocation() {
return location;
}
public void setLocation(Location[] location) {
this.location = location;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDescription ()
{
return description;
}
public void setDescription (String description)
{
this.description = description;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public String getName ()
{
return name;
}
public void setName (String name)
{
this.name = name;
}
public Exit[] getExit() {
return exit;
}
public void setExit(Exit[] exit) {
this.exit = exit;
}
public boolean isVisited() {
return visited;
}
public void setVisited(boolean visited) {
this.visited = visited;
}
public boolean isGoalLocation() {
return goalLocation;
}
public void setGoalLocation(boolean goalLocation) {
this.goalLocation = goalLocation;
}
public int getApproximateDistanceFromGoal() {
return approximateDistanceFromGoal;
}
public void setApproximateDistanceFromGoal(int approximateDistanceFromGoal) {
this.approximateDistanceFromGoal = approximateDistanceFromGoal;
}
public Location getParent() {
return parent;
}
public void setParent(Location parent) {
this.parent = parent;
}
#Override
public String toString() {
return "Location [location=" + Arrays.toString(location) + ", id=" + id
+ ", description=" + description + ", weight=" + weight
+ ", name=" + name + ", exit=" + Arrays.toString(exit)
+"]";
}
}
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.0</version>
</dependency>
You need the above dependency to define predicate unless you want to do it on your own.
public class Location {
private int id;
// more stuff here
private Predicate<Integer> filter;
public Location() {
this.filter = TruePredicate.INSTANCE;
}
public Location(int idFilter) {
this.filter = new EqualPrediate(idFilter);
}
public String toString() {
StringBuilder buffer = new StringBuilder();
if(filter.apply(this.id)) {
buffer.append("Location [location=" + Arrays.toString(location) + ", id=" + id
+ ", description=" + description + ", weight=" + weight
+ ", name=" + name + ", exit=" + Arrays.toString(exit)
+"]");
}
return buffer.toString();
}
}
This code is a simplified Visitor Pattern where the
'Visitor' -> your predicate
'this' -> 'this.id'
This works because your toString() is invoking the toString() of the nested Location objects which also have their predicates for filtering set.
If you aren't in control of their construction where you can propogate the filter then you can take this approach:
public String toString() {
StringBuilder buffer = new StringBuilder();
int i = 0;
for(Location l = this; i < locations.length; l = locations[i++])
if(filter.apply(l.id) {
buffer.append("Location [location=" + Arrays.toString(location) + ", id=" + id
+ ", description=" + description + ", weight=" + weight
+ ", name=" + name + ", exit=" + Arrays.toString(exit)
+"]");
}
return buffer.toString();
}
Stream.of(location).filters(l -> l.getId() == 2).foreach(System.out::println);
Does that work?
You can have a try with gson, which inputs a object and outputs a JSON or in the opposite side.
After u make the object a JSONObject, you can ergodic the JSON in order to ergodic object.

Categories