OOP in java - creating objects - java

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.

Related

program printing extra null that I can't seem to get rid of

public class Student {
private String courses = null;
}
.....Some code here.......
//Enroll in courses
public void enroll() {
//Get inside a loop and user hits Q
do {
System.out.print("Enter Course to Enroll(Q to quit): ");
Scanner in = new Scanner(System.in);
String course = in.nextLine();
if (!course.equals("Q")) {
courses = courses + "\n " + course;
tuitionBalance = tuitionBalance + costOfCourse;
}
else{ break; }
}while ( 1!= 0);
}
......Some code here......
//Show Status
public String showInfo() {
return "Name: " + firstName + " " + lastName +
"\nGrade level: " + gradeYear +
"\nStudent ID: " + studentId +
"\nCourses Enrolled:" + courses +
"\nBalance: $" + tuitionBalance;
}
}
Everything seems to be running just fine. But there's an extra null printed after the Courses Enrolled that sticks out like a sore thumb. How could I get rid of it? I've tried setting the String variable courses to null and also without assigning but doesn't seem to affect the result
Name: Frank Kuo
Grade level: 1
Student ID: 11001
Courses Enrolled:null
Math101
Balance: $0
You can replace private String courses = null; with private String courses = ""; to get rid of the null.

How to get values for specific items in enum array in Java?

Continuing on from this post I've been looking into and messing around with enums a bit, and now I've managed to create an enum that holds the values I want and outputs them in the way I want, now I'd just like to know how I could get the same output but for a single item rather than every item. Again, I'm very new to Java so a simple explanation as to how and why would be greatly appreciated.
public class PeriodicTable {
public enum Element {
Lithium("Li", "Alkali Metals", 6.941),
Iron("Fe", "Transition Metals", 55.933);
private String symbol;
private String group;
private Double weight;
private Element(String symbol, String group, Double weight) {
this.symbol = symbol;
this.group = group;
this.weight = weight;
}
}
public static void main(String[] args) {
for(Element cName : Element.values()) {
System.out.println("Element: " + cName + " (" + cName.symbol + ")" + "\nGroup: " + cName.group + "\nAtomic Weight: " + cName.weight);
}
}
}
You can use the valueOf method passing in the user input to retrieve the enum:
Element ele = Elements.valueOf(input);
And then you can use your print statement to print the info:
Element cName = Element.valueOf("Iron");
System.out.println("Element: " + cName + " (" + cName.symbol + ")" + "\nGroup: " + cName.group + "\nAtomic Weight: " + cName.weight);
Output:
Element: Iron (Fe)
Group: Transition Metals
Atomic Weight: 55.933

JAVA - Issues Printing ArrayList

I'm currently attempting to make a lottery program through the use of a GUI. I can not figure out why the method getTicketNumbers() is not returning anything. It is simply printing [].
And so too is:
String output = "Name: " + name + "\nNumbers: " + ticketNumbers + "\n\n";
tickNumbers is outputting [] but name successfully prints out the name.
I added a System.out.print to the Ticket class in the constructor to confirm the ArrayList is being passed successfully and it is:
public Ticket(ArrayList<Integer> ticketNumbers, String name) {
this.ticketNumbers = ticketNumbers;
this.name = name;
System.out.print("Are the numbers being passed:" + ticketNumbers + "\n");
}
The method toString is successfully printing the name but again, it is not printing the ArrayList called ticketNumbers.
private void enterLottoButtonActionPerformed(java.awt.event.ActionEvent evt) {
if (nameInput.getText().equalsIgnoreCase("")) {
JOptionPane.showMessageDialog(null, "Please Enter Your Name", "Error", JOptionPane.ERROR_MESSAGE);
} else if (ticketNumbers.size() < 4) {
JOptionPane.showMessageDialog(null, "Please Enter Four Numbers", "Error", JOptionPane.ERROR_MESSAGE);
} else {
ticketList.add(new Ticket(ticketNumbers, nameInput.getText()));
JOptionPane.showMessageDialog(null, "You Successfully Entered! \n\nName: " + nameInput.getText() + "\nNumbers: " + ticketNumbers.toString());
ticketNumbers.clear();
numbersTextField.setText("");
nameInput.setText("");
numberOfPeopleLabel.setText(" People Entered: " + ticketList.size());
}
Ticket Class:
import java.util.ArrayList;
import java.util.Collections;
import javax.swing.JOptionPane;
public class Ticket {
private String name;
private ArrayList<Integer> ticketNumbers = new ArrayList<>();
public Ticket(ArrayList<Integer> ticketNumbers, String name) {
this.ticketNumbers = ticketNumbers;
this.name = name;
System.out.print("Are the numbers being passed:" + ticketNumbers + "\n");
}
public String getName() {
return name;
}
public ArrayList<Integer> getTicketNumbers() {
return ticketNumbers;
}
public ArrayList<Integer> getSortedTicketNumbers() {
Collections.sort(ticketNumbers);
return ticketNumbers;
}
#Override
public String toString() {
String output = "Name: " + name + "\nNumbers: " + ticketNumbers + "\n\n";
return output;
}
}
If needed, code in its entirety:
http://pastebin.com/7i8VWQLk and http://pastebin.com/iRd49Nc7
ticketNumbers.clear()
This line cause the problem. As you said, during the construction of Ticket object, the data been passed in correctly in this line: ticketList.add(new Ticket(ticketNumbers, nameInput.getText()));. But you cleared them afterwards. You will need a clone of ticketList. Regardless of the best practice, you can do it inside Ticket class.
private List<Integer> clonedTicketNumbersList = new ArrayList<Integer>();
public Ticket(ArrayList<Integer> ticketNumbers, String name) {
this.ticketNumbers = ticketNumbers;
this.name = name;
for(Integer ticketNum : ticketNumbers) {
clonedTicketNumbersList.add(ticketNum );
}
System.out.print("Are the numbers being passed:" + ticketNumbers + "\n");
}
#Override
public String toString() {
String output = "Name: " + name + "\nNumbers: " + clonedTicketNumbersList + "\n\n";
return output;
}
It looks like you're copying the reference to the list, and so when you clear it in one place (or modify it) it changes/clears everywhere.
Try making a defensive copy. Like:
ArrayList<Integer> tickets = new ArrayList<>(ticketNumbers)

Java Class - Array println

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

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.

Categories

Resources