无法访问的Java代码

Tma*_*122 1 java exception

当我尝试编译此代码时,第41-45行给出了一个"无法访问的代码"语句.当我输入几行来处理异常时,会发生同样的事情.我有什么不对劲吗?这是SAMS在24小时内自学Java一书中的修改示例代码.用它作为复习.

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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

eri*_*c.m 6

由于while循环条件1 < 2始终为true,因此无法访问代码,因此您始终处于while循环中.为避免这种情况,您可以:

  • while循环条件更改为可能为false的内容.
  • break在while循环中的某处添加一个语句,退出它.