public static boolean isValidDate(int month, int day) {
if (month >= 3 && month <= 5) {
if (month == 3) {
if (day >= 1 && day <= 31) {
return true;
} else {
return false;
}
} else if (month == 4) {
if (day >= 1 && day <= 30) {
return true;
} else {
return false;
}
} else if (month == 5) {
if (day >= 1 && day <= 15) {
return true;
} else {
return false;
}
}
} else {
return false;
}
}
Get these errors:not sure how to fix them im returning everything.
BoxOffice.java:81: error: missing return statement
}
BoxOffice.java:85: error: missing return statement
}
The compiler isn't smart enough to deduce that the inner if covers every scenario in the range of the outer if. Just change
else if(month == 5) {
to
else { // month must be 5 here
shmosel's answer describes the problem and the least disruptive fix.
Personally, I'd write this as a switch, and avoid writing the long if/else statements to check the day:
switch (month) {
case 3:
return (day >= 1 && day <= 31);
case 4:
return (day >= 1 && day <= 30);
case 5:
return (day >= 1 && day <= 15);
default:
return false;
}
you need to transforme the else if (month == 5) to else ....
public static boolean isValidDate(int month, int day)
{
if (month >= 3 && month <= 5)
{
if (month == 3)
{
if (day >= 1 && day <= 31)
{
return true;
}
else
{
return false;
}
}
else if (month == 4)
{
if (day >= 1 && day <= 30)
{
return true;
}
else
{
return false;
}
}
else
{
if (day >= 1 && day <= 15)
{
return true;
}
else
{
return false;
}
}
}
else
{
return false;
}
}
Try making a boolean, and instead of returning in the if statement, change the boolean and return at the end of the method. Here is an example with your code.
public static boolean isValidDate (int month, int day) {
boolean result = true; //This must be set to a value to avoid compiler errors
if(month >= 3 && month <= 5) {
if(month == 3) {
if(day >= 1 && day <= 31) {
result = true;
}
else {
result = false;
}
}
else if(month == 4) {
if(day >= 1 && day <= 30) {
result = true;
}
else {
result = false;
}
}
else if(month == 5) {
if(day >= 1 && day <= 15) {
result = true;
}
else {
result = false;
}
}
}
else {
result = false;
}
return result;
}
Hope that helps!
How could I optimize having a lot of switch cases? Is there some other method to do what I'm attempting to do?
I have a time slider and this slider updates a variable currentTime with the value (1-24) where the current slider is and calls the updateTime() method. In this method I have switch cases for 1 - 24 (only 3 in this example). Instead of making 24 switch cases, could I do this in a much simpler way?
private void updateTime() {
switch (currentTime) {
case 1:
hourlyData = weatherAPI.HourlyReport(1);
setHourlyData();
break;
case 2:
hourlyData = weatherAPI.HourlyReport(2);
setHourlyData();
break;
...
case 24:
hourlyData = weatherAPI.HourlyReport(24);
setHourlyData();
break;
default:
System.out.println("Oops");
break;
}
}
--
public Map HourlyReport(int hour) {
Hourly hourly = new Hourly(fio);
//In case there is no hourly data available
if (hourly.hours() < 0) {
System.out.println("No hourly data.");
} else {
hourlyData.put("Temp", hourly.getHour(hour).temperature()); // Temperature
hourlyData.put("TempFeel", hourly.getHour(hour).apparentTemperature()); // Feel Temperature
hourlyData.put("Humidity", hourly.getHour(hour).humidity()); // Humidity
hourlyData.put("WindSpeed", hourly.getHour(hour).windSpeed()); // Wind Speed
hourlyData.put("Precip", hourly.getHour(hour).precipProbability()); // Precipitation
hourlyData.put("TimeStamp", hourly.getHour(hour).time());// TimeStamp
}
return hourlyData;
}
The use of a switch is not justified in this case. Use a simple if
if (currentTime > 0 && currentTime < 25) {
hourlyData = weatherAPI.HourlyReport(currentTime);
setHourlyData();
} else {
System.out.println("Oops");
}
I would validate first
private void updateTime() {
if (currentTime < 1 || currentTime > 24)
throw new IllegalStateException("currentTime: " + currentTime);
hourlyData = weatherAPI.HourlyReport(currentTime);
setHourlyData();
}
You could use a simple if statement to validate currentTime's value and just pass it to weatherAPI.HourlyReport:
private void updateTime() {
if (currentTime >= 1 || currentTime <= 24) {
hourlyData = weatherAPI.HourlyReport(currentTime);
setHourlyData();
} else{
System.out.println("Oops");
}
}
private boolean isValidHour(){
if (currentTime >= 1 && currentTime <= 24)
return true;
else
return false;
}
private void updateTime() {
if(this.isValidHour())
hourlyData = weatherAPI.HourlyReport(currentTime);
else
System.out.println("Oops");
}
What i am trying to do::
Show message based on
Good morning (12am-12pm)
Good after noon (12pm -4pm)
Good evening (4pm to 9pm)
Good night ( 9pm to 6am)
CODE::
I used 24-hr format to get this logic
private void getTimeFromAndroid() {
Date dt = new Date();
int hours = dt.getHours();
int min = dt.getMinutes();
if(hours>=1 || hours<=12){
Toast.makeText(this, "Good Morning", Toast.LENGTH_SHORT).show();
}else if(hours>=12 || hours<=16){
Toast.makeText(this, "Good Afternoon", Toast.LENGTH_SHORT).show();
}else if(hours>=16 || hours<=21){
Toast.makeText(this, "Good Evening", Toast.LENGTH_SHORT).show();
}else if(hours>=21 || hours<=24){
Toast.makeText(this, "Good Night", Toast.LENGTH_SHORT).show();
}
}
Question:
Is this this best way of doing it, If no which is the best way
You should be doing something like:
Calendar c = Calendar.getInstance();
int timeOfDay = c.get(Calendar.HOUR_OF_DAY);
if(timeOfDay >= 0 && timeOfDay < 12){
Toast.makeText(this, "Good Morning", Toast.LENGTH_SHORT).show();
}else if(timeOfDay >= 12 && timeOfDay < 16){
Toast.makeText(this, "Good Afternoon", Toast.LENGTH_SHORT).show();
}else if(timeOfDay >= 16 && timeOfDay < 21){
Toast.makeText(this, "Good Evening", Toast.LENGTH_SHORT).show();
}else if(timeOfDay >= 21 && timeOfDay < 24){
Toast.makeText(this, "Good Night", Toast.LENGTH_SHORT).show();
}
For anyone who is looking for the latest Kotlin syntax for #SMA's answer, here is the helper function :
fun getGreetingMessage():String{
val c = Calendar.getInstance()
val timeOfDay = c.get(Calendar.HOUR_OF_DAY)
return when (timeOfDay) {
in 0..11 -> "Good Morning"
in 12..15 -> "Good Afternoon"
in 16..20 -> "Good Evening"
in 21..23 -> "Good Night"
else -> "Hello"
}
}
I would shorten your if/elseif statement to:
String greeting = null;
if(hours>=1 && hours<=12){
greeting = "Good Morning";
} else if(hours>=12 && hours<=16){
greeting = "Good Afternoon";
} else if(hours>=16 && hours<=21){
greeting = "Good Evening";
} else if(hours>=21 && hours<=24){
greeting = "Good Night";
}
Toast.makeText(this, greeting, Toast.LENGTH_SHORT).show();
java.time
I would advise to use Java 8 LocalTime.
Maybe create a class like this to handle your time of day problem.
public class GreetingMaker { // think of a better name then this.
private static final LocalTime MORNING = LocalTime.of(0, 0, 0);
private static final LocalTime AFTER_NOON = LocalTime.of(12, 0, 0);
private static final LocalTime EVENING = LocalTime.of(16, 0, 0);
private static final LocalTime NIGHT = LocalTime.of(21, 0, 0);
private LocalTime now;
public GreetingMaker(LocalTime now) {
this.now = now;
}
public void printTimeOfDay() { // or return String in your case
if (between(MORNING, AFTER_NOON)) {
System.out.println("Good Morning");
} else if (between(AFTER_NOON, EVENING)) {
System.out.println("Good Afternoon");
} else if (between(EVENING, NIGHT)) {
System.out.println("Good Evening");
} else {
System.out.println("Good Night");
}
}
private boolean between(LocalTime start, LocalTime end) {
return (!now.isBefore(start)) && now.isBefore(end);
}
}
try this code(get hours and get minute methods in Date class are deprecated.)
private void getTimeFromAndroid() {
Date dt = new Date();
Calendar c = Calendar.getInstance();
c.setTime(dt);
int hours = c.get(Calendar.HOUR_OF_DAY);
int min = c.get(Calendar.MINUTE);
if(hours>=1 && hours<=12){
Toast.makeText(this, "Good Morning", Toast.LENGTH_SHORT).show();
}else if(hours>=12 && hours<=16){
Toast.makeText(this, "Good Afternoon", Toast.LENGTH_SHORT).show();
}else if(hours>=16 && hours<=21){
Toast.makeText(this, "Good Evening", Toast.LENGTH_SHORT).show();
}else if(hours>=21 && hours<=24){
Toast.makeText(this, "Good Night", Toast.LENGTH_SHORT).show();
}
}
You determine if it is in the first interval, and then all other intervals depends on the upper limit. So you can make it even shorter:
String greeting = null;
if(hours>=1 && hours<=11){
greeting = "Good Morning";
} else if(hours<=15){
greeting = "Good Afternoon";
} else if(hours<=20){
greeting = "Good Evening";
} else if(hours<=24){
greeting = "Good Night";
}
Toast.makeText(this, greeting, Toast.LENGTH_SHORT).show();
Using Time4J (or Time4A on Android) enables following solutions which do not need any if-else-statements:
ChronoFormatter<PlainTime> parser =
ChronoFormatter.ofTimePattern("hh:mm a", PatternType.CLDR, Locale.ENGLISH);
PlainTime time = parser.parse("10:05 AM");
Map<PlainTime, String> table = new HashMap<>();
table.put(PlainTime.of(1), "Good Morning");
table.put(PlainTime.of(12), "Good Afternoon");
table.put(PlainTime.of(16), "Good Evening");
table.put(PlainTime.of(21), "Good Night");
ChronoFormatter<PlainTime> customPrinter=
ChronoFormatter
.setUp(PlainTime.axis(), Locale.ENGLISH)
.addDayPeriod(table)
.build();
System.out.println(customPrinter.format(time)); // Good Morning
There is also another pattern-based way to let the locale decide in a standard way based on CLDR-data how to format the clock time:
ChronoFormatter<PlainTime> parser =
ChronoFormatter.ofTimePattern("hh:mm a", PatternType.CLDR, Locale.ENGLISH);
PlainTime time = parser.parse("10:05 AM");
ChronoFormatter<PlainTime> printer1 =
ChronoFormatter.ofTimePattern("hh:mm B", PatternType.CLDR, Locale.ENGLISH);
System.out.println(printer1.format(time)); // 10:05 in the morning
ChronoFormatter<PlainTime> printer2 =
ChronoFormatter.ofTimePattern("B", PatternType.CLDR, Locale.ENGLISH)
.with(Attributes.OUTPUT_CONTEXT, OutputContext.STANDALONE);
System.out.println(printer2.format(time)); // morning
The only other library known to me which can also do this (but in an awkward way) is ICU4J.
You can equally have a class that returns the greetings.
import java.util.Calendar;
public class Greetings {
public static String getGreetings()
{
Calendar c = Calendar.getInstance();
int timeOfDay = c.get(Calendar.HOUR_OF_DAY);
if(timeOfDay < 12){
return "Good morning";
}else if(timeOfDay < 16){
return "Good afternoon";
}else if(timeOfDay < 21){
return "Good evening";
}else {
return "Good night";
}
}
}
For Kotlin Users They can use it like this :
private fun showDayMessage():String {
val c: Calendar = Calendar.getInstance()
var message:String ?=null
val timeOfDay: Int = c.get(Calendar.HOUR_OF_DAY)
if (timeOfDay >= 0 && timeOfDay < 12) {
message = "Good Morning"
} else if (timeOfDay >= 12 && timeOfDay < 16) {
message = "Good Afternoon"
} else if (timeOfDay >= 16 && timeOfDay < 21) {
message = "Good Evening"
} else if (timeOfDay >= 21 && timeOfDay < 24) {
message = "Good Night"
}
return message!!
}
When I write
Calendar c = Calendar.getInstance();
int timeOfDay = c.get(Calendar.HOUR_OF_DAY);
I didn't get output and it doesn't show any error. Just the timeOfDay won't get assigned any value in the code. I felt it was because of some threading while Calendar.getInstance() is executed. But when I collapsed the lines it worked for me. See the following code:
int timeOfDay = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
if(timeOfDay >= 0 && timeOfDay < 12){
greeting.setText("Good Morning");
}else if(timeOfDay >= 12 && timeOfDay < 16){
greeting.setText("Good Afternoon");
}else if(timeOfDay >= 16 && timeOfDay < 21){
greeting.setText("Good Evening");
}else if(timeOfDay >= 21 && timeOfDay < 24){
greeting.setText("Good Morning");
}
private String getStringFromMilli(long millis) {
Calendar c = Calendar.getInstance();
c.setTimeInMillis(millis);
int hours = c.get(Calendar.HOUR_OF_DAY);
if(hours >= 1 && hours <= 12){
return "MORNING";
}else if(hours >= 12 && hours <= 16){
return "AFTERNOON";
}else if(hours >= 16 && hours <= 21){
return "EVENING";
}else if(hours >= 21 && hours <= 24){
return "NIGHT";
}
return null;
}
If somebody looking the same for Dart and Flutter: the code without if statements - easy to read and edit.
main() {
int hourValue = DateTime.now().hour;
print(checkDayPeriod(hourValue));
}
String checkDayPeriod(int hour) {
int _res = 21;
Map<int, String> dayPeriods = {
0: 'Good night',
12: 'Good morning',
16: 'Good afternoon',
21: 'Good evening',
};
dayPeriods.forEach(
(key, value) {
if (hour < key && key <= _res) _res = key;
},
);
return dayPeriods[_res];
}
using System;
namespace PF_Claas_Assign1
{
class Program
{
static void Main(string[] args)
{
DateTime Greeting = DateTime.Now;
if (Greeting.Hour >= 5 && Greeting.Hour < 12)
{
Console.WriteLine("Good morning....!");
}
else if (Greeting.Hour >= 12 && Greeting.Hour < 16)
{
Console.WriteLine("Good afternoon...!");
}
else if (Greeting.Hour >= 16 && Greeting.Hour < 20)
{
Console.WriteLine("Good evening...!");
}
else
{
Console.WriteLine("Good night...!");
}
}
}
}
In kotlin use the following
fun getCurrentTime(dateFormatInPut:String,myDate:String): Time {
val sdf = SimpleDateFormat(dateFormatInPut, Locale.ENGLISH)
val date = sdf.parse(myDate)
val millis = date!!.time
val calendar=Calendar.getInstance()
calendar.timeInMillis=millis
return when (calendar.get(Calendar.HOUR_OF_DAY)) {
in 0..11 -> Time.Morning
in 12..15 -> Time.AfterNoon
else -> Time.Evening
}
}
Here Time is enum class
enum class Time {
Morning,
AfterNoon,
Evening
}
A cleaner method for detecting date would be.
//the time cannot go below zero, so if this case is true, it must be between 0 and 12
if(time <= 12)
{
return "Good Morning";
//it will only fall into this case if the time is greater than 12.
}else if(time < 16)
{
return "Good Afternoon";
}else if(time < 21)
{
return "Good Evening";
}else //it is guaranteed that the time will not exceed 24
//, and if the previous case are all false, it must be within 21 and 24
{
return "Good Night";
}
More specific
public static String getDayMessage() {
Calendar c = Calendar.getInstance();
int timeOfDay = c.get(Calendar.HOUR_OF_DAY);
if (timeOfDay < 5) {
return "Hi, Good Mid Night";
}else if (timeOfDay < 6) {
return "Hi, Good Late Night";
} else if (timeOfDay < 12) {
return "Hi, Good Morning";
} else if (timeOfDay < 14) {
return "Hi, Good Noon";
} else if (timeOfDay < 16) {
return "Hi, Good Afternoon";
} else if (timeOfDay < 21) {
return "Hi, Good Evening";
} else {
return "Hi, Good Night";
}
}
As Simple as possible
private String getTimeFromAndroid() {
Date dt = new Date();
Calendar c = Calendar.getInstance();
c.setTime(dt);
int hours = c.get(Calendar.HOUR_OF_DAY);
int min = c.get(Calendar.MINUTE);
if(hours<=12){
return "Good Morning";
}else if(hours<=16){
return "Good Afternoon";
}else if(hours<=21){
return "Good Evening";
}else {
return "Good Night";
}
}
This solution seems perfect for the tropics area countries' users. Suppose my country is Bangladesh and this greeting is appropriate for our users most of the time.
public static String getTimeToHumanGenericTerm(boolean isBangla, Calendar c) {
int timeOfDay = c.get(Calendar.HOUR_OF_DAY);
if (timeOfDay < 5) {
return isBangla ? " মধ্যরাত " : " Mid Night";
} else if (timeOfDay < 6) {
return isBangla ? " শেষরাত " : " Late Night";
} else if (timeOfDay < 12) {
return isBangla ? " সকাল " : " Late Night";
} else if (timeOfDay < 14) {
return isBangla ? " দুপুর" : " Noon";
} else if (timeOfDay < 16) {
return isBangla ? " বিকাল" : " Afternoon";
} else if (timeOfDay < 21) {
return isBangla ? " সন্ধ্যা" : " Evening";
} else {
return isBangla ? " রাত " : " Night";
}
}
I have everything working but the System.exit(0). It should exit any time remaining if the button is pressed. I'm not sure what to do. Help would be greatly appreciated.
/*
Creates the perfect hard-boiled(simulates 12 minutes in boiling water) or soft-boiled
egg(simulates 6 minutes in boiling water). Both options require 10 seconds of rinsing
under cold water after necessary time for boiling. Allow user to exit any remaining
time.
*/
import java.io.*;
import java.util.*;
public class AdvancedEggMaker {
public static void main(String[] args) {
MCU mcu = null;
try {
mcu = new MCU(new Communicator(args[0]));
}
catch (IOException e) {
System.out.println(e);
}
mcu.println("SW2 - HB Egg", 0);
mcu.println("SW3 - SB Egg", 1);
while (true) {
int sw = mcu.getSwitch();
if (sw == 2) {
mcu.println("Hard Boiled Egg", 0);
mcu.println("Place Egg in", 0);
mcu.println("boiling water", 1);
mcu.println("then press SW4", 0);
mcu.println("SW5 - Quit", 1);
int sw2 = mcu.getSwitch();
switch (sw2) {
case 4:
int t = 720;
while (t > 0 && sw2 == 4) {
t = (t - 1);
mcu.println("Boiling...", 0);
mcu.println((t / 60) + "mins left...", 1);
}
break;
case 5:
System.exit(0);
break;
}
}
if (sw == 3) {
mcu.println("Soft Boiled Egg", 0);
mcu.println("Place Egg in", 0);
mcu.println("boiling water", 1);
mcu.println("then press SW4", 0);
mcu.println("SW5 - Quit", 1);
int sw2 = mcu.getSwitch();
switch (sw2) {
case 4:
int t = 360;
while (t > 0 && sw2 == 4) {
t = (t - 1);
mcu.println("Boiling...", 0);
mcu.println((t / 60) + "mins left...", 1);
}
break;
case 5:
System.exit(0);
break;
}
}
mcu.println("Rinse Egg", 0);
mcu.println("then press SW4", 0);
mcu.println("SW5 - Quit", 1);
int sw3 = mcu.getSwitch();
if (sw3 == 4) {
double t = 10;
while (t > 0.0) {
t = (t - 1);
mcu.println("Rinsing...", 0);
mcu.println(t + "Secs left...", 1);
}
if (sw == 5) {
System.exit(0);
}
}
}
}
}
Are you sure about that the execution is reaching one of your System.exit(0) statements. I don't see any sysout or logs to help you to be sure about that. First examine that because I don't see there any reason why it should not work.
Secondly you can check whether you have some background thread working in your code. It may be the case that you may have some connections/streams open somewhere in a thread and it is not letting the System.exit(0) to terminate the process.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
why am i getting the following error message when i call the toString of class Date from toString of class Time2 ?
Exception in thread "main" java.lang.NullPointerException
at Exerciseschpt8.Time2.toString(Time2.java:111)
at Exerciseschpt8.Time2Test.main(Time2Test.java:18)
package Exerciseschpt8;
public class Date{
private int month; // 1-12
private int day; // 1-31 based on month
private int year; // any year
public Date(){
this(0,0,0);
}
public Date(int theMonth, int theDay, int theYear) {
month = checkMonth(theMonth); // validate month
year = theYear; // could validate year
day = checkDay(theDay); // validate day
System.out.printf("Date object constructor for date %s\n", this);
}
private int checkMonth(int month) {
if (month > 0 && month <= 12) // validate month
return month;
else // month is invalid
{
System.out.printf("Invalid month (%d) set to 1.", month);
return 1; // maintain object in consistent state
} // end else
} // end method checkMonth
// utility method to confirm proper day value based on month and year
private int checkDay(int day) {
int[] daysPerMonth = { 0, 31, 28, 31, 30, 31, 30, 28, 31, 30, 31, 30,
31 };
// check if day in range for month
if (day > 0 && day <= daysPerMonth[month])
return day;
// check for leap year
if (month == 2 && day == 29
&& (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)))
return day;
System.out.printf("Invalid day (%d) set to 1.", day);
return 1; // maintain object in consistent state
} // end method checkDay
// return a String of the form month/day/year
public String toString() {
return ""+month+"/"+ day+"/"+year;
} // end method toString
public int nextDay() {
int testDay = day + 1;
if (checkDay(testDay) == testDay)
day = testDay;
else {
day = 1;
//nextMonth();
}
return day;
}
public int nextMonth() {
if (1 == month)
month++;
return month = 1;
}
public String toDateString() {
return month + "/" + day + "*/" + year;
}
}
package Exerciseschpt8;
import Exerciseschpt8.Date;
public class Time2 {
Date dateX;
private int hour; // 0 - 23
private int minute; // 0 - 59
private int second; // 0 - 59
public Time2() {
this(0, 0, 0);
}
public Time2(int h) {
this(h, 0, 0);
}
public Time2(int h, int m) {
this(h, m, 0);
}
public Time2(int h, int m, int s) {
setTime(h, m, s);
}
public Time2(Time2 time) {
this(time.getHour(), time.getMinute(), time.getSecond());
}
public boolean setTime(int h, int m, int s) {
boolean hourValid, minuteValid, secondValid;
hourValid = setHour(h); // set the hour
minuteValid = setMinute(m); // set the minute
secondValid = setSecond(s); // set the second
return (hourValid && minuteValid && secondValid);
}
public boolean setHour(int h) {
// hour = ((h >= 0 && h < 24) ? h : 0);
if (h >= 0 && h < 24) {
hour = h;
return true;
} else {
hour = 0;
return false;
}
} // end method setHour
public boolean setMinute(int m) {
// minute = ((m >= 0 && m < 60) ? m : 0);
if (m >= 0 && m < 60) {
minute = m;
return true;
} else {
minute = 0;
return false;
}
} // end method setMinute
public boolean setSecond(int s) {
// second = ((s >= 0 && s < 60) ? s : 0);
if (s >= 0 && s < 60) {
second = s;
return true;
} else {
second = 0;
return false;
}
} // end method setSecond
public int getHour() {
return hour;
} // end method getHour
public int getMinute() {
return minute;
} // end method getMinute
public int getSecond() {
return second;
} // end method getSecond
// Tick the time by one second
public void tick() {
setSecond(second + 1);
if (second == 23)
incrementMinute();
}
public void incrementMinute() {
setMinute(minute + 1);
if (minute == 25)
incrementHour();
}
public void incrementHour() {
setHour(hour + 1);
if (hour == 0)
dateX.nextDay();
}
public String toString() {
return + hour + ":" + minute + ":" + second + "\n"+dateX.toString();
}
package Exerciseschpt8;
public class Time2Test {
public static void main(String[] args) {
Time2 t1 = new Time2(2,15,23); // 00:00:00
/
Date d1 = new Date(10,23,1973);
//System.out.println(d1.toDateString());
System.out.println("Constructed with:");
System.out.println("t1: all arguments defaulted");
//System.out.printf(" %s\n", t1.toUniversalString());
System.out.printf(" %s\n", t1.toString());
}
}
You are nowhere initializing dateX in your Time2 class and using a method on it (dateX.toString()) in the toString() method of Time2 class. That is causing the valid NullPointerException.
To fix the issue, intialize dateX as appropriate to your program.
In the line Date dateX; you are declaring dateX, but you aren't initializing it, so it's a null pointer. To initialize it, change the line to Date dateX = new Date();