Reputation: 17
When I try to complie this code, Lines 41-45 give me an "Unreachable code" statement. Same thing happens when I put in a few lines to handle exceptions. Is there something wrong that I am doing? This is a modified example code from the book SAMS Teach yourself Java in 24 hours. Using it as a refresher.
import java.util.*;
import java.util.concurrent.TimeUnit;
public class Clock {
public static void main(String[] arguments) {
Calendar now = Calendar.getInstance();
int hour = now.get(Calendar.HOUR_OF_DAY);
int minute = now.get(Calendar.MINUTE);
int month = now.get(Calendar.MONTH) + 1;
int day = now.get(Calendar.DAY_OF_MONTH);
int year = now.get(Calendar.YEAR);
//Display greeting
if (hour < 12){
System.out.println("Good Morning! \n");
}else if (hour < 17){
System.out.println("Good afternoon! \n");
} else {
System.out.println("Good evening! \n");
}
//Time message start
while(1 < 2){
try
{
final String os = System.getProperty("os.name");
if (os.contains("Windows"))
{
Runtime.getRuntime().exec("cls");
}
else
{
Runtime.getRuntime().exec("clear");
}
}
catch (final Exception e)
{
// Handle any exceptions.
}
}
//Errors occur here
try {
TimeUnit.SECONDS.sleep(100);
} catch (InterruptedException e) {
//Handle exception
}
//Errors end here
System.out.println("The time currently is:" + hour + ":" + minute);
System.out.println("Date: " + month + "/" + day + "/" + year);
}
}
Upvotes: 1
Views: 267
Reputation: 1
You have an infinite loop. 1 is always less than 2.
Suggestions:
Upvotes: 0
Reputation: 21
As your while loop is an infinite loop, so your code will never reach to your this block.
//Errors occur here
try {
TimeUnit.SECONDS.sleep(100);
} catch (InterruptedException e) {
//Handle exception
}
//Errors end here
System.out.println("The time currently is:" + hour + ":" + minute);
System.out.println("Date: " + month + "/" + day + "/" + year);
}
As your code
while(1 < 2){
try
{
final String os = System.getProperty("os.name");
if (os.contains("Windows"))
{
Runtime.getRuntime().exec("cls");
}
else
{
Runtime.getRuntime().exec("clear");
}
}
catch (final Exception e)
{
// Handle any exceptions.
}
} // from here again start from loop staring point and looping this again and again
so in compile time compiler is warning you that your second try block and rest statements are unreachable. you program will never able to execute this blocks. That's why it is saying unreachable.
Upvotes: 0
Reputation: 72844
The while
loop will never break since 1 < 2
is always true. Therefore, the part after the while loop will never be reached, hence the compiler error.
Upvotes: 2
Reputation: 1612
The code there is unreachable, as the while loop condition, 1 < 2
, is always true, and so you are always in the while loop. To avoid it, you can:
while
loop condition to something that can be false.break
statement somewhere in your while loop, to exit it.Upvotes: 6