Java Class - Array println - java

i have 2 Class, the first class College and the second Lecturer.
in College class i have >> public Lecturer[] allLecturer;
I want the college department will receive the Lecturer department, But I have something strange when I try to print the college department.
class Lecturer:
public class Lecturer {
public String name;
public int numOfTimesPenFalls;
public String favoriteIceCream;
public int autoNumber;
//constructor
public Lecturer(String Name, int NumOfTimesPenFalls,
String FavoriteIceCream, int AutoNumber) {
this.name = Name;
this.numOfTimesPenFalls = NumOfTimesPenFalls;
this.favoriteIceCream = FavoriteIceCream;
this.autoNumber = AutoNumber;
}
#Override
public String toString(){
return "name: " +name+ " num Of Times Pen Falls: "+ numOfTimesPenFalls +
" favorite Ice Cream: " + favoriteIceCream + " auto Number: " + autoNumber;
}
}
class College:
public class College {
public String name;
public int numOfLecturer;
public Lecturer[] allLecturer;
public int maxLecturer;
//constructor
public College(String Name, int NumOfLecturer, Lecturer[] AllLecturer, int MaxLecturer) {
this.name = Name;
this.numOfLecturer = NumOfLecturer;
this.allLecturer = AllLecturer;
this.maxLecturer = MaxLecturer;
}
public College(String Name){
this.name = Name;
}
#Override
public String toString(){
return "Name College: " +name+ " num Of Lecturer: " + numOfLecturer +
" all Lecturer: " + allLecturer + " max Lecturer " + maxLecturer ;
}
}
main:
public class main {
public static void main(String[] args) {
Lecturer[] L1 = new Lecturer[] { new Lecturer("David", 3, "Banana",
1001) };
College myCollege = new College("College1", 20, L1, 10);
System.out.println(myCollege.toString());
}
}
Result output:
Name College: College1 num Of Lecturer: 20 all Lecturer: [LLecturer;#139a55 max Lecturer 10
Why it prints me the ([LLecturer;#139a55) Instead the details of the department?
If I write in main for loop:
for (int i = 0; i < L1.length; i++) {
System.out.println(L1[i]);
}
the Result output:
name: David num Of Times Pen Falls: 3 favorite Ice Cream: Banana auto Number: 1001
How do I fix this so that when I print the class College (System.out.println(myCollege.toString()) );
I also printed the information that is in the lecturer Department?
thank you.

hey when you concat an array with string it will use his toString function.
the default toString function will print something like you see in your code.
the toString of a single object in the array will print what you want .

Java arrays do not override Object's toString() method. just add the loop that you wrote to the toString() method of College
example solution:
#Override
public String toString(){
return "Name College: " +name+ " num Of Lecturer: " + numOfLecturer +
" all Lecturer: " + java.util.Arrays.toString(allLecturer) + " max Lecturer " + maxLecturer ;
}
and if you can use 3rd party library, take a look at Apache's StringUtils class, it has a handy join() method that produces a String from concatanating array of objects

change your toString() method in College.java to
#Override
public String toString(){
return "Name College: " +name+ " num Of Lecturer: " + numOfLecturer +
" all Lecturer: " + Arrays.toString(allLecturer) + " max Lecturer " + maxLecturer ;
}
and in your main method try to print your College reference
College myCollege = new College("College1", 20, L1, 10);
System.out.println(myCollege);
now your output is:
Name College: College1 num Of Lecturer: 20 all Lecturer: [name: David num Of Times Pen Falls: 3 favorite Ice Cream: Banana auto Number: 1001] max Lecturer 10

Related

Why is the compiler saying "cannot find symbol" to the getter methods? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
When I try to compile the code, it keeps saying "cannot find symbol" every single time I try to call a getter method. I'd love any and all suggestions as to how to fix the problem.
Here is the code with the main method
import java.util.Scanner;
public class Assignment10
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);
System.out.println("\nThis program displays some attributes and behaviors of two different dogs.");
//Create two Dogs objects
Dogs firstDog = new Dogs();
Dogs secondDog = new Dogs();
//Naming scheme for first dog
System.out.print("\nWhat would you like to name the first dog? ");
firstDog.setName(in.nextLine());
//Naming scheme for second dog
System.out.print("What would you like to name the second dog? ");
secondDog.setName(in.nextLine());
//Scheme for getting the breed of first dog
System.out.print("\nWhat is the breed of the first dog? ");
firstDog.setBreed(in.nextLine());
//Scheme for getting the breed of first dog
System.out.print("What is the breed of the second dog? ");
secondDog.setBreed(in.nextLine());
//Scheme to get age of first dog
System.out.println("\nWhere is the first dog in their lifespan? ");
System.out.print("Enter 1 for puppy, 2 for adolescent, 3 for adult, 4 for senior: ");
firstDog.setAge(in.nextInt());
//Scheme to get age of second dog
System.out.println("Where is the first dog in their lifespan? ");
secondDog.setAge(in.nextInt());
//Scheme to get weight of first dog
System.out.println("\nWhere is the first dog in the weight range?");
System.out.print("Enter 1 for low, 2 for medium, 3 for high: ");
firstDog.setWeight(in.nextInt());
//Scheme to get weight of second dog
System.out.println("Where is the second dog in the weight range?: ");
secondDog.setWeight(in.nextInt());
System.out.println("\nThank you for your input.");
System.out.println("The following describes the first dog:\n");
//Displaying the attributes and behaviors of the first dog
System.out.println( firstDog.getName + " is a " + firstDog.getAge + " month old " + firstDog.getWeight + " pound " + firstDog.getGender + " " + firstDog.getBreed + " who " + firstDog.getFleas + "fleas.");
System.out.print("When their owner tossed over a doggie treat, " + firstDog.getName + " jumped in the air and went ");
firstDog.eating();
System.out.println();
System.out.print("When " + firstDog.getName + " ran back to their owner after fetching the ball, the " + firstDog.getBreed + " dropped the ball and elatedly went ");
firstDog.barking();
System.out.println();
if ( firstDog.getFleas().equals("has") )
{
System.out.print("After rolling around in the mud, " + firstDog.getName + " always goes ");
firstDog.scratchingFleas();
}
//Displaying the attributes and behaviors of the second dog
System.out.println( secondDog.getName + " is a " + secondDog.getAge + " month old " + secondDog.getWeight + " pound " + secondDog.getGender + " " + secondDog.getBreed + " who " + secondDog.getFleas + "fleas.");
System.out.print( secondDog.getName + " loudly goes ");
secondDog.eating();
System.out.println(" whenever they eat.");
System.out.print( secondDog.getName + " goes ");
secondDog.barking();
System.out.println(" each and every time there's a squirrel in the backyard.");
if ( secondDog.getFleas().equals("has") )
{
System.out.print("The owners brought the " + secondDog.getBreed + " to the vet because " + secondDog.getName + " kept going ");
secondDog.scratchingFleas();
System.out.print(" as if there were fleas.");
}
}
}
and here is the code with the class that defines the objects
public class Dogs
{
private StringBuffer z = new StringBuffer("");
private StringBuffer name;
private StringBuffer breed;
private String gender;
private int age;
private double weight;
private String fleas;
private int i = (int)(Math.random() * 20);
private int j = (int)(Math.random() * 20);
private int k = (int)(Math.random() * 50);
private int l = (int)(Math.random() * 50);
public Dogs()
{
name = z;
breed = z;
gender = (i <= j) ? "female" : "male";
age = 0;
weight = 0;
fleas = (k <= l) ? "has " : "does not have ";
}
public void setName(String s) {
name = name.append(s);
}
public void setBreed(String s) {
breed = breed.append(s);
}
public void setAge(int i)
{
if (i == 1)
age = (int)(1 + Math.random() * 7);
if (i == 2)
age = (int)(8 + Math.random() * 10);
if (i == 3)
age = (int)(18 + Math.random() * 66);
if (i == 4)
age = (int)(84 + Math.random() * 49);
}
public void setWeight(int i)
{
if (i == 1)
weight = 10 + Math.random() * 30;
if (i == 2)
weight = 40 + Math.random() * 60;
if (i == 3)
weight = 100 + Math.random() * 50;
}
public String getName() {
return name.toString();
}
public int getAge() {
return age;
}
public double getWeight() {
return weight;
}
public String getGender() {
return gender;
}
public String getBreed() {
return breed.toString();
}
public String getFleas() {
return fleas;
}
public void eating() {
System.out.print("chomp chomp chomp!");
}
public void barking() {
System.out.print("woof woof woof!");
}
public void scratchingFleas() {
System.out.print("scrhh scrhh scrhh");
}
}
I really appreciate everyone who helps!!!!
You are not calling the getters. You do dog.getNamewhen you should be doing dog.getName();

Java vanClass giving cannot find symbol error [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I have code that has several classes with different cars and some classes. Below is my code, I'm not sure why vanClass van; is not working as it is basically a copy paste of the past classes that work. Any help is appreciated. To clarify, I am only having problems with the last few lines of the autopark class where I initiate vanClass as van and go from there.
import java.util.*;
class sedan {
String make;
String model;
String color;
int year;
double price;
boolean fourWD;
boolean isheavyDuty;
String carries;
public sedan(String initMake, String initModel, String initColor, int initYear, double initPrice) {
make = initMake;
model = initModel;
color = initColor;
year = initYear;
price = initPrice;
}
#Override
public String toString() {
String name = "Sedan";
String main = (color + " " + make + " " + model + " " + name + " (" + year + ") costs $" + price);
return main;
}
}
class SUV {
String make;
String model;
String color;
int year;
double price;
boolean fourWD;
String carries;
public SUV(String initMake, String initModel, String initColor, int initYear, double initPrice, boolean initFourWD){
make = initMake;
model = initModel;
color = initColor;
year = initYear;
price = initPrice;
fourWD = initFourWD;
}
public String toString() {
String name = "SUV";
String main = new String();
if (fourWD) {
main = ("4WD " + color + " " + make + " " + model + " " + name + " (" + year + ") costs $" + price);
}
else {
main = (color + " " + make + " " + model + " " + name + " (" + year + ") costs $" + price);
}
return main;
}
}
class truckClass {
String make;
String model;
String color;
int year;
double price;
boolean fourWD;
boolean isheavyDuty;
String carries;
public truckClass(String initMake, String initModel, int initYear, double initPrice, boolean initisheavyDuty, String initCarries){
make = initMake;
model = initModel;
year = initYear;
price = initPrice;
isheavyDuty = initisheavyDuty;
carries = initCarries;
}
public String toString() {
String name = "Truck";
String main = (make + " " + model + " " + name + " (" + year + ") carries" + carries + " costs $" + price);
return main;
}
class vanClass {
String make;
String model;
int year;
double price;
boolean isCovered;
String carries;
public vanClass(String initMake, String initModel, int initYear, double initPrice, boolean initisCovered, String initCarries){
make = initMake;
model = initModel;
year = initYear;
price = initPrice;
isCovered = initisCovered;
carries = initCarries;
}
public String toString() {
String name;
String main;
if (isCovered()){
name = "covered Van";
String main = (make + " " + model + " " + name + " (" + year + ") carries" + carries + " costs $" + price);
}
else {
name = "Van";
String main = (make + " " + model + " " + name + " (" + year + ") carries" + carries + " costs $" + price);
}
return main;
}
}
public class autoPark {
public static void main(String args[]) {
sedan sedan1; // declaring cars object by name sedan1
sedan1 = new sedan("Ford" , "Model-1" , "white" , 2015, 20000); // initialising sedan1 using sedan constructor
System.out.println(sedan1); // printing sedan1 for invoking toString() method
SUV suv; // declaring cars object by name suv
suv = new SUV("Ford" , "Model-1" , "white" , 2015, 20000, true); // initialising suv using SUV constructor
System.out.println(suv); // printing suv for invoking toString() method
truckClass truck; //declaring cars object by name truck
truck = new truckClass("Ford" , "Model-1" , 2015, 20000, true, "2"); // initialising truck using truck constructor
System.out.println(truck); // printing truck for invoking toString() method
vanClass van;
van = new vanClass("Ford" , "Model-1" , 2015, 20000, true, "2";
System.out.println(van);
}
}
I came across 4 issues
missing } just before starting vanClass
missing ) after van = new vanClass("Ford" , "Model-1" , 2015, 20000, true, "2");
extra pair of parenthesis after isCovered which is a member data instead of method
Declaring main as String twice inside the toString method of SUV class
import java.util.*;
class sedan {
String make;
String model;
String color;
int year;
double price;
boolean fourWD;
boolean isheavyDuty;
String carries;
public sedan(String initMake, String initModel, String initColor, int initYear, double initPrice) {
make = initMake;
model = initModel;
color = initColor;
year = initYear;
price = initPrice;
}
#Override
public String toString() {
String name = "Sedan";
String main = (color + " " + make + " " + model + " " + name + " (" + year + ") costs $" + price);
return main;
}
}
class SUV {
String make;
String model;
String color;
int year;
double price;
boolean fourWD;
String carries;
public SUV(String initMake, String initModel, String initColor, int initYear, double initPrice, boolean initFourWD){
make = initMake;
model = initModel;
color = initColor;
year = initYear;
price = initPrice;
fourWD = initFourWD;
}
public String toString() {
String name = "SUV";
String main = new String();
if (fourWD) {
main = ("4WD " + color + " " + make + " " + model + " " + name + " (" + year + ") costs $" + price);
}
else {
main = (color + " " + make + " " + model + " " + name + " (" + year + ") costs $" + price);
}
return main;
}
}
class truckClass {
String make;
String model;
String color;
int year;
double price;
boolean fourWD;
boolean isheavyDuty;
String carries;
public truckClass(String initMake, String initModel, int initYear, double initPrice, boolean initisheavyDuty, String initCarries){
make = initMake;
model = initModel;
year = initYear;
price = initPrice;
isheavyDuty = initisheavyDuty;
carries = initCarries;
}
public String toString() {
String name = "Truck";
String main = (make + " " + model + " " + name + " (" + year + ") carries" + carries + " costs $" + price);
return main;
}
}
class vanClass {
String make;
String model;
int year;
double price;
boolean isCovered;
String carries;
public vanClass(String initMake, String initModel, int initYear, double initPrice, boolean initisCovered, String initCarries){
make = initMake;
model = initModel;
year = initYear;
price = initPrice;
isCovered = initisCovered;
carries = initCarries;
}
public String toString() {
String name;
String main;
if (isCovered){
name = "covered Van";
main = (make + " " + model + " " + name + " (" + year + ") carries" + carries + " costs $" + price);
}
else {
name = "Van";
main = (make + " " + model + " " + name + " (" + year + ") carries" + carries + " costs $" + price);
}
return main;
}
}
public class autoPark {
public static void main(String args[]) {
sedan sedan1; // declaring cars object by name sedan1
sedan1 = new sedan("Ford" , "Model-1" , "white" , 2015, 20000); // initialising sedan1 using sedan constructor
System.out.println(sedan1); // printing sedan1 for invoking toString() method
SUV suv; // declaring cars object by name suv
suv = new SUV("Ford" , "Model-1" , "white" , 2015, 20000, true); // initialising suv using SUV constructor
System.out.println(suv); // printing suv for invoking toString() method
truckClass truck; // declaring cars object by name truck
truck = new truckClass("Ford" , "Model-1" , 2015, 20000, true, "2"); // initialising truck using truck constructor
System.out.println(truck); // printing truck for invoking toString() method
vanClass van;
van = new vanClass("Ford" , "Model-1" , 2015, 20000, true, "2");
System.out.println(van);
}
}
You need to consider using inheritance as mentioned by others.
I fixed and refactored your class using inheritance:
abstract class Vehicle{
protected String maker;
protected String model;
protected int year;
protected double price;
public Vehicle(String maker, String model, int year, double price) {
this.maker=maker;
this.model=model;
this.year=year;
this.price=price;
}
abstract String getType();
#Override
public String toString() {
return maker + " " + model + " " + getType() + " (" + year + ") costs $" + price;
}
}
abstract class HeavyVehicle extends Vehicle{
protected String carries;
public HeavyVehicle(String maker, String model, int year, double price, String carries) {
super(maker, model, year, price);
this.carries=carries;
}
}
class SUV extends HeavyVehicle{
String color;
boolean fourWD;
public SUV(String maker, String model, String initColor, int year, double price,
boolean initFourWD) {
super(maker,model,year,price,"1");
color = initColor;
fourWD = initFourWD;
}
public String toString() {
StringBuilder sb = new StringBuilder();
if (fourWD) {
sb.append("4WD ");
}
sb.append(color + " " + super.toString());
return sb.toString();
}
#Override
String getType() {
return "SUV";
}
}
class Truck extends HeavyVehicle{
public Truck(String maker, String model, int year, double price,String carries) {
super(maker,model,year,price,carries);
}
public String toString() {
return maker + " " + model + " " + getType() + " (" + year + ") carries" + carries + " costs $" + price;
}
#Override
String getType() {
return "Truck";
}
}
class Van extends HeavyVehicle{
boolean isCovered;
public Van(String maker, String model, int year, double price, boolean isCovered, String carries){
super(maker,model,year,price,carries);
this.isCovered = isCovered;
}
public String toString() {
String name = isCovered ? "covered Van" : getType();
return maker + " " + model + " " + name + " (" + year + ") carries" + carries + " costs $" + price;
}
#Override
String getType() {
return "Van";
}
}
class Sedan extends Vehicle{
String color;
public Sedan(String maker, String model, String color, int year, double price) {
super(maker,model,year,price);
this.color = color;
}
#Override
public String toString() {
return color + " " + super.toString();
}
#Override
String getType() {
return "Sedan";
}
}
public class Main {
public static void main(String args[]) {
Sedan sedan1; // declaring cars object by name sedan1
sedan1 = new Sedan("Ford", "Model-1", "white", 2015, 20000); // initialising sedan1 using sedan constructor
System.out.println(sedan1); // printing sedan1 for invoking toString() method
SUV suv; // declaring cars object by name suv
suv = new SUV("Ford", "Model-1", "white", 2015, 20000, true); // initialising suv using SUV constructor
System.out.println(suv); // printing suv for invoking toString() method
Truck truck; // declaring cars object by name truck
truck = new Truck("Ford", "Model-1", 2015, 20000, "2"); // initialising truck using truck constructor
System.out.println(truck); // printing truck for invoking toString() method
Van van;
van = new Van("Ford", "Model-1", 2015, 20000, true, "2");
System.out.println(van);
}
}
Was missing a } and ). Silly mistake

Java: Accessibility problems with two methods in ArrayList (three classes)

I have three classes: Main,ReusaxCorp and Employee. Let's get straight to the point: In the ReusaxCorp class I want to implement two methods: retrieveEmployee, which iterates through the Array List and prints out all employees information. So I tried this:
public void retrieveEmployee() {
for (int i = 0; i < employees.size(); i++) {
System.out.println("ID: " + employee.ID + END_OF_LINE + "Name: " + employee.name + END_OF_LINE + "salary: " + employee.grossSalary);
}
}
But that does not work, because I can't access - for instance - employee.ID or employee.name. In the second method. updateEmployee I would have liked to change the information, but that doesn't work either because of the accessibility. I appreciate any kind of help. Here are my three classes:
public class Employee {
protected String ID;
protected String name;
protected double grossSalary;
final String END_OF_LINE = System.lineSeparator();
public Employee (String ID, String name, double grossSalary){
this.ID = ID;
this.name = name;
this.grossSalary = grossSalary;
}
public double getGrossSalary() {
return grossSalary;
}
public void setGrossSalary(double grosssalary) {
this.grossSalary = grossSalary;
}
public String getName(){
return name;
}
public void setName(String name) {
this.name = name;
}
}
Here's my Main class:
public class Main {
private static String END_LINE;
private Scanner sc;
public String name;
public String ID;
public double salary;
private int GPA;
private ReusaxCorp reusaxcorp;
public Main(){
sc = new Scanner(System.in);
END_LINE = System.lineSeparator();
}
public void presentoptions(){
while (true){
System.out.println("=== Welcome === ");
System.out.println("Choose an option below: ");
System.out.println(" ");
System.out.println("1. Register an employee. ");
System.out.println("2. Remove an employee. ");
System.out.println("3. Retrieve an employees information. ");
int option = sc.nextInt();
switch (option) {
case 1:
System.out.println("What type of employee? " + END_LINE
+ " - Intern. " + END_LINE
+ " - Employee. " + END_LINE
+ " - Manager. " + END_LINE
+ " - Director." + END_LINE);
String type = sc.nextLine();
createEmployee();
break;
case 2:
break;
case 3:
reusaxcorp.retrieveEmployee();
break;
default:
System.out.println("Error. Please try again.");
break;
}
}
}
public void createEmployee(){
String typeofemployee = sc.nextLine();
System.out.println("What's the ID of the new " + typeofemployee + "?");
ID = sc.nextLine();
System.out.println("What's the name of the new " + typeofemployee + "?");
name = sc.nextLine();
System.out.println("What's the salary of the new " + typeofemployee + "?");
salary = sc.nextDouble();
Employee employee = new Employee(ID, name, salary);
switch (typeofemployee) {
case "Intern":
System.out.println("What's the new Interns GPA? ");
GPA = sc.nextInt();
case "Employee":
break;
case "Manager":
break;
case "Director":
break;
default:
System.out.println("Error");
break;
}
}
public static void main(String[] args) {
Main runcode = new Main();
runcode.presentoptions();
}
}
And here at last the ReusaxCorp class.
public class ReusaxCorp extends Main {
ArrayList<Employee> employees = new ArrayList<Employee>();
final String END_OF_LINE = System.lineSeparator();
public void registerEmployee(){
employees.add(new Employee(ID, name, salary));
}
public void retrieveEmployee() {
for (int i = 0; i < employees.size(); i++) {
System.out.println("ID: " + employee.ID + END_OF_LINE + "Name: " + employee.name + END_OF_LINE + "salary: " + employee.grossSalary);
}
}
public void updateEmployee(){
}
}
You are trying to access the variable employee which does not exist anywhere int the class.
public void retrieveEmployee() {
for (int i = 0; i < employees.size(); i++) {
//add this line
Employee employee = employees.get(i);
System.out.println("ID: " + employee.ID + END_OF_LINE + "Name: " + employee.name + END_OF_LINE + "salary: " + employee.salary);
}
}
You can also use a for-each loop:
for(Employee employee: employees){
System.out.println("ID: " + employee.ID + END_OF_LINE + "Name: " + employee.name + END_OF_LINE + "salary: " + employee.salary);
}
Also note that accessing the fields such as ID using employee.ID is only applicable if the classes are in the same package (being protected). Otherwise you need to create a getter and access them using getter such as employee.getID()
Use employee.getId() instead of employee.ID while iterating through the list of employees, you already have those public getter methods implemented while the class members are protected. Do so for the other class members (name and so on) as well…
You can do that in your solution by getting the employee from the list by index like
System.out.println(employees.get(i).getId());
or you just take a "for each" loop like
for (Employee employee : employees) {
System.out.println(employee.getId());
}

How can I print out in columns in java

This is where I am printing out and I need it to print in columns.aLeaderboard is an array list with a custom class.it contains several different ints
System.out.println("Position Team Games Played Home Wins Home Draws Home Losses Home Goals For Home Goals Against Away Wins Away Draws Away Losses Away Goals For Away Goals Against Goal Difference Total Points");
for(int counter = 0;counter<teamName.size();counter++)
{
System.out.print((counter + 1) + " " + teamName.get(counter) + " " + (aLeaderboard.get(counter)).getGamesPlayed() + " " + (aLeaderboard.get(counter)).getHomeWins() + " " + (aLeaderboard.get(counter)).getHomeDraws() + " ");
System.out.print((aLeaderboard.get(counter)).getHomeLosses() + " " + (aLeaderboard.get(counter)).getAwayWins() + " " + (aLeaderboard.get(counter)).getAwayWins() + " " + (aLeaderboard.get(counter)).getAwayDraws() + " ");
System.out.print((aLeaderboard.get(counter)).getHomeGoalsFor() + " " + (aLeaderboard.get(counter)).getHomeGoalsAgainst() + " " + (aLeaderboard.get(counter)).getAwayLosses() + " " + (aLeaderboard.get(counter)).getGamesPlayed() + " ");
System.out.print((aLeaderboard.get(counter)).getAwayGoalsFor() + " " + (aLeaderboard.get(counter)).getAwayGoalsAgainst() + " " + (aLeaderboard.get(counter)).getGoalsDifference() + " " + (aLeaderboard.get(counter)).getTotalPoints());
System.out.println();
}
I would use System.out.printf(...) and use a template String to help be sure that all columns line up. Then you could print things out easily in a for loop.
For example:
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
public class Foo4 {
public static void main(String[] args) {
List<Bar4> bar4List = new ArrayList<>();
bar4List.add(new Bar4("Donald", 3, "A", 22.42));
bar4List.add(new Bar4("Duck", 100, "B", Math.PI));
bar4List.add(new Bar4("Herman", 20, "C", Math.sqrt(20)));
String titleTemplate = "%-10s %6s %6s %9s%n";
String template = "%-10s %6d %6s %9s%n";
System.out.printf(titleTemplate, "Name", "Value", "Grade", "Cost");
for (Bar4 bar4 : bar4List) {
System.out.printf(template, bar4.getName(),
bar4.getValue(), bar4.getGrade(), bar4.getCostString());
}
}
}
class Bar4 {
private String name;
private int value;
private String grade;
private double cost;
private NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
public Bar4(String name, int value, String grade, double cost) {
this.name = name;
this.value = value;
this.grade = grade;
this.cost = cost;
}
public String getName() {
return name;
}
public int getValue() {
return value;
}
public String getGrade() {
return grade;
}
public double getCost() {
return cost;
}
public String getCostString() {
return currencyFormat.format(cost);
}
}
Which would return:
Name Value Grade Cost
Donald 3 A $22.42
Duck 100 B $3.14
Herman 20 C $4.47
For more details on the user of the String format specifiers (i.e., the %6d and %6s above), please look at the Formatter API.

OOP in java - creating objects

OK guys, up till now (and since I'm a beginner) I was programming Java based on procedural programming and it was nice and all but It's time to use Java like-a-boss.
I'm learning the OOP concept now while writing some code as practice.
What I dont understand is that if I create a few objects this way:
Contact first = new Contact(25, "Yosi", "Male");
System.out.println("Age of contact " + first.toString() + " is - "
+ first.getAge() + " " + first.getName());
Contact second = new Contact(22, "lisa", "Femal");
System.out.println("Age of contact " + second.toString() + " is - "
+ second.getAge() + " " + second.getName());
Contact third = new Contact(34, "Adam", "Male");
System.out.println("Age of contact " + third.toString() + " is - "
+ third.getAge() + " " + third.getName());
The result will be:
Age of contact Contact#173f7175 is - 25 Yosi
Age of contact Contact#4631c43f is - 22 lisa
Age of contact Contact#6d4b2819 is - 34 Adam
But if I then try to print the first contact again, it will get the values of the last object created. I mean, for this code:
Contact first = new Contact(25, "Yosi", "Male");
System.out.println("Age of contact " + first.toString() + " is - "
+ first.getAge() + " " + first.getName());
Contact second = new Contact(22, "lisa", "Femal");
System.out.println("Age of contact " + second.toString() + " is - "
+ second.getAge() + " " + second.getName());
Contact third = new Contact(34, "Adam", "Male");
System.out.println("Age of contact " + third.toString() + " is - "
+ third.getAge() + " " + third.getName());
System.out.println("Age of contact " + first.toString() + " is - "
+ first.getAge() + " " + first.getName());
the result will be:
Age of contact Contact#173f7175 is - 25 Yosi
Age of contact Contact#4631c43f is - 22 lisa
Age of contact Contact#6d4b2819 is - 34 Adam
Age of contact Contact#173f7175 is - 34 Adam
I've added up the object string representation so you can see the different objects.
I thought I was creating a new object and each object has it's own instance values?
could you guys explain to me?
This is the contacts class:
public class Contact {
private static int age = 0;
private static String name = "Unknown";
private static String gender = "Male";
public Contact(int a, String n, String g) {
age = a;
name = n;
gender = g;
}
public Contact() {
}
public static int getAge() {
return age;
}
public static String getName() {
return name;
}
public static String getGender() {
return gender;
}
public static void setAge(int a) {
age = a;
}
public static void setName(String n) {
name = n;
}
public static void setGender(String g) {
gender = g;
}
}
Please note that if I remove static qualifier I get errors saying "cannot make a static referance to the non static field"
Remove the static qualifier from your instance variables and/or methods (age, getAge, name, getName).
This can occur if you mistakenly use a static variable:
class Stat {
static String name;
Stat(String n) {
name = n;
}
}
In the example class above, all instances will share the same value for name.
Use non-static variables for instance members:
class Stat {
String name;
Stat(String n) {
name = n;
}
}
Well, Yosi.Static qualifiers tie your fields(and methods) to your class not to your object and each Object of your Class(Contact) share the same value.
Whenever you instantiate it by New, this value gets updated. So when you print fourth time the value it has is what you update it in third time. That'y its printing like that.
As I see you code, if you remove static from everywhere, your code will behave as you desire.

Categories

Resources