为什么java程序输出以下内容

时间:2014-02-19 06:55:48

标签: java time calendar

以下是实施时间服务器的代码

服务器类

public static void main(String args[])
    {
   try{
            ServerSocket ss=new ServerSocket(990);
             Socket s=ss.accept();
            while(true)
            {
                Calendar c=Calendar.getInstance();
                BufferedReader in=new BufferedReader(new InputStreamReader(s.getInputStream()));
                PrintWriter out =new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
                out.println("Hello This is server & My Time is :");
                out.println("Time :::  Hour="+c.HOUR +" Min="+c.MINUTE +" sec="+c.SECOND);
            out.flush();
              s.close();
            }
        }
        catch(Exception e)
        {
        }
    }

客户端类

public static void main(String args[])
    {
   try{
            ServerSocket ss=new ServerSocket(990);
             Socket s=ss.accept();
            while(true)
            {
                Calendar c=Calendar.getInstance();
                BufferedReader in=new BufferedReader(new InputStreamReader(s.getInputStream()));
                PrintWriter out =new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
                out.println("Hello This is server & My Time is :");
                out.println("Time :::  Hour="+c.HOUR +" Min="+c.MINUTE +" sec="+c.SECOND);
            out.flush();
              s.close();
            }
        }
        catch(Exception e)
        {
        }
    }

程序正在运行,但输出始终是

time:: hour=10 min=12 sec=13

为什么输出上述值

1 个答案:

答案 0 :(得分:5)

那是因为您正在打印Calendar类中存在的名为HOURMINUTESECOND的静态整数字段的值。您需要使用Calendar#get(field)方法从日历中获取HOURMINUTESECOND值。

out.println("Time :::  Hour="+c.get(Calendar.HOUR) +" Min="+c.get(Calendar.MINUTE)+" sec="+c.get(Calendar.SECOND));

请注意,由于HOUR,MINUTE,SECOND是static字段,因此您需要使用类名(Calendar.SECOND)访问它们而不使用实例(c.SECOND)。