第一题帮你做了,剩下的自己努力
public class AgeException extends Exception {
int age = 0;
AgeException(int age){
this.age = age;
}
public String toString(){
return "年龄应在18—80之间";
}
}
----------------------------------------
public class Age {
public static void main(String[] args){
getAge(15);
getAge(30);
}
private static void getAge(int age){
if(age>80 || age<18){
try {
throw new AgeException(age);
} catch (AgeException e) {
e.printStackTrace();
return;
}
}
System.out.println("年龄" + age +"合法");
}
}
public class AgeException extends Exception {
int age = 0;
AgeException(int age){
this.age = age;
}
public String toString(){
return "年龄应在18—80之间";
}
}
----------------------------------------
public class Age { //创建类
public static void main(String[] args){ //主方法
getAge(15);
getAge(30);
}
private static void getAge(int age){
if(age>80 || age<18){ //用if语句可判断 age大于80且小于18
try {
throw new AgeException(age);
} catch (AgeException e) {
e.printStackTrace();
return;
}
}
System.out.println("年龄" + age +"合法"); //输出信息
}
}
这是18和80是之间的, “急求采纳,需要分数下载java面试宝典。”
客户端:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class ClientDemo {
public static void main(String[] args) {
Socket socket;
BufferedReader in;
PrintWriter out;
try {
socket = new Socket("localhost", 8900);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream());
String str = in.readLine();
System.out.println(str);
Scanner console = new Scanner(System.in);
out.println(console.nextLine());
out.flush();
str = in.readLine();
System.out.println(str);
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
服务器:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerDemo {
public static void main(String[] args) throws Exception{
ServerDemo server = new ServerDemo();
server.listen(8900);
}
public void listen(int port) throws Exception{
ServerSocket ss = new ServerSocket(port);
System.out.println("等待客户端连接 :");
while(true){
Socket socket = ss.accept();
System.out.println("客户端连接上:");
new ClientAgent(socket);
}
}
class ClientAgent extends Thread{
Socket socket;
public ClientAgent(Socket socket){
this.socket = socket;
start();
}
public void run(){
try {
BufferedReader in= new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream());
out.println("客户端连接成功:");
out.flush();
String str = in.readLine();
System.out.println(str);
out.println("已接受你提交的信息");
out.flush();
in.close();
out.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}