JAVA程序设计期末提高复习题(大一)

1、利用java语言编程,判断101-200之间有多少个素数,并输出所有素数。

public class  Test1{
    public static void main(String args[]) {
    	int count = 0;
    	for(int i = 100;i<201;i++) {
    		boolean flag = true;
    		for(int k =2;k
public  class Test1 {

        public static void main(String[] args) {
            //第一题
        long num = 0;
        for (int i = 101; i <= 200; i++) {
            if (check(i)) {
                num += 1;
            }
        }
        System.out.println(num);
        }

        private static boolean check(int i) {
            for (int j = 2; j <= Math.sqrt(i); j++) {
                if (i % j == 0) {
                    return false;
                }
            }
            return true;
        }
    }

2.利用java语言编程,打印出所有的 "水仙花数 ",所谓 "水仙花数 "是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个 "水仙花数 ",因为153=1的三次方+5的三次方+3的三次方。

public class Test2 {
    public static void main(String[] args) {
        int a,b,c;
        for(int i=101;i<1000;i++) {
//判断这个三位数是否满足要求:个十百位立方和相加等于一个水仙花数
            a=i%10;//个位
            b=i/10%10;//十位
            c=i/100;//百位
            if(a*a*a+b*b*b+c*c*c==i){
                System.out.println(i);
            }
        }
} 
//计算水仙花个数
public  class Test2 {
        public static void main(String[] args) {

        long num = 0;
        for (int i = 100; i <= 999; i++) {
            int a = i % 10;
            int b = i / 10 % 10;
            int c = i / 100;
            if ((a * a * a + b * b * b + c * c * c) == i) {
                num++;
            }
        }
        System.out.println(num);
                }
                }

3.利用java语言编程,利用条件运算符的嵌套来完成此题:学习成绩> =90分的同学用A表示,60-89分之间的用B表示,60分以下的用C表示。

import java.util.Scanner;
public class Test3 {
    public static void main(String[] args) {
        Scanner input=new Scanner(System.in);
        int score=input.nextInt();
        char grade=score>=90?'A':score>=60?'B':'C';
        System.out.println(grade);
    }
}

4、利用java语言编程,输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。

import java.util.Scanner;
public class Test4 {
    public static void main(String[] args) {
        int abccount=0;
        int spacecount=0;
        int numcount=0;
        int othercount=0;
        Scanner input=new Scanner(System.in);
        String toString=input.nextLine();
        char [] ch=toString.toCharArray();
 
        for(int i=0;i
public class Test4 {
    //题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一行字符:");
        String s = sc.nextLine();
        int zm=s.length()-(s.replaceAll("[a-zA-Z]","")).length();
        int kg=s.length()-(s.replaceAll("[ ]","")).length();
        int sz=s.length()-(s.replaceAll("[0-9]","")).length();
        int qt=s.length()-zm-kg-sz;
        System.out.println("字母有:"+zm);
        System.out.println("空格有:"+kg);
        System.out.println("数字有:"+sz);
        System.out.println("其他字符有:"+qt);
    }
}
public  class Test4 {
    public static void main(String[] args) {
Scanner s = new Scanner(System.in);
        String str = s.nextLine();
        int num = 0, strNum = 0, sum = 0, other = 0;
        for (int i = 0; i < str.length(); i++) {
        if (str.charAt(i) >= '0' && str.charAt(i) <= '9') {
        num++;
        } else if (str.charAt(i) >= 'A' && str.charAt(i) <= 'Z') {
        strNum++;
        } else if (str.charAt(i) >= 'a' && str.charAt(i) <= 'z') {
        strNum++;
        } else if (str.charAt(i) == ' ') {
        sum++;
        } else {
        other++;
        }
        }
        System.out.printf("%d,%d,%d,%d",num,strNum,sum,other);
        }
        }

5、利用java语言编程,利用toCharArray()方法将字符串“江西财经职业学院”转换为数组并输出。

public class Test5 {
    public static void main(String[] args) {
        String str = "江西财经职业学院";
        
        // 将字符串转换为字符数组
        char[] charArray = str.toCharArray();
        
        // 输出字符数组中的每一个元素
        for (int i = 0; i < charArray.length; i++) {
            System.out.print(charArray[i] + " ");
        }
    }
}
public class Test5 {
    public static void main(String[] args) {
        String str = "江西财经职业学院";
        char[] strAll = str.toCharArray();
        System.out.println(strAll);
    }
}

6.利用java语言编程,利用String类的方法将“fdadfadfAFDAfadKJLJOKJjjIFGUFUvy”全部转成小写并输入。

public class Test6 {
    public static void main(String[] args) {
        String str = "fdadfadfAFDAfadKJLJOKJjjIFGUFUvy";
                String result = str.toLowerCase();
        System.out.println(result);
    }
}
public class Test6 {
    public static void main(String[] args) {
        String str = "fdadfadfAFDAfadKJLJOKJjjIFGUFUvy";
        System.out.println(str.toLowerCase());
    }
}

7.利用java语言编程,利用Calendar类的方法,把系统时间拆分成:年、月、日、时、分、秒、毫秒,输出以分行方式显示。

import java.util.Calendar;
public class Test7 {
    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;  // 月份需要加1
        int day = cal.get(Calendar.DAY_OF_MONTH); 
        int hour = cal.get(Calendar.HOUR_OF_DAY);  // 24小时制
        int minute = cal.get(Calendar.MINUTE);
        int second = cal.get(Calendar.SECOND);
        int millisecond = cal.get(Calendar.MILLISECOND);
     
        System.out.println("年:" + year);
        System.out.println("月:" + month);
        System.out.println("日:" + day);
        System.out.println("时:" + hour);
        System.out.println("分:" + minute);
        System.out.println("秒:" + second);
        System.out.println("毫秒:" + millisecond);
    } 
}
public class Test7 {
    public static void main(String[] args) {
Calendar cale = Calendar.getInstance();
        System.out.println("年"+cale.get(Calendar.YEAR));
        System.out.println("月"+cale.get(Calendar.MONTH) + 1);
        System.out.println("日"+cale.get(Calendar.DAY_OF_MONTH));
        System.out.println("时"+cale.get(Calendar.HOUR_OF_DAY));
        System.out.println("分"+cale.get(Calendar.MINUTE));
        System.out.println("秒"+cale.get(Calendar.SECOND));
        System.out.println("毫秒"+cale.get(Calendar.MILLISECOND));

        }}

8.利用java语言编程,记录3只流浪猫的姓名、性别、花色和状况信息,并输出。3只流浪猫的详细信息是:

小喵,母,橘猫,收留。

小米,公,三花,收留。

小咪,母,奶牛,领养。

public class Cat {
    String name; 
    String gender; 
    String color;  
    String status;  
    
    public Cat(String name, String gender, String color, String status) {
        this.name = name;
        this.gender = gender;
        this.color = color;
        this.status = status;
    }
}

public class Test8 {
    public static void main(String[] args) {
        Cat cat1 = new Cat("小喵", "母", "橘猫", "收留");
        Cat cat2 = new Cat("小米", "公", "三花", "收留");
        Cat cat3 = new Cat("小咪", "母", "奶牛", "领养");
        
        Cat[] cats = {cat1, cat2, cat3};
        
        for (int i = 0; i < cats.length; i++) {
            System.out.println("姓名:" + cats[i].name);
            System.out.println("性别:" + cats[i].gender);
            System.out.println("花色:" + cats[i].color);
            System.out.println("状况:" + cats[i].status);
            System.out.println();   
        }
    }
}
import java.util.ArrayList;
import java.util.List;

public class Test8 {
    public static void main(String[] args) {
        ArrayList list = new ArrayList<>();
        // 将猫对象添加到list集合
        list.add(new catTest8("小喵", '母',"橘猫","收留"));
        list.add(new catTest8("小米", '公',"三花","收留"));
        list.add(new catTest8("小咪", '母',"奶牛","领养"));
        System.out.println("名称 性别 花色 领养状态");
        // 遍历集合输出
        list.forEach(System.out::println);
    }
}
/*
public class catTest8 {
    private String name;
    private char sex;
    private String color;
    private String locale;

    public catTest8() {

    }

    public catTest8(String name, char sex, String color, String locale) {
        this.name = name;
        this.sex = sex;
        this.color = color;
        this.locale = locale;
    }

    @Override
    public String toString() {
        return name + "," + sex + "," + color + ","+  locale;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public char getSex() {
        return sex;
    }

    public void setSex(char sex) {
        this.sex = sex;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public String getLocale() {
        return locale;
    }

    public void setLocale(String locale) {
        this.locale = locale;
    }
}*/

9.利用java语言编程,模拟冬奥会花样滑冰比赛的评分机制,请5位评委(1-5号评委)打分。在控制台输入5个10分以内的整数,使用逗号隔开,输出每位评委的评分并计算平均分。

public class Test9 {
    public static void main(String[] args) {
          Scanner scanner = new Scanner(System.in);
           System.out.println("请输入5个评委的分数,用英文逗号分隔:");
           String s = scanner.nextLine();
           String[] arr = s.split(",");
           if (arr.length != 5) {
               System.out.println("输入有误!请确保输入5个评委的分数!");
               return;
           }
           int[] nums = new int[5];
           int sum = 0;
           for (int i = 0; i < 5; i++) {
               int score = Integer.parseInt(arr[i].trim());    
//parseInt方法用于将字符串转为整数。
               if (score < 0 || score > 10) {
                   System.out.println("输入有误!请输入0到10之间的整数!");
                   return;
               }
               nums[i] = score;
               sum += score;
           }
           System.out.println("平均值:" + (double) sum / 5);
       }
   }
public class Test9 {
        public static void main (String[]args){
             Scanner scanner = new Scanner(System.in);
           System.out.println("请输入5个分数用英文逗号隔开");
           //String next():接收键盘输入的内容,并以字符串形式返回
           String input = scanner.next();
           //split():根据匹配给定的正则表达式来拆分此字符串
           String[] string = input.split(",");//英文逗号
           if (string.length != 5) {
               System.out.println("输入有误!请确保输入5个评委的分数!");
               return;
           }
           // 定义一个数组,用来存储取出来的5个数
           int[] nums = new int[5];
           System.out.print("数字转换格式后:");
           int sum = 0;
           for (int i = 0; i < 5; i++) {
               int score = Integer.parseInt(string[i].trim());
               if (score < 0 || score > 10) {
                   System.out.println("输入有误!请输入0到10之间的整数!");
                   return;
               }
               //将字符串参数作为有符号的十进制整数进行解
               nums[i] = Integer.parseInt(string[i]);
               sum = sum + nums[i];
               System.out.print(nums[i] + " ");
           }
           System.out.println();
           TreeMap treeMap = new TreeMap<>();
           treeMap.putAll(treeMap);
           treeMap.put("1号评委", nums[0]);
           treeMap.put("2号评委", nums[1]);
           treeMap.put("3号评委", nums[2]);
           treeMap.put("4号评委", nums[3]);
           treeMap.put("5号评委", nums[4]);
           Iterator iter = treeMap.keySet().iterator();
           while (iter.hasNext()) {
               String str = (String) iter.next();
               int name = (int) treeMap.get(str);
               System.out.println(str + " " + name);
           }
           System.out.println("平均分数为" + (double)sum/5);
       }
   }
public class Test9 {
    public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
             System.out.print("请输入5个10分以内的整数,使用英文逗号隔开:");
                     String s = input.nextLine();
                     String[] arr = s.split(",");//英文逗号
        if (arr.length != 5) {
            System.out.println("输入有误!请确保用英文逗号输入5个评委的分数!");
            return;
        }
                     int[] scores = new int[5];
                     for (int i = 0; i < 5; i++) {
        int score = Integer.parseInt(arr[i].trim());
        if (score < 0 || score > 10) {
        System.out.println("请输入0到10之间的5个整数!");
        return;
        }
        scores[i] = score;
        }

        System.out.println("每位评委的评分如下:");
        for (int i = 0; i < 5; i++) {
        System.out.println("第" + (i+1) + "号评委:" + scores[i] + "分");
        }

        double sum = 0;
        for (int i = 0; i < 5; i++) {
            int score = Integer.parseInt(arr[i].trim());
            if (score < 0 || score > 10) {
                System.out.println("输入有误!请输入0到10之间的整数!");
                return;
            }
        sum += scores[i];
        }
        double average = sum / scores.length;

        System.out.println("平均分为:" + average + "分");
        }
        }

10.利用java语言编程,用fileList()方法遍历c:盘所有的文件。

public class Test10 {
    public static void main(String[] args) {
        File root = new File("C:\\");
        if (root.isDirectory() && root.exists()) {
            File[] files = root.listFiles();
            for (File file : files) {
                if (file.isFile()) {
                    System.out.println(file.getAbsolutePath());
                }
            }
        } else {
            System.out.println("C: 盘根目录不存在或者不是一个目录!");
        }
    }
}
//isDirectory()函数是Java中File类的一部分。
// 此函数确定由抽象文件名表示的文件或目录是否为Directory。
// 如果抽象文件路径为Directory,则函数返回true,否则返回false。
//getAbsolutePath()返回抽象路径名的绝对路径名字符串。
//java获取c盘所有文件(递归)
public class Test10 {
    public static void main(String[] args) {
        File file = new File("C:\\");// 指定文件目录
        method(file);
    }
Method类
//代表类中的一个方法的定义,一个Method由修饰符,返回值,方法名称,参数列表组合而成。
    public static void method(File file) {
        File[] fs = file.listFiles();// 得到File数组

        if (fs != null) {// 判断fs是否为null
            for (File f : fs) {
                if (f.isFile()) {// 如果是文件直接输出
                    System.out.println(f.getName());
                } else {
                    method(f);// 否则递归调用
                }
            }
        }

    }
}
public class Test10 {
    public static void main(String[] args) throws Exception {
        File f = new File("C:\\");
        showAllFile(f);
    }

    private static void showAllFile(File file) throws Exception {
        File[] files = file.listFiles();
        for (int i = 0; i < files.length; i++) {
            System.out.println(files[i].getAbsolutePath());
            if (files.length < 0)
                continue;
            if (files[i].isDirectory()) {
                showAllFile(files[i]);
            }
        }
    }
}

11、利用java语言编程,用文件输入输出流,实现对c:盘下的某个文件复制到d:盘。

public class Test11 {
    public static void main(String[] args) {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream("C:\\Temp\\test.txt");//注意文件路径
            fos = new FileOutputStream("D:\\test.txt");

            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
            System.out.println("文件复制完成!");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
public class Test11 {
public static void main(String[] args) throws Exception {

        FileReader fr = new FileReader("C:\\Temp\\test.txt");

        FileWriter fw = new FileWriter("D:\\test.txt");

        char [] c = new char[10];
        int i = fr.read(c);
        while (i != -1) {
        fw.write(c , 0 , i);

        i = fr.read(c);
        }


        fw.close();
        fr.close();

        }}
public class FileCopyExample {
    public static void main(String[] args){
        String sourceFile = "C:\\file.txt";
        String destinationFile = "D:\\file.txt";

        try (FileInputStream fis = new FileInputStream(sourceFile);
             FileOutputStream fos = new FileOutputStream(destinationFile)) {

            byte[] buffer = new byte[1024];
            int length;

            while ((length = fis.read(buffer)) > 0) {
                fos.write(buffer, 0, length);
            }

            System.out.println("文件复制成功!");

        } catch(IOException e) {
            System.out.println("文件复制失败:" + e.getMessage());
        }
    }
}
//该示例中使用了try-with-resources语句,它在使用完后会自动关闭文件输入输出流。

12、利用java语言编程,输出呀一个登录窗体,窗体名称为:学生管理登录系统;窗体包括:用户名lable,密码lable,两个文本框,登录button,取消button。布局自行设定。

public class Demo0618 extends JFrame {
    private JLabel usernameLabel, passwordLabel;
    private JTextField usernameField, passwordField;
    private JButton loginButton, cancelButton;

    public Demo0618() {

        setTitle("学生管理登录系统");
        setSize(500, 250);
        setLocationRelativeTo(null);  // 在屏幕中心显示


        usernameLabel = new JLabel("用户名:");
        passwordLabel = new JLabel("密码:");


        usernameField = new JTextField(10);
        passwordField = new JPasswordField(10);


        loginButton = new JButton("登录");
        cancelButton = new JButton("取消");


        setLayout(new GridLayout(4, 2));//页面布局单元格

        add(usernameLabel);
        add(usernameField);
        add(passwordLabel);
        add(passwordField);
        add(loginButton);
        add(cancelButton);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }

    public static void main(String[] args) {
        new Demo0618();
    }
}

13、利用java语言编程,实现一个窗体,包含文件、开始、插入三个菜单,文件菜单包含打开、保存、复制、替换四个子菜单,开始菜单包括字体、段落、行距子菜单。

public class Test13 {
    public static void main(String[] args) {
        JFrame jf = new JFrame("窗体");
        JMenuBar jmb = new JMenuBar();
        jf.setJMenuBar(jmb);
        JMenu jm = new JMenu("文件");
        JMenu jm1 = new JMenu("开始");
        JMenu jm2 = new JMenu("插入");
        jmb.add(jm);
        jmb.add(jm1);
        jmb.add(jm2);
        JMenuItem item = new JMenuItem("打开");
        JMenuItem item1 = new JMenuItem("保存");
        JMenuItem item2 = new JMenuItem("复制");
        JMenuItem item3 = new JMenuItem("替换");
        jm.add(item);
        jm.add(item1);
        jm.add(item2);
        jm.add(item3);
        JMenuItem item4 = new JMenuItem("字体");
        JMenuItem item5 = new JMenuItem("段落");
        JMenuItem item6 = new JMenuItem("行距");
        jm1.add(item4);
        jm1.add(item5);
        jm1.add(item6);
        jf.setBounds(500, 500, 500, 300);
        jf.setVisible(true);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}
//利用java语言编程,实现一个窗体,包含文件、开始、插入三个菜单,
// 文件菜单包含打开、保存、复制、替换四个子菜单,开始菜单包括字体、段落、行距子菜单。
public class Demo0618 extends JFrame {
    private JMenuBar menuBar;
    private JMenu fileMenu, startMenu;
    private JMenu fileSubMenu, startSubMenu1, startSubMenu2,startSubMenu3;
    private JMenu insertMenu, insertMenu1, insertMenu2;
    private JMenuItem openItem, saveItem, copyItem, replaceItem;
    private JMenuItem fontItem,  lineSpacingItem;

    public Demo0618() {
        setTitle("菜单");
        setSize(400, 300);
        setLocationRelativeTo(null);

        menuBar = new JMenuBar();

        fileMenu = new JMenu("文件");
        startMenu = new JMenu("开始");
        insertMenu =new JMenu("插入");
        fileSubMenu = new JMenu("文件操作");
        openItem = new JMenuItem("打开");
        saveItem = new JMenuItem("保存");
        copyItem = new JMenuItem("复制");
        replaceItem = new JMenuItem("替换");

        startSubMenu1 = new JMenu("字体");
        startSubMenu2 = new JMenu("段落");
        startSubMenu3 = new JMenu("行距");
        fontItem = new JMenuItem("设置字体");
        lineSpacingItem = new JMenuItem("设置行距");


        fileSubMenu.add(openItem);
        fileSubMenu.add(saveItem);
        fileSubMenu.add(copyItem);
        fileSubMenu.add(replaceItem);
        startSubMenu1.add(fontItem);
        startSubMenu2.add(lineSpacingItem);


        fileMenu.add(fileSubMenu);
        startMenu.add(startSubMenu1);
        startMenu.add(startSubMenu2);
        startMenu.add(startSubMenu3);


        menuBar.add(fileMenu);
        menuBar.add(startMenu);
        menuBar.add(insertMenu);


        setJMenuBar(menuBar);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }

    public static void main(String[] args) {
        new Demo0618();
    }
}
/*编写一个应用程序,要求如下:  ① 在窗口设置两个菜单“文件”、“编辑”; ② 在“文件”菜单里添加三个菜单
项“打开”、“保存”、“关闭”; ③ 在“编辑”菜单里添加两个菜单项“复制”*/
public class Demo0618 {
    public static class cannian extends JFrame{
        public cannian(){
            super("菜单演示");
            //创建菜单栏
            JMenuBar menuBar = new JMenuBar();
            //设置菜单栏
            setJMenuBar(menuBar);
            //创建菜单
            JMenu m1 = new JMenu("文件");
            //向菜单栏中添加菜单
            menuBar.add(m1);
            //创建选项
            JMenuItem menuItem1 = new JMenuItem("打开");
            JMenuItem menuItem2 = new JMenuItem("保存");
            JMenuItem menuItem3 = new JMenuItem("关闭");
            m1.add(menuItem1);
            m1.add(menuItem2);
            m1.add(menuItem3);
            JMenu m2 = new JMenu("编辑");
            menuBar.add(m2);
            JMenuItem menuItem4 = new JMenuItem("复制");
            JMenuItem menuItem5 = new JMenuItem("粘贴");
            m2.add(menuItem4);
            m2.add(menuItem5);
            menuItem3.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    dispose();//不建议用这个关闭System.exit(0);
/*总之,直接调用`System.exit(0);`不是一个通用的或推荐的退出应用程序的方式,特别是在使用 GUI 框架开发的程序中。
可用setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);替换*/
        }
                }
            });
            setSize(300,300);
            setLocationRelativeTo(null);
            setResizable(false);
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            setVisible(true);
        }
    }

    public static void main(String[] args) {
        new cannian();
    }
}

14、利用java语言编程,使用thread类穿件线程,模拟播放50次音乐,主进程为玩游戏,在玩游戏线程进行了10次后,开始播放音乐。

class GameThread extends Thread {
    public void run() {
        for (int i = 1; i <= 10; i++) {
            System.out.println("Playing game for " + i + " time(s).");
        }
        MusicThread musicThread = new MusicThread();
        musicThread.start();
    }
}

class MusicThread extends Thread {
    public void run() {
        for (int i = 1; i <= 50; i++) {
            System.out.println("Playing music for " + i + " time(s).");
        }
    }
}

public class Main {
    public static void main(String[] args) {
        GameThread gameThread = new GameThread();
        gameThread.start();
    }
}
  class MyThread extends Thread {
        @Override
        public void run() {
            for (int i = 1; i <= 50; i++) {
                System.out.println("正在播放第" + i + "首音乐...");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("音乐播放完毕!");
        }
    }


    class GameThread extends Thread {
        @Override
        public void run() {
            for (int i = 1; i <= 10; i++) {
                System.out.println("正在玩游戏,已进行了" + i + "次...");
                try {
                    Thread.sleep(300);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("玩游戏结束!");

            // 等待 2 秒后再开始播放音乐
            try {
                System.out.println("等待 3秒后播放音乐...");
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            // 播放音乐线程
            MyThread musicThread = new MyThread();
            musicThread.start();
        }
    }

    public class Test14 {
        public static void main(String[] args) {
            // 玩游戏线程
            GameThread gameThread = new GameThread();
            gameThread.start();
        }
    }

15、利用java语言编程,使用ServerSocket类和Socket类,建立一个TCP网络服务器端程序。

public class Test15 {
    // 利用java语言编程,使用ServerSocket类和Socket类,建立一个TCP网络服务器端程序。
    public static void main(String[] args) throws IOException {
        ServerSocket ss = new ServerSocket(9090);
        System.out.println("等待接收数据...");
        Socket s = ss.accept();
        InputStream is = s.getInputStream();
        byte[] b = new byte[20];
        int len;
        while ((len = is.read()) != -1) {
            String str = new String(b, 0, len);
            System.out.println(str);
        }
        OutputStream os = s.getOutputStream();
        os.write("服务器端已收到。This is Server".getBytes());
        os.close();
        is.close();
        s.close();
        ss.close();
    }
}
public class TCPServer {
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(54188);
            System.out.println("服务器已启动,等待客户端连接...");

            while (true) {
                Socket socket = serverSocket.accept();
                System.out.println("客户端已连接,地址为:" + socket.getInetAddress().getHostAddress());

                InputStream is = socket.getInputStream();
                OutputStream os = socket.getOutputStream();

                byte[] buffer = new byte[1024];
                int length;
                while ((length = is.read(buffer)) != -1) {
                    os.write(buffer, 0, length);
                    os.flush();
                }

                os.close();
                is.close();
                socket.close();
                System.out.println("客户端已断开连接!");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

16、利用java语言编程,使用ServerSocket类和Socket类,建立一个TCP网络客户端程序。

public class Test16 {
    //使用ServerSocket类和Socket类,建立一个TCP网络客户端程序
    public static void main(String[] args) throws IOException {
        System.out.println("正在发送数据...");
        Socket s = new Socket(InetAddress.getByName("127.0.0.1"), 9090);
        OutputStream os = s.getOutputStream();
        os.write("服务器·端,你好! This is Client!".getBytes());
        s.shutdownOutput();//执行此方法,显示告诉服务器端发送完毕
        InputStream is = s.getInputStream();
        byte[] b = new byte[20];
        int len;
        while ((len = is.read()) != -1) {
            String str = new String(b, 0, len);
            System.out.println(str);
        }
        is.close();
        os.close();
        s.close();


    }
}
public class TCPClient {
    public static void main(String[] args) {
        String serverIP = "127.0.0.1"; // 这里填写服务器的IP地址
        int serverPort = 12345; // 这里填写服务器的端口号

        try {
            // 创建Socket对象,指定服务器的IP地址和端口号
            Socket socket = new Socket(serverIP, serverPort);

            // 获取输入流,用于接收服务器发送的数据
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            // 获取输出流,用于向服务器发送数据
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

            // 向服务器发送数据
            out.println("Hello, Server!");

            // 接收服务器返回的数据
            String response = in.readLine();
            System.out.println("Server response: " + response);

            // 关闭连接
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

17. 利用SQL语言写出下列操作。数据库名:student;表名:s_xueji;表内字段名:序号,姓名,籍贯,考试成绩。(本小题5分)

(1)在student表中插入一条记录:10,张三,江西省赣州市,80。

(2)把student表中“李明”的成绩修改为92。

(3)查询出班上及格同学信息并按籍贯的升序排列。

(4)删除“张百知”同学的记录。

-- 创建表
create  table  student1(
    id int comment '序号',
    name varchar(50) comment '姓名',
    place varchar(50) comment '籍贯',
    grade int comment '考试成绩'
)comment 's_xueji';
-- 输入信息
insert into student1(id, name, place, grade) VALUES (10,'张三','江西省赣州市',80),(11,'李明','江西',82),(12,'张百知','赣州市',98);
-- 修改
update student1 set grade=92 where name='李明';
-- 查询并升序
select *from student1 order by grade asc;
-- 删除
delete  from student1 where id=12 and name='张百知'and place='赣州市'and grade=98;

-- 创建表

create  table  student1(

    id int comment '序号',

    name varchar(50) comment '姓名',

    place varchar(50) comment '籍贯',

    grade int comment '考试成绩'

)comment 's_xueji';

-- 输入信息

insert into student1(id, name, place, grade) VALUES (10,'张三','江西省赣州市',80),(11,'李明','江西',82),(12,'张百知','赣州市',98);

-- 修改

update student1 set grade=92 where name='李明';

-- 查询并升序

select *from student1 order by grade asc;

-- 删除

delete  from student1 where id=12 and name='张百知'and place='赣州市'and grade=98;

你可能感兴趣的:(java,java,开发语言,算法)