Java custom toString function error - java

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

Related

Simple database on 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.

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!

"constructor Employee in class Employee cannot be applied to given types;"

I seem to be getting the constructor Employee in class Employee cannot be applied to given types; error and I'm not sure how to fix it. Im fairly new to coding so the simpler explanation the better.
method where the error occurs
specifically the "new Employee();" in the first line
Collections.sort(employees, new Employee());
System.out.println("\nFirst and Last Names of Employees sorted based on first Name\n");
for (Employee employee : employees) {
System.out.println("First Name: " + employee.getfirstName() + " Last Name: " + employee.getlastName()
+ " Salary: " + employee.getSalary());
}
List<Employee> newHirees = readFile(hirefile);
// Add new Hired employees
employees.addAll(newHirees);
Collections.sort(employees, new Employee());
System.out.println("\nFirst and Last Names of Employees sorted based on first Name after adding new hires\n");
for (Employee employee : employees) {
System.out.println("First Name: " + employee.getFirstName() + " Last Name: " + employee.getLastName()
+ " Salary: " + employee.getSalaryPaid());
}
List<Employee> firedEmployees = readFile(firefile);
System.out.println("\nFirst and Last Names of Employees After removing fired employees\n");
for (Employee fired : firedEmployees) {
String firstName=fired.getFirstName();
String lastname=fired.getLastName();
for (Employee employee : employees) {
if (employee.getFirstName().trim().equals(firstName)
&& employee.getLastName().equals(lastname)) {
employees.remove(employee);
}
}
}
for (Employee employee : employees) {
System.out.println("First Name: " + employee.getFirstName() + " Last Name: " + employee.getLastName());
}
}
//Employee class
public class Employee{
String firstName;
String lastName;
String gender;
int tenure;
String rate;
double salary;
public Employee( String firstName, String lastName,String gender,int tenure, String rate,double salary )
{
this.firstName=firstName;
this.lastName=lastName;
this.gender=gender;
this.tenure=tenure;
this.rate=rate;
this.salary=salary;
}
//get and set methods
public void setfirstName(String nm) {
this.firstName=nm;}
public void setlastName(String nm) {
this.lastName=nm;}
String getfirstName() {
return this.firstName;}
String getlastName() {
return this.lastName;}
public void setGender(String nm) {
this.gender=nm;}
public void setRate(String nm) {
this.rate=nm;}
String getGender(){
return this.gender;}
String getRate(){
return this.rate;}
void setSalary(double pr){
this.salary=pr;}
double getSalary(){
return this.salary;}
void setTenure(int q){
this.tenure=q;}
int getTenure(){
return this.tenure;}
public String toString(){
String s=this.firstName+" "+this.lastName+" "+this.gender+" "+this.tenure+" "+
this.rate+" "+this.salary;
return(s);
}
}
You don't have a parameterless constructor, so new Employee() won't work.
Why are you trying to pass that as a parameter there anyway?

Mutator methods not storing values for the class that I have just made?

Here is the class:
package employee;
public class Employee
{
private String name, department,position;
private int idNumber;
public Employee(String n, int id, String depart,String pos)
{
n= name;
id=idNumber;
depart=department;
pos=position;
}
public Employee(String n, int id)
{
n= name;
id=idNumber;
department="";
position="";
}
public Employee()
{
name="";
idNumber=0;
department="";
position="";
}
public void setName(String n)
{
n=name;
}
public void setDepartment(String depart)
{
depart=department;
}
public void setPosition(String pos)
{
pos=position;
}
public void setId(int id)
{
id=idNumber;
}
public String getName()
{
System.out.println();
return name;
}
public String getDepartment()
{
return department;
}
public String getPosition()
{
return position;
}
public int getId()
{
return idNumber;
}
}
Here is the program:
package employee;
public class RunEmployee
{
public static void main(String[] args)
{
Employee first= new Employee();
first.setName("Susan Myers");
first.setId(47899);
first.setDepartment("Accounting");
first.setPosition("Vice President");
Employee sec= new Employee("Mark Jones",39119,"IT","Programmer");
Employee third= new Employee("Joy Rogers", 81774);
third.setDepartment("Manfacturing");
third.setPosition("Engineer");
/*Printing employee ones information*/
System.out.print("Employee #1- using the no-arg constructor.");
System.out.println("Name: " + first.getName());
System.out.println("Id Number: "+ first.getId());
System.out.println("Department: " + first.getDepartment());
System.out.println("Position: "+ first.getPosition());
/*Printing employee twos information*/
System.out.println("Name: " + sec.getName());
System.out.println("Id Number: "+ sec.getId());
System.out.println("Department: " + sec.getDepartment());
System.out.println("Position: "+ sec.getPosition());
/*Printing employee threes information*/
System.out.print("Employee #3- using a constructor that accepts the name"
+ "and ID number only.");
System.out.println("Name: " + third.getName());
System.out.println("Id Number: "+ third.getId());
System.out.println("Department:" + third.getDepartment());
System.out.println("Position: "+ third.getPosition());
}
}
For this project, I am simply trying to store values into the constructor in different ways. However, my output is showing that my mutator methods are not storing any values. I tried to post my output but I do not have the reputation points. Basically, all the the values for the things I tried to arguments say zero or null.
You've got your assignments backwards!
n = name; puts the value of name to n, not the other way around.
You are assigning the value from the Employee instance to your passed in parameters. To prevent that, it is probably a good idea to use this -
this.name = n; // <-- assign n to the name field of the current instance.
In your example code, this.n would have given you a compile time error.

Trouble with inner class, toString confliction

Based on one of the Head First books examples I'm having a little trouble in which the toString method is causing issues with my student and they're uni and home address being outputted correctly. All i'm trying to do is output if a students uni address is empty use his home address else use the uni one.
But my test data looks like the following
John John72 Nottingham Drive
John72 Nottingham Drive
public class Test {
public static void main(String[] args){
Student student1 = new Student("John", 19, "Walkers Way");
student1.setUniAddress(72, "Nottingham Drive");
System.out.print(student1.toString());
}
}
Other Class
public class Student {
private String name;
private Address homeAddress, uniAddress;
public Student(String name, int houseNumber, String homeStreet){
this.name = name;
this.homeAddress = new Address(houseNumber, homeStreet);
}
public String getName() { return this.name; }
public Address getHomeAddress(){
if(this.uniAddress == null){
return this.homeAddress;
}else{
return getUniAddress();//this.uniAddress;
}
}
public Address getUniAddress() { return this.uniAddress; }
public void setUniAddress(int number, String add){
Address address = new Address(number, add);
uniAddress = address;
}
#Override
public String toString(){
return getName() + " " + getHomeAddress() + " " + getUniAddress() + "\n";
}
public class Address{
private int number;
private String street;
public Address(int no, String street){
this.number = no;
this.street = street;
}
#Override
public String toString(){
return name + number + " " + street + "\n";
}
}
}
Your getHomeAddress method takes care of displaying the uni address, so this line:
return getName() + " " + getHomeAddress() + " " + getUniAddress() + "\n";
can be shortened to:
return getName() + " " + getHomeAddress() + " " + "\n";
Otherwise your getHomeAddress method will pull the uni address, then your getUniAddress method will pull the uni address again.
Also in your address toString you are pulling the person's name and you probably didn't mean to (and you might not want a newline here either since you have a newline in your other toString method).
#Override
public String toString(){
return number + " " + street;
}

Categories