简体   繁体   中英

why java program is outputting the following

Below is the code for implementing time server

Server class

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)
        {
        }
    }

Client class

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)
        {
        }
    }

the program is working but the output is always

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

why it is outputting the above values

That's because you're printing the values of the static integer fields called HOUR , MINUTE , SECOND present in the Calendar class. You need to use the Calendar#get(field) method to get the HOUR , MINUTE , SECOND values from the Calendar.

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

Note that since HOUR, MINUTE, SECOND are static fields, you need to access them using the class name( Calendar.SECOND ) and not using the instance( c.SECOND ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM