Print the value of a Java constructor - java

I am a java beginner and I am trying to get used to objects. Is there anyway that I can print out the value of a constructor in main? How can I print out the value's Kevin,20? Thanks
public class MainConstructor {
public static void main(String[] args) {
ConstructorClass emp1 = new ConstructorClass("Kevin", 20);
}
}
//Constructor Class
public class ConstructorClass {
private String name;
private int number;
public ConstructorClass(String name, int number) {
this.name = name;
this.number = number;
System.out.println("called");
}
}

Add a toString() method to ConstructorClass:
public String toString() {
return name + "," + number;
}
Then call this from main:
public static void main(String[] args) {
ConstructorClass emp1 = new ConstructorClass("Kevin",20);
System.out.println(emp1.toString());
}

Try using toString() in your class
public String toString() {
return this.name + "," + this.number;
}
and in your main just do emp1.toString(); to print it to your console

Constructor is basically just another method (but for the love of what is holy, never say that during interview or even to your professor) so there is nothing wrong with doing this:
public class ConstructorClass {
private String name;
private int number;
public ConstructorClass(String name, int number) {
this.name = name;
this.number = number;
System.out.println(name+" "+number);
}
}
But this solution is really ugly and kind of "hotfixy". Better solution would be to have constructor to only get the values and have separate method to print what you want:
public ConstructorClass(String name, int number) {
this.name = name;
this.number = number;
}
void printNameAndNumber() {
System.out.println(name+" "+number);
}
And use the class like this in your main
ConstructorClass c = new ConstructorClass("John",85)
c.printNameAndNumber();
Also some people like to handle this by going through hoops and loops and overriding ToString, but that is being too overzealous and there is really no benefit in your case (or any other primitive case).

public ConstructorClass(String name, int number) {
this.name = name;
this.number = number;
System.out.println(name + "," + number);
}

If you want to properly print out those values, you should have getter methods set in your methods
Example below
public String getName(){
return name;
}
public int getNumber(){
return number;
}
Then to print those values, you should then use methods toString() and method print() to display your values
Example
public String toString(){
return getName() + " " + getNumber();
}
public void print(){
System.out.println(toString());
}
Then in the class with the main method, you call your print method for that specific class
Example
ConstructorClass emp1 = new ConstructorClass("Kevin",20);
emp1.print();
Hope this helped, Enjoy :)

Related

Static Method addStudents

So I need help with this part of JAVA in my COP class OOP programming.
First is that I need to change the addStudent to static method but the code will not run because the this.student is not static which makes no sense because it already private static
import java.util.Arrays;
public class InitializerDemo {
public static final int MAX_STUDENTS = 10;
private static Student[] students;
private Instructor instructor;
private static int numStudents = 0;
// default constructor
public InitializerDemo() {
}
// instructor mutator
public void setInstructor(Instructor instructor) {
this.instructor = instructor;
}
// add a student, increment the count
//This PART!!! HELP
public static void addStudent(Student s) {
this.students[numStudents++] = s;
}
public static void main(String[] args) {
// create our aggregator object
InitializerDemo id = new InitializerDemo();
// set the instructor
id.setInstructor(new Instructor("Sally"));
// add the students
id.addStudent(new Student("Sam"));
id.addStudent(new Student("Rajiv"));
id.addStudent(new Student("Jennifer"));
id.addStudent(new Student("Test Student"));
// output
System.out.println(id);
}
public String toString() {
String s = "Instructor = " + instructor + "\n" +
"Number of students = " + numStudents + "\n" +
"Students: " + Arrays.toString(students) + "\n";
return s;
}
}
class Student {
private String name;
// instance initializer block
{
name = "noname";
}
public Student() {
}
public Student(String name) {
this.name = name;
}
public String toString() { return name; }
}
class Instructor {
private String name;
// instance initializer block
{
name = "noname";
}
public Instructor() {
}
public Instructor(String name) {
this.name = name;
}
public String toString() { return name; }
}
I need help with that addStudent Method
These are the instructions and sorry to confuse all you guys and thank you for putting time to help me
change the instance variables representing the number of students and the Student array in the aggregator object to private static variables.
• change the addStudent method in the aggregator object from an instance method to a static method
• Remove all initialization/instantiation operations from the aggregator object’s default constructor; the constructor can simple be an empty method { }
• provide a static initializer block in the aggregator object which does the following:
o initializes the number of students to 0
o instantiates the student array
o adds a single student named “Test Student” to the array using the addStudent method
Change
this.students[numStudents++] = s;
to
students[numStudents++] = s;.
I believe that should work.
You also have to initialize the students, so change
private static Student[] students;
to
private static Student[] students = new Student[MAX_STUDENTS];

How do you update/change a instance variable in Java? (Beginner Level)

I am new to java, and I am trying to create a method to update the instance variable age for my objects. I am getting the code to compile, but I am seeing no change in the age value. This code is part of an assignment, so I cannot change the constructors. The method I wrote to update the age (that doesn't work) is shown below. My entire code is shown below that. I am also curious if there's a way to update/change just one of my objects, but before I do that, I need the method to work for both. Any help writing this method properly would be appreciated!
public void setnewAge(int age) {
dogAge += 1;
this.dogAge = dogAge;
}
Below is my entire code (including the method I wrote to update age).
public class Dog {
//Instance Varibles
private String dogName;
private int dogAge;
private int dogWeight;
//Two Contructors (One Completely Empty)
public Dog() {
}
public Dog(String name, int age, int weight){
dogName = name;
dogAge = age;
dogWeight = weight;
}
//Getters
public String getName() { return dogName;}
public int getAge() { return dogAge;}
public int getWeight() { return dogWeight;}
//Setters
public void setName(String theName) { dogName = theName;}
public void setAge(int theAge) {dogAge = theAge;}
public void setWeight(int theWeight) {dogWeight = theWeight;}
//to(String) method
public String toString() {
return "The dogs's name is " + getName() + ", the dogs's age is " +
getAge() + ", " + "\n" + "the dogs's weight is " + getWeight() + ".";
}
public void setnewAge(int age) {
dogAge += 1;
this.dogAge = dogAge;
}
//Main Method
public static void main(String[] args) {
Dog poodle = new Dog("Bob", 5, 26);
System.out.println(poodle);
Dog lab = new Dog();
lab.setName("Steve");
lab.setAge(8);
lab.setWeight(43);
System.out.println(lab);
}
}
As Tom said, you need to actually call the function in your main function otherwise, there will be no change, and also to refine your code for your setnewAge function, try this:
public void setnewAge() {
this.dogAge = dogAge + 1;
}
Then in the main function call setnewAge() and then print your age to see the results.
Dog poodle = new Dog("Bob", 5, 26);
poodle.setnewAge() ;

How to write a toString method for ArrayList?

I am having a hard time finding out how to write my toString Method to get the output of each of my bears in my program. I want the output to show "Race - Points - TotalPoints". But can't manage to get it right even though the rest of the code seems to compile.
Do i need to have the toString defined in both classes or what am I missing? I have checked a couple of other questions that are resembling and that seems to be an alternativ? But how is it most effectively implemented?
First off the bear class:
import java.util.ArrayList;
public class Bear {
public static void main(String[] args) {
Bear b = new Bear("Sebastian", 100, "Brownbear");
ArrayList <Bear> bears = new ArrayList<Bear>();
bears.add(b);
}
private String name;
private int points;
private String race;
public Bear(String name, int points, String race) {
this.name = name;
this.points = points;
this.race = race;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRace() {
return race;
}
public void setRace(String race) {
this.race = race;
}
public int getInitialPoints() {
return points;
}
public int getPoints() {
int oldPoints = points;
points /= 2;
return oldPoints;
}
}
Secondly the BearCollection class:
import java.util.ArrayList;
public class BearCollection {
ArrayList <Bear> bears = new ArrayList<Bear>();
int totalPoints = 0;
public void add (Bear b) {
for (Bear inCollection : bears) {
if(b.getName().equals(inCollection.getName())) {
return;
}
}
for (Bear inCollection : bears)
if (b.getRace().equals(inCollection.getRace())) {
for(int i = bears.size(); i > 0; i --) {
if(bears.get(i).getRace().equals(b.getRace())) {
b.getPoints();
i = 0;
}
}
}
totalPoints += b.getInitialPoints();
bears.add(b) ;
}
public String toString(){
return ;
}
As you were told, just override the toString method. For performance use StringBuilder, rather than String concatenation.
import java.util.*;
public class ans{
public static void main(String[] args){
Bears bears = new Bears();
bears.add(new Bear());
bears.add(new Bear());
bears.add(new Bear());
System.out.println(bears);
}
}
class Bear{
public String toString(){
return "I am a bear";
}
}
class Bears{
private ArrayList<Bear> bears = new ArrayList<Bear>();
public void add(Bear bear){
bears.add(bear);
}
public String toString(){
StringBuilder str = new StringBuilder();
if(!bears.isEmpty()){ // If there is no bears, return empty string
str.append(bears.get(0)); // Append the first one
for(int index = 1; index < bears.size(); index++){ // For all others
str.append(" - "); // Append a separator and the bear string
str.append(bears.get(index));
}
}
return str.toString();
}
}
Edit To print A-B-C-D, just associate every item with a separator except one. A(-B)(-C)(-D) or (A-)(B-)(C-)D. You could add easily a beginning and a end mark.
overriding the toString in Bear class would resolve the issue.
If you need to print out the entire collection of Bears, you'd need to give Bear a toString, something like:
return "Bear("+name+","+points+","+race+")";
Then, in the toString of BearCollection, just write a for each loop in the toString to go through and call toString on each bear in the collection, printing them out.

How does get method knows what it needs to return

I have a little trouble understanding when can value be returned
For example I will use get and set methods:
In case 1:
Class:
public class Debb {
private String word;
public void setName(String n){
word = n;
}
public String getName(){
return word;
}
public void say(){
System.out.println(getName());
}
}
Main:
public class nebb {
public static void main(String args[]){
String plane = "plane";
Debb temp = new Debb();
temp.setName(plane);
temp.say();
}
}
case 2:
Class:
public class lav {
private String word;
public void setName(){
word = "luka";
}
public String getName(){
return word;
}
public void say(){
System.out.println(getName());
}
}
Main:
public class fav {
public static void main(String args[]){
lav temp = new lav();
temp.say();
}
}
I totally understand what happens with case 2 . getName() does'nt have connection with setName() so it does'nt know what to return and i will get null.
but what about case 1 how method getName() knows that it needs to return value of word from setName().
getName() is returning word and you set it to "plane" with setName().
I totally understand what happens with case 2 . getName() does'nt have
connection with setName() so it does'nt know what to return and i will
get null.
actually you've misunderstood this , getName() is again returning word but in this case since you didn't provide any value for it , it was initialized to the default value of null
The class has a field String word.
private String word;
When you say
public void setName(String n){
word = n;
}
You are saying
public void setName(String n){
this.word = n;
}
And thus your getName is accessing the same field when it calls
public String getName(){
return this.word;
}
In your method setter when you set word to "plane".
public void setName(String n){
word = n;
}
And the value of word come when you go to get it with getter method
public String getName(){
return word;
}
Bacuase you refer to same variable. It's good practice to add key this in the method like this.
public void setName(String n){
this.word = n;
}

How do I print using toString using inheritance in Java

public class StuTest2
{
public static final int NUMBER_OF_STUDENTS = 7;
public static void main(String[] args)
{
Student[] stus = new Student[NUMBER_OF_STUDENTS];
// Student has ID, name, and GPA
stus[0] = new Student(123, "Suzy", 3.9);
// Default for missing GPA will be 9.99 "special value
stus[1] = new Student(234, "Tom");
// Default name will be "Student #xxx" where
// "xxx" is the actual ID number
stus[2] = new Student(456);
// A grad student also has a thesis topic
stus[3] = new GradStudent(567, "Fred", 3.8, "Java");
// Default thesis topic is "Undecided"
stus[4] = new GradStudent(678, "Staci", 3.1);
// Doctoral students earn a stipend
stus[5] = new DoctoralStudent(789, "Mandy", 4.0, "Databases", 3550.00);
// If missing, the default stipend is $3000.00
stus[6] = new DoctoralStudent(890, "Ned", 3.7, "Cisco Networking");
// Inside the loop, the toString method is called for each
// student. All graduate students show the word "Graduate" in
// front of the output from this method.
for(Student stu : stus)
{
}
}
}
class Student
{
private int id;
private String name;
private double gpa;
public Student(int i, String n, double g)
{
id = i;
name = n;
gpa = g;
}
public Student(int i)
{
this(i, "Student #" + i);
}
public Student(int i, String n)
{
this(i, n, 9.99);
}
public int getId()
{
return id;
}
public String getName()
{
return name;
}
public double getGPA()
{
return gpa;
}
public String toString()
{
return System.out.println(stus.getId+", " + stus.getName
+ ", " + stus.getGPA);
}
}
class GradStudent extends Student
{
private String topic;
public GradStudent(int i, String n, double g, String t)
{
super(i, n, g);
topic = t;
}
public GradStudent(int i, String n, double g)
{
this(i, n, g, "Undecided");
}
public String getTopic()
{
return topic;
}
public String toString()
{
return super.getTopic();
}
}
class DoctoralStudent extends GradStudent
{
private double stip;
public DoctoralStudent(int i, String n, double g, String t, double s)
{
super(i, n, g, t);
stip = s;
}
public DoctoralStudent(int i, String n, double g, String t)
{
this(i, n, g, t, 3000.00);
}
public double getStip()
{
return stip;
}
public String toString()
{
return super.getStip();
}
}
I'm trying to print out while using the return super.toString(), but Iget errors saying cannot find symbol for stus, but I have it right before starting the student class. What gives? ps, sorry for the bad closings, trying to meet standards on here lol
Your "stus" variable is only in scope inside the main() method, so you can't access it outside of that method. Furthermore, "stus" is an array, so it doesn't even make sense to call getId on it. Further, notice that getId refers to a variable since it doesn't have parenthesis after it.
Keep in mind that in your toString() method, you're already "inside" a Student Object, so you can just call the getId() function directly:
public String toString()
{
return getId() +", " + getName() + ", " + getGPA();
}
Also note that I've removed the System.out.println() function in your toString method, since it doesn't return anything and therefore doesn't make sense to return anyway.
You've got a lot of incorrect syntax in your code, and I highly recommend starting much smaller. You'll have much better luck if you develop your program incrementally instead of trying to do the whole thing in one shot. I recommend starting over and compiling and testing with every single line you add.

Categories

Resources