f) 阅读下列程序,写出程序运行结果。
class Calculator { public static double f1(int[] numbers) { int sum = 0; for (int i=0; i<numbers.length; i++) sum += numbers[i]; return sum/(double)numbers.length; } public static int f2(int[] numbers) { int max = numbers[0]; for (int i=0; i<numbers.length; i++) if (numbers[i] > max) max = numbers[i]; return max; } } public class CalculatorTester2 { public static void main(String args[]) { int numbers[] = {23, 54, 88, 98, 23, 54, 7, 72, 35, 22}; System.out.println("The val1 is " + Calculator.f1(numbers)); System.out.println("The val2 is " + Calculator.f2(numbers)); } }
The val1 is 47.6
/ The val2 is 98
三、 程序填空(每空2分,共20分)
下面为时间服务器的客户端和服务器端程序,客户端通过网络命令可以获取服务器时
间。补充缺少部分,使之成为一个完整的程序,将答案写入答案栏。
客户端程序: import .*; import java.io.*;
public class JTimeClient {
private String server; //时间服务器 private int port; //端口号
{ this.server = server; this.port = port; }
//返回网络时间, -1表示出错 public long getNetTime() { Socket socket = null; InputStream in = null; try {
socket = new Socket(server, port); in = socket.getInputStream( );
//读取数据,网络时间为4字节无符号整数, long netTime = 0; for(int i=0; i<4; i++) {
netTime = return netTime; }
catch (UnknownHostException e) { } catch ( e) { } finally {//安全释放资源 try {//关闭输入流
if(in != null) in.close(); } catch (Exception e) {} try {//关闭连接
if(socket != null) ; } catch (Exception e) {} }
return -1; }
public static void main(String[] args) { JTimeClient timeClient = null; if(args.length == 2) { timeClient = new JTimeClient(args[0], Integer.parseInt(args[1])); } else { System.out.println("Usage: java JTimeClient TimeServer Port"); return; }
System.out.println("Time:" + timeClient.getNetTime()); } }