-Im struggling to understand printing objects to values -I will supply the main
ID: 670201 • Letter: #
Question
-Im struggling to understand printing objects to values
-I will supply the main method and classes that i will need help with.
-In the following code I want it to print out the values which are stored in the object reference of "mytest".
currently it is only printing out the values stored in the object "testing".. I would like to know with the following code how the output can be "2,3,5".... with this code statement System.out.printf("The 3 numbers are %s%n",mytest.getNumbers());
-would you also please explain the concepts behind this and point me int he right direction on any reading i can find in textsbooks, and any youtube videos.. thanks
----------------------------------------------------------------
public static void main(String[] args)
{
class2 testing = new class2(3,5);
class1 mytest = new class1(2,testing);
System.out.printf("The 3 numbers are %s%n",mytest.getNumbers());
}
---------------------------------------------------------
public class class1 {
double num3;
class2 numbers;
public class1(double mynum, class2 mynum2) {
this.num3 = mynum;
double t1 = mynum2.get1();
double t2 = mynum2.get2();
this.numbers = new class2(t1, t2);
}
public class2 getNumbers() {
return numbers;
}
double getnum3()
{
return num3;
}
@Override
public String toString() {
String myString;
myString = String.format(" %d: %d, %d", num3, numbers.num1, numbers.num2);
return myString;
}
-------------------------
public class class2
{
double num1;
double num2;
public class2(double num1,double num2)
{
this.num1 = num1;
this.num2 = num2;
}
public double get1()
{
return num1;
}
public double get2()
{
return num2;
}
public String toString()
{
return "" +get1() + " , " + get2() ;number
}
Explanation / Answer
your output is 3, 5 only because when you print object it is called your override toString() method written in class 2 and where you are only printing num1 and num2, thats why only 2 values is coming
Use below code :
public class class1 {
double num3;
class2 numbers;
public class1(double mynum, class2 mynum2) {
this.num3 = mynum;
double t1 = mynum2.get1();
double t2 = mynum2.get2();
this.numbers = new class2(t1, t2);
}
class2 getNumbers() {
return numbers;
}
double getnum3()
{
return num3;
}
public static void main(String[] args)
{
class2 testing = new class2(3,5);
class1 mytest = new class1(2,testing);
System.out.println("The 3 numbers are"+ mytest.getnum3());
System.out.println(mytest.getNumbers());
}
}
class class2
{
double num1;
double num2;
public class2(double num1,double num2)
{
this.num1 = num1;
this.num2 = num2;
}
public double get1()
{
return num1;
}
public double get2()
{
return num2;
}
public String toString() {
System.out.println(num1+" "+num2);
return "";
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.