(Java begineer) "this" keyword discussion [duplicate] - java

This question already has answers here:
How do I call one constructor from another in Java?
(22 answers)
Closed 3 years ago.
I know the meaning for "this" keyword.. we use it to reference instance variables if we have a method arguments that has the same name as instance variables but in this code i don't understand why we use it.. what does " this( 0, 0, 0 ) " even mean? we can just put arguments inside the instructors. Can someone please explain?
public class Time2
{
private int hour; // 0 - 23
private int minute; // 0 - 59
private int second; // 0 - 59
// Time2 no-argument constructor: initializes each instance variable
// to zero; ensures that Time2 objects start in a consistent state
public Time2()
{
this( 0, 0, 0 ); // invoke Time2 constructor with three arguments
} // end Time2 no-argument constructor
// Time2 constructor: hour supplied, minute and second defaulted to 0
public Time2( int h )
{
this ( h, 0, 0 ); // invoke Time2 constructor with three arguments
} // end Time2 one-argument constructor
// Time2 constructor: hour and minute supplied, second defaulted to 0
public Time2( int h, int m )
{
this( h, m, 0 ); // invoke Time2 constructor with three arguments
} // end Time2 two-argument constructor
// Time2 constructor: hour, minute and second supplied
public Time2( int h, int m, int s )
{
setTime( h, m, s ); // invoke setTime to validate time
} // end Time2 three-argument constructor
// Time2 constructor: another Time2 object supplied
public Time2( Time2 time )
{
// invoke Time2 three-argument constructor
this( time.getHour(), time.getMinute(), time.getSecond() );
} // end Time2 constructor with a Time2 object argument
// Set Methods
// set a new time value using universal time; ensure that
// the data remains consistent by setting invalid values to zero
public void setTime( int h, int m, int s )
{
setHour( h ); // set the hour
setMinute( m ); // set the minute
setSecond( s ); // set the second
} // end method setTime
// validate and set hour
public void setHour( int h )
{
hour = ( ( h >= 0 && h < 24 ) ? h : 0 );
} // end method setHour
// validate and set minute
public void setMinute( int m )
{
minute = ( ( m >= 0 && m < 60 ) ? m : 0 );
} // end method setMinute
public void setSecond( int s )
{
second = ( ( s >= 0 && s < 60 ) ? s : 0 );
} // end method setSecond
// Get Methods
// get hour value
public int getHour()
{
return hour;
} // end method getHour
// get minute value
public int getMinute()
{
return minute;
} // end method getMinute
// get second value
public int getSecond()
{
return second;
} // end method getSecond
// convert to String in universal-time format (HH:MM:SS)
public String toUniversalString()
{
return String.format(
"%02d:%02d:%02d", getHour(), getMinute(), getSecond() );
} // end method toUniversalString
// convert to String in standard-time format (H:MM:SS AM or PM)
public String toString()
{
return String.format( "%d:%02d:%02d %s",
( (getHour() == 0 || getHour() == 12) ? 12 : getHour() % 12 ),
getMinute(), getSecond(), ( getHour() < 12 ? "AM" : "PM" ) );
} // end method toString
} // end class Time2ere

this( 0, 0, 0 ) call an other constructor with 3 parameters
so
public Time2()
{
this( 0, 0, 0 ); // invoke Time2 constructor with three arguments
} // end Time2 no-argument constructor
calls:
public Time2( int h, int m, int s )
{
setTime( h, m, s ); // invoke setTime to validate time
} // end Time2 three-argument constructor
with h,m,s = 0

You are simply calling the constructor from within itself.
Let's imagine we have a class Ball:
public class Ball {
private Color color;
private int size;
// This is our constructor
public Ball(Color c, int s) {
this.color = c;
this.size = s;
}
}
Now, if we wanted to create a new red ball with size 4, we could do so with new Ball(Color.RED, 4);
this refers to the current object. So if we are within Ball and creating a new Ball, we would do this(Color.RED, 4);.
This is effectively like saying new Ball();.

Related

Attempting to add an increment method to a time class

I am attempting to add an increment method for a time class I have. I have modified the original code to only have one private integer "totalseconds" that reads the amount of seconds since midnight. That part of the code works fine but now I am trying to create a method that increments the setSecond, setMinute, and setHour. The problem (I believe) I am having is that these set methods all receive their values from totalseconds not int hour, int minute, int second as before. When I run the test for it the way I have it now I get errors at lines 36, 75 (when attempted to increment seconds via Tick method) and 101 (again only when incrementing seconds via Tick method). I have attached both the Time2 class and Time2Test app for reference.
public class Time2 {
private int totalseconds;
//no argument constructor
public Time2()
{
this(0,0,0); //invoke constructor with three arguments default to 0
}
//constructor with hour supplied minute and second default to 0
public Time2(int hour)
{
this(hour, 0, 0); //invoke constructor with 3 args
}
//constructor with hour and minute supplied seconds default to 0
public Time2(int hour, int minute)
{
this(hour, minute, 0); //invoke constructor with 3 args
}
//Time2 constructor with hour minute and second supplied also tests
public Time2(int hour, int minute, int second)
{
this.totalseconds = (hour * 3600);
this.totalseconds += (minute * 60);
this.totalseconds += (second);
}
public Time2(Time2 time)
{
//invoke constructor with 2 args
this(time.getHour(), time.getMinute(), time.getSecond());
}
// SET and GET methods start here, also Universal time conversion and check
public void setTime(int hour, int minute, int second)
{
if (hour < 0 || hour >= 24)
throw new IllegalArgumentException("Hour must be 0-23");
if (minute < 0 || minute >= 59)
throw new IllegalArgumentException("Minute must be 0-59");
if (second < 0 || second >= 59)
throw new IllegalArgumentException("Hour must be 0-59");
this.totalseconds = (hour * 3600);
this.totalseconds += (minute * 60);
this.totalseconds += second;
}
//validate and set hour
public void setHour(int hour)
{
if (hour < 0 || hour >= 23)
throw new IllegalArgumentException("Hour must be 0-23");
this.totalseconds = (hour * 3600);
}
//validate and set minute
public void setMinute(int minute)
{
if (minute < 0 || minute >= 59)
throw new IllegalArgumentException("Minute must be 0-59");
this.totalseconds += (minute * 60);
}
//validate and set second
public void setSecond(int second)
{
if (second < 0 || second >= 59)
throw new IllegalArgumentException("Second must be 0-59");
this.totalseconds += second;
}
//Get Methods start here
//Get hour
public int getHour()
{
return totalseconds / 3600;
}
//get minute
public int getMinute()
{
return (totalseconds - (3600 * getHour())) / 60;
}
//get second
public int getSecond()
{
return totalseconds - (3600 * getHour())- (60 * getMinute());
}
//Assignment 1-2 tick methods start here.
public void Tick()
{
setSecond(totalseconds ++);
if (totalseconds >= 59) incrementMinute();
}
public void incrementMinute()
{
setMinute( totalseconds ++);
if ( totalseconds >= 59) incrementHour();
}
public void incrementHour()
{
setHour ( this.totalseconds ++);
}
//convert our string to universal format (HH:MM:SS)
public String ToUniversalString()
{
return String.format(
"%02d:%02d:%02d", getHour(), getMinute(), getSecond());
}
//conver to standard format (H:MM:SS AM or PM)
public String toString()
{
return String.format("%d:%02d:%02d %s",((getHour() == 0 || getHour() ==
12) ? 12 : getHour() % 12), getMinute(), getSecond(), (getHour()
< 12 ? "AM" : "PM"));
}
}//end class Time2
public class Time2Test
{
public static void main(String[] args)
{
Time2 t1 = new Time2(); //00:00:00
Time2 t2 = new Time2(2); //02:00:00
Time2 t3 = new Time2(21, 34); //21:34:00
Time2 t4 = new Time2(12, 25, 42); //12:25:42
Time2 t5 = new Time2(t4); //12:25:42
System.out.println("Constructed with:");
displayTime("t1: all default arguments", t1);
displayTime("t2: hour specified; defaults for minute and second", t2);
displayTime("t3: hour and minute supplied second defaulted", t3);
displayTime("t4: hour minute and second supplied", t4);
displayTime("t5: Time2 object t4 specified", t5);
//attempt to initialize t6 with invalid args
try
{
Time2 t6 = new Time2(27,74,99); //all invalid values
}
catch (IllegalArgumentException e)
{
System.out.printf("%nException while initializing t6: %s%n",
e.getMessage());
}
System.out.println("Time before increment minute method");
System.out.printf("%s\n", t4.toString());
t4.Tick();
t4.incrementMinute();
t4.incrementHour();
System.out.println("Time after increment minute method");
System.out.printf("%s\n", t4.toString());
}
//display Time2 object in 24 hour and 12 hour formats
private static void displayTime(String header, Time2 t)
{
System.out.printf("%s%n %s%n %s%n", header, t.ToUniversalString(),
t.toString());
}
}

Create a toString() method that returns the value as a formatted time String

Im at the last few steps in my homework and need some help understanding/doing the last two steps. The last two things I have to do are:
Create a toString() method that returns the value as a formatted time String. Remember that values less than 10 must be padded with zeroes. For example, midnight will look like this returned from getMilitaryTime(): 00:00:00. Use the String zeroPad(int) method to pad the numbers - see the code below. Use a StringBuffer object to build the String in the toString() method, calling zeroPad(int) as necessary.
Create a main method and construct the following times and print the time using System.out.println(clock):
Call the default constructor (no parameters)
hour: 0, minute: 94, second: 56
hour: 14, minute: 63, second: 64
hour: 98, minute: 76, second: -64
hour: 5, minute: 8, second: 1
hour: 23, minute: 59, second: 59
under just the println at the end I get the error :Syntax error on token "println", = expected after this token. I'm not sure if fixing this will help me move onto the next steps or not. Is what I have for the most part correct when it come to making the toString method?
So Far this is what I have:
//Create a new class called Clock
public class Clock {
public static void main(String[] args){
}
//Create three integer attributes for hour, minute and second.
//Always store the hour in military time.
private double MilitaryHour;
private double Minute;
private double Second;
// Create setters for the hour, minute and second values.
public double getMilitaryHour() {
return MilitaryHour;
}
public void setMilitaryHour(double militaryHour) {
if(militaryHour < 0 || militaryHour > 23)
this.MilitaryHour = (militaryHour % 24);
this.MilitaryHour = militaryHour;
}
public double getMinute() {
return Minute;
}
public void setMinute(double minute) {
if(minute < 0 || minute > 59)
this.Minute = (minute % 60);
this.Minute = minute;
}
public double getSecond() {
return Second;
}
public void setSecond(double second) {
if(second < 0 || second > 59)
this.Second = (second % 60);
this.Second = second;
}
public Clock(double MilitaryHour,double Minute,double Second) {
this.MilitaryHour = MilitaryHour;
this.Minute = Minute;
this.Second = Second;
}
/default
public Clock(){
this(0.0, 0.0, 0.0);
}
public String toString()
{
String result = "Hour: " + getMilitaryHour()+"Minute: " + getMinute()+ "Seconds:" + getSecond();
return result;
}
System.out.println("" + result.toString());
}
A quick look shows me that your implementation contains many errors.
Your statement System.out.println("" + result.toString()); is not placed correctly. It should be place inside a function, may be inside your main function.
The result.toString() doesn't make sense. With what I understood from your problem, you need to create a Clock object like this:
Clock clock = new Clock(1, 1, 1);
Then,
System.out.println(clock.toString());
To print the object. Like this:
public static void main(String[] args){
Clock clock = new Clock(1, 1, 1);
System.out.println(clock.toString());
}
I am not sure if this would be enough, but this should fix some of your issues.

Beginner Java: How do I write a constructor to call methods?

I am trying to figure out how to write a constructor that calls methods. I have been given the following instructions for a Java project. The emboldened ones are relevant to this step. Step 3 I have completed, but I can't confirm if I completed it correctly. The code for Step 3 is the second Date constructor within the Date class.
Uncomment line 1 from DateTest (don’t forget to delete the “Line 1.” part) and build and run the project. What is the output? Why is this the output?
Create a default constructor for Date which sets the date to 1/1/2000. Build and run the project. What is the output?
Create a constructor that has three int parameters for the month, day, and year and sets the values of these instance variables to the values passed in. Uncomment lines 2 and 3. Build and run the project. What is the output?
Rewrite the constructor from question 3 so that it calls setMonth(), setDay(), and setYear(). Build and run the project. What is the output?
Write a set() method that has three parameters for the month, day, and year. Uncomment lines 4 and 5. Build and run the project. What is the output?
Rewrite the constructor from question 3 so that it calls set (). Build and run the project. What is the output?
Below is the code for Date class and DateTest class.
package datetest;
import java.util.Scanner;
public class Date
{
public Date() {
month = 1;
day = 1;
year = 2000;
}
public Date(int m, int d, int y) {
month = m;
day = d;
year = y;
}
private int month;
private int day;
private int year; //a four digit number.
public void setYear(int newYear)
{
year = newYear;
}
public void setMonth(int newMonth)
{
if ((newMonth <= 0) || (newMonth > 12))
{
month=newMonth;
}
else
month = newMonth;
}
public void setDay(int newDay)
{
if ((newDay <= 0) || (newDay > 31))
{
day=1;
}
else
day = newDay;
}
public int getMonth( )
{
return month;
}
public int getDay( )
{
return day;
}
public int getYear( )
{
return year;
}
public void printDate( )
{
System.out.print(getMonth() + "/" + getDay() + "/" + getYear());
}
public void readInput( )
{
boolean tryAgain = true;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter month, day, and year.");
System.out.println("Do not use a comma.");
month = keyboard.nextInt( );
day = keyboard.nextInt( );
year = keyboard.nextInt( );
}
}
This is the DateTest class.
package datetest;
public class DateTest {
public static void main(String[] args) {
Date today = new Date();
System.out.println("Today’s date is " + today.getMonth() + "/" + today.getDay() + "/" + today.getYear());
//Line 2. today = new Date(55, 55, 2011);
//Line 3. System.out.println("Today’s date is " + today.getMonth() + "/" + today.getDay() + "/" + today.getYear());
//Line 4. today.set(10, 5, 2011);
//Line 5. System.out.println("Today’s date is " + today.getMonth() + "/" + today.getDay() + "/" + today.getYear());
}
}
I have attempted to write the code to call the methods in step 4. Would the following code be the correct way to write a constructor to call methods?
public Date (int m, int d, int y) {
this.setMonth(month);
this.setDay(day);
this.setYear(year);
}
Would the following code be the correct way to write a constructor to call methods?
public Date (int m, int d, int y) {
this.setMonth(month);
this.setDay(day);
this.setYear(year);
}
Yes, if you used your m, d, and y arguments instead of month, day, and year:
public Date (int m, int d, int y) {
this.setMonth(m);
this.setDay(d);
this.setYear(y);
}
With your code, you're actually just setting the instance members (month and so on) to their existing values (because month in the constructor is automatically resolved to the instance data member month using an implied this.). So I'm guessing when you tried it, you ended up with zeroes and didn't understand why. (int members are auto-initialized to zero before the code in the constructor runs.)

Need help incrementing the getHour Method

I am currently trying to increment my code to add a second and if the second changes the hour and minute, it will be reflected. here is my current code. I know the issue that I am having lies in the get hour method because it is the only one that isn't incrementing. Thank you for the help.
public class Time2
{
private int hour; // 0 - 23
private int minute; // 0 - 59
private int second; // 0 - 59
private int seconds;
// Time2 no-argument constructor: initializes each instance variable
// to zero; ensures that Time2 objects start in a consistent state
public Time2()
{
this( 0, 0, 0 ); // invoke Time2 constructor with three arguments
} // end Time2 no-argument constructor
// Time2 constructor: hour supplied, minute and second defaulted to 0
public Time2( int h )
{
this( h, 0, 0 ); // invoke Time2 constructor with three arguments
} // end Time2 one-argument constructor
// Time2 constructor: hour and minute supplied, second defaulted to 0
public Time2( int h, int m )
{
this( h, m, 0 ); // invoke Time2 constructor with three arguments
} // end Time2 two-argument constructor
// Time2 constructor: hour, minute and second supplied
public Time2( int h, int m, int s )
{
setTime( h, m, s ); // invoke setTime to validate time
} // end Time2 three-argument constructor
// Time2 constructor: another Time2 object supplied
public Time2( Time2 time )
{
// invoke Time2 three-argument constructor
this( time.getHour(), time.getMinute(), time.getSecond() );
} // end Time2 constructor with a Time2 object argument
// Set Methods
// set a new time value using universal time; ensure that
// the data remains consistent by setting invalid values to zero
public void setTime( int h, int m, int s )
{
setHour( h ); // set the hour
setMinute( m ); // set the minute
setSecond( s ); // set the second
} // end method setTime
// validate and set hour
public void setHour( int h )
{
hour = ( ( h >= 0 && h < 24 ) ? h : 0 );
} // end method setHour
// validate and set minute
public void setMinute( int m )
{
minute = ( ( m >= 0 && m < 60 ) ? m : 0 );
} // end method setMinute
// validate and set second
public void setSecond( int s )
{
second = ( ( s >= 0 && s < 60 ) ? s : 0 );
} // end method setSecond
// Get Methods
// get hour value
public int getHour()
{
if(minute > 59)
{
hour++;
}
return hour;
} // end method getHour
// get minute value
public int getMinute()
{
if(second > 59)
{
minute++;
}
if(minute > 59)
{
minute = 00;
}
return minute;
} // end method getMinute
// get second value
public int getSecond()
{
if(second > 59)
{
second = 00;
}
return second++;
} // end method getSecond
// convert to String in universal-time format (HH:MM:SS)
public String toUniversalString()
{
return String.format(
"%02d:%02d:%02d", getHour(), getMinute(), getSecond() );
} // end method toUniversalString
// convert to String in standard-time format (H:MM:SS AM or PM)
public String toString()
{
return String.format( "%d:%02d:%02d %s",
( (getHour() == 0 || getHour() == 12) ? 12 : getHour() % 12 ),
getMinute(), getSecond(), ( getHour() < 12 ? "AM" : "PM" ) );
} // end method toString
} // end class Time2
The results that I am getting from my test app are:
public class Time2Test
{
public static void main(String[] args)
{
Time2 t1 = new Time2(); // 00:00:00
Time2 t2 = new Time2(2); // 02:00:00
Time2 t3 = new Time2(21, 34); // 21:34:00
Time2 t4 = new Time2(12, 59, 59); // 12:25:42
Time2 t5 = new Time2(t4); // 12:25:42
System.out.println("Constructed with:");
displayTime("t1: all default arguments", t1);
displayTime("t2: hour specified; default minute and second", t2);
displayTime("t3: hour and minute specified; default second", t3);
displayTime("t4: hour, minute and second specified", t4);
displayTime("t5: Time2 object t4 specified", t5);
// attempt to initialize t6 with invalid values
try
{
Time2 t6 = new Time2(27, 74, 99); // invalid values
}
catch (IllegalArgumentException e)
{
System.out.printf("%nException while initializing t6: %s%n",
e.getMessage());
}
}
// displays a Time2 object in 24-hour and 12-hour formats
private static void displayTime(String header, Time2 t)
{
System.out.printf("%s%n %s%n %s%n",
header, t.toUniversalString(), t.toString());
}
} // end class Time2Test
Output:
Constructed with:
t1: all default arguments
00:00:00
12:00:01 AM
t2: hour specified; default minute and second
02:00:00
2:00:01 AM
t3: hour and minute specified; default second
21:34:00
9:34:01 PM
t4: hour, minute and second specified
12:00:00
12:00:01 PM
t5: Time2 object t4 specified
12:59:59
12:00:00 PM
In this piece of code:
getMinute(), getSecond(), ( getHour() < 12 ? "AM" : "PM" )
If minute is greater than 59, the getMinute method will change minute to 0. Then when getHour is called, minute is 0, so hour isn't incremented.
As others have stated, do not modify variables in getters. It causes all kinds of havoc.

Understanding this recursive method

We are learning recursion in my intro to Java class, and I am having a hard time understanding how the method in the example given works. What is happening when the method is called?.
Here is the code:
public class Hanoi
private int n;
private int pegA;
private int pegB;
public Hanoi(int in_n, int in_pegA, int in_pegB)
{
n = in_n;
pegA = in_pegA;
pegB = in_pegB;
}
public void makemoves()
{
if (n==1)
System.out.format("%d ==> %d%n", pegA, pegB)
else
{
int otherPeg = 6 - pegA - pegB; // 1 + 2 + 3 =6
Hanoi firstmove = new Hanoi (n-1, pegA, otherPeg);
firstmove.makemoves();
System.out.format("%d ==> %d%n", pegA, pegB);
Hanoi secondmove = new Hanoi (n-1, otherPeg, pegB);
secondmove.makemoves();
}
}
}
Recursion is simply a method calling itself, and testing for a break condition.
This is an very easy example to illustrate the basic concept:
static void recurse( int val ) {
if ( val == 0 ) {
return; // returns from last invocation
}
System.out.println("val=" + val );
recurse( val - 1 );
return; // here the method returns to previous invocation (or initial call from main)
}
public static void main( String[] args) {
recurse( 3 );
}
The first invocation recurse( 3 ) calls the method,
after testing that 3 != 0 the method calls itself with val - 1 until the value becomes 0.
The call hierachy looks like:
recurse( 3 )
recurse( 2 )
recurse( 1 )
recurse( 0 ) // break condition
return // val == 0
return // val == 1
return // val == 2
return // val == 3
How this work is simply by traverse a binary tree in order. Check the wiki.

Categories

Resources