内容学习于:edu.aliyun.com


1. 数字大小比较

  编写Java程序,输入3个整数,并求出3个整数的最大值和最小值。
如果要想进行数字的输入处理,那么应该保证输入错误的时候可以重新输入,那么为了可以达到重用的设计,应该准备一个单独的输入数据类。

a) 定义一个输入工作类:

package com.xzzz.e20200114_chapter1;

import java.util.Scanner;

public class InputUtil {

    private InputUtil() {
    }
    /** * 实现键盘接收数字的操作 * * @param prompt 提示信息 * @return 一个可以使用的数字 */
    public static int getInt(String prompt) {
        boolean flag = true;
        System.out.println(prompt);
        int num = 0;
        while (flag) {
            Scanner input = new Scanner(System.in);
            if (input.hasNextInt()) {
                num = input.nextInt();
                flag = false;
            } else {
                System.out.println("请重新输入");
            }
        }
        return num;
    }
}

b) 定义数据的输入处理

package com.xzzz.e20200114_chapter1.service;


public interface INumberService {
    /** * 输入数据并且返回输入数据的最大值和最小值 * * @param count 表示输入数据的个数 * @return 包含有两个内容,第一个是最大值,第二是最小值 */
    public int[] stat(int count);
}

c) 定义接口的实现子类

package com.xzzz.e20200114_chapter1.service.impl;

import com.xzzz.e20200114_chapter1.InputUtil;
import com.xzzz.e20200114_chapter1.service.INumberService;


public class NumberServiceImpl implements INumberService {
    @Override
    public int[] stat(int count) {
        int result[] = new int[2];
        int data[] = new int[count];
        for (int x = 0; x < data.length; x++) {
            data[x] = InputUtil.getInt("请输入第" + (x + 1) + "个数字");
        }
        result[0] = result[1] = data[0];
        for (int x = 0; x < data.length; x++) {
            if (result[0] < data[x]) {
                result[0] = data[x];
            }
            if (result[1] > data[x]) {
                result[1] = data[x];
            }
        }

        return result;
    }
}

d) 定义工厂类获取对象

package com.xzzz.e20200114_chapter1.factory;


import com.xzzz.e20200114_chapter1.service.INumberService;
import com.xzzz.e20200114_chapter1.service.impl.NumberServiceImpl;

public class Factory {
    private Factory(){}
    public static INumberService getInstance(){
        return new NumberServiceImpl();
    }
}

e) 编写测试类

package com.xzzz.e20200114_chapter1;


import com.xzzz.e20200114_chapter1.factory.Factory;
import com.xzzz.e20200114_chapter1.service.INumberService;

public class IOCaseDemo {
    public static void main(String[] args) {
        INumberService nsi = Factory.getInstance();
        int result[] = nsi.stat(3);
        System.out.println("最大的数字是:" + result[0] + "、最小的数字是:" + result[1]);
    }
}

结果:

请输入第1个数字
a
请重新输入
15
请输入第2个数字
36
请输入第3个数字
1
最大的数字是:36、最小的数字是:1

2. 文件保存

  从键盘输入文件的内容和要保存的文件名称,然后根据输入的名称创建文件,并将内容保存到文件中。
  在本程序里面只要求开发者保存的是文件名称而并没有设置文件路径,那么对于文件路径就应该在程序启动之前就准备好。

a) 定义一个文件操作的服务接口

package com.xzzz.e20200114_chapter1.service;

import java.io.File;

public interface IFileService {
    public static final String SAVE_DIR = "D:" + File.separator + "mldndata" + File.separator;
    /** * 定义文件的保存处理方法 * @return 保存成功返回true,否则返回false */
    public boolean save();
}

b) 定义输入字符串处理方法

package com.xzzz.e20200114_chapter1;

import java.util.Scanner;

public class InputUtil {

    private InputUtil() {
    }

    public static String getString(String prompt) {
        boolean flag = true;
        String str = null;
        while (flag) {
            System.out.println(prompt);
            Scanner input = new Scanner(System.in);
            if (input.hasNext(".+")) {
                str = input.next(".+");
                flag = false;
            } else {
                System.out.println("请重新输入");
            }
        }
        return str;
    }
}

c) 定义实现子类

package com.xzzz.e20200114_chapter1.service.impl;

import com.xzzz.e20200114_chapter1.InputUtil;
import com.xzzz.e20200114_chapter1.service.IFileService;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;

public class FileServiceImpl implements IFileService {
    private String name;
    private String content;
    public FileServiceImpl(){
        this.name = InputUtil.getString("请输入要保存的文件名称:");
        this.content = InputUtil.getString("请输入要保存的文件内容:");
    }
    @Override
    public boolean save() {
        File file = new File(IFileService.SAVE_DIR + this.name);
        PrintWriter out = null;
        try {
            out = new PrintWriter(new FileOutputStream(file));
            out.print(content);
            out.close();
        } catch (FileNotFoundException e) {
            return false;
        }
        return true;
    }
}

d) 建立工厂类

package com.xzzz.e20200114_chapter1.factory;


import com.xzzz.e20200114_chapter1.service.IFileService;
import com.xzzz.e20200114_chapter1.service.impl.FileServiceImpl;

public class Factory {
    private Factory(){}
    public static IFileService getInstance(){
        return new FileServiceImpl();
    }
}

e) 定义测试类

package com.xzzz.e20200114_chapter1;


import com.xzzz.e20200114_chapter1.factory.Factory;
import com.xzzz.e20200114_chapter1.service.IFileService;

import java.io.File;

public class IOCaseDemo {
    static {//项目创建时应该首先创建
        File file = new File(IFileService.SAVE_DIR);
        if (!file.exists()){
            file.mkdirs();
        }
    }
    public static void main(String[] args) {
        IFileService ifs = Factory.getInstance();
        System.out.println(ifs.save());
    }
}

结果:

请输入要保存的文件名称:
demo.txt
请输入要保存的文件内容:
阿恢复好好加减
true

3. 字符串逆序显示

  从键盘传入多个字符串到程序中,并将它们按逆序输出在屏幕上。
本程序之中应该考虑到如下的几种设计:

  • 既然字符串的内容可以随时修改,那么最好建立一个StringBuffer做保存;
  • 在进行数据处理的时候应该由用户自己来决定是否继续输入;

a) 定义字符串操作标准

package com.xzzz.e20200114_chapter1.service;

public interface IStringService {
    public void append(String str);//追加数据
    public String[] reverse();//翻转数据
}

b) 定义工厂类

package com.xzzz.e20200114_chapter1.factory;


import com.xzzz.e20200114_chapter1.service.IStringService;
import com.xzzz.e20200114_chapter1.service.impl.StringServiceImpl;

public class Factory {
    private Factory(){}
    public static IStringService getInstance(){
        return new StringServiceImpl();
    }
}

c) 定义实现子类

package com.xzzz.e20200114_chapter1.service.impl;

import com.xzzz.e20200114_chapter1.service.IStringService;

public class StringServiceImpl implements IStringService {
    private StringBuffer data = new StringBuffer();//方便字符串的修改

    @Override
    public void append(String str) {
        data.append(str).append("|");//方便分割
    }

    @Override
    public String[] reverse() {
        String [] result = this.data.toString().split("\\|") ;
        int head = 0;
        int tail = result.length-1;
        int center = result.length>>1;
        for (int i = 0;i<center;i++){
            String t = result[head];
            result[head] = result[tail];
            result[tail] = t;
            head++;
            tail--;
        }
        return result;
    }
}

d) 定义交互菜单

package com.xzzz.e20200114_chapter1;

import com.xzzz.e20200114_chapter1.factory.Factory;
import com.xzzz.e20200114_chapter1.service.IStringService;

import java.util.Arrays;

public class Menu {
    private IStringService iss = Factory.getInstance();

    public Menu() {
        System.out.println("【1】追加字符串数据");
        System.out.println("【2】字符串翻转");
        System.out.println("【-1】退出");
        System.out.println("\n\n\n");

        this.choose();

    }

    public void choose() {
        String choose = InputUtil.getString("请进行选择:");

        switch (choose) {
            case "1": {
                iss.append(InputUtil.getString("请输入内容:"));
                this.choose();
            }
            case "2": {
                String result[] = iss.reverse();
                System.out.println(Arrays.toString(result));
                this.choose();
            }
            case "-1": {
                System.out.println("欢迎下次操作!!");
                System.exit(1);//退出
            }
            default: {
                System.out.println("您输入的选项有误!!");
            }
        }
    }
}

e) 定义测试类

package com.xzzz.e20200114_chapter1;


public class IOCaseDemo {
    public static void main(String[] args) {
        new Menu();//启动菜单

    }
}

结果:

【1】追加字符串数据
【2】字符串翻转
【-1】退出
请进行选择:
1
请输入内容:
adad
请进行选择:
1
请输入内容:
dadafa
请进行选择:
1
请输入内容:
ljnxn
请进行选择:
1
请输入内容:
uouq
请进行选择:
2
[uouq, ljnxn, dadafa, adad]
请进行选择:
-1
欢迎下次操作!!

4. 数据排序处理

  从键盘输入以下的数据: “TOM:89|JERRY:90|TONY:59.9",数据格式为“姓名:成绩|姓名:成绩|姓名:成绩”,对输入的内容按成绩进行排序,并将排序结果按照成绩由高到低排序。
  对于排序的处理肯定使用Comparable接口完成,同时利用Arrays类来处理,这里面唯一不同的地方就在于此时的数据显示需要通过键盘输入。

a) 建立Student类

package com.xzzz.e20200114_chapter1;
public class Student implements Comparable<Student>{
    private String name;
    private double score;

    public Student(String name, double score) {
        this.name = name;
        this.score = score;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", score=" + score +
                '}';
    }

    @Override
    public int compareTo(Student o) {
        if (this.score>o.score){
            return -1;
        }
        else if (this.score<o.score){
            return 1;
        }
        else {
            return 0;
        }
    }
}

b) 建立数据输入处理接口

package com.xzzz.e20200114_chapter1.service;

import com.xzzz.e20200114_chapter1.Student;

public interface IStudentService {
    public Student[] getdata();//获取排序后的数据
}

c) 建立接口实现的子类

package com.xzzz.e20200114_chapter1.service.impl;


import com.xzzz.e20200114_chapter1.Student;
import com.xzzz.e20200114_chapter1.service.IStudentService;

import java.util.Arrays;

public class StudentServiceImpl implements IStudentService {
    private String content;
    private Student[] students;
    public StudentServiceImpl(String content){
        this.content = content;
        this.haddle();
    }

    private void haddle() {
        String result[] = this.content.split("\\|");
        this.students = new Student[result.length];
        for (int i = 0;i<result.length;i++){
            String [] t = result[i].split(":");
            this.students[i] = new Student(t[0],Double.parseDouble(t[1]));
        }
    }

    @Override
    public Student[] getdata() {
        Arrays.sort(students);
        return students;
    }
}

d) 建立工厂类

package com.xzzz.e20200114_chapter1.factory;


import com.xzzz.e20200114_chapter1.InputUtil;
import com.xzzz.e20200114_chapter1.service.IStudentService;
import com.xzzz.e20200114_chapter1.service.impl.StudentServiceImpl;

public class Factory {
    private Factory(){}
    public static IStudentService getInstance(){
        return new StudentServiceImpl(InputUtil.getString("请输入内容:"));
    }
}

e) 建立测试类

package com.xzzz.e20200114_chapter1;


import com.xzzz.e20200114_chapter1.factory.Factory;

import java.util.Arrays;

public class IOCaseDemo {
    public static void main(String[] args) {
        System.out.println(Arrays.toString(Factory.getInstance().getdata()));
    }
}

结果:

TOM:89|JERRY:90|TONY:59.9
[Student{name=‘JERRY’, score=90.0}, Student{name=‘TOM’, score=89.0}, Student{name=‘TONY’, score=59.9}]

5. 数据排序处理深入

  将上一题中的内容进行扩展,可以将全部输入的信息保存在文件中,还可以添加信息,并可以显示全部的数据。
  如果此时要进行内容的保存,那么首先一定要确认好所有输入数据的保存位置,所有的数据之间如果要想沿用之前的设计的结构,则数据文件里面的保存应该做到格式统一,即:“姓名:成绩|”的形式进行存储,而在进行数据添加的时候可以添加两类数据:“单独的内容”、 “一组内容”。还有一个前提:暂时不去考虑数据过大的问题。

a) 设置一个文件处理类

package com.xzzz.e20200114_chapter1.util;

import java.io.*;
import java.util.Scanner;

public class FileUtil {
    private FileUtil() {}

    /** * 文件读取操作 * @param file 读取的文件路径 * @return 返回文件内容 */

    public static String load(File file) {
        Scanner sc = null;
        String str = null;
        try {
            sc = new Scanner(file);//加载文件
            if (sc.hasNext()) {
                str = sc.next();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (sc != null) {
                sc.close();
            }
        }
        return str;
    }

    /** * 文件内容的追加操作 * * @param file 保存的文件路径 * @param str 追加的字符串 */
    public static void append(File file, String str) {
        PrintStream ps = null;
        try {
            ps = new PrintStream(new FileOutputStream(file, true));
            ps.print(str);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (ps != null) {
                ps.close();
            }
        }

    }

}

b) 扩充IStudentService方法

package com.xzzz.e20200114_chapter1.service;

import com.xzzz.e20200114_chapter1.Student;

public interface IStudentService {
    public void append(String str);//追加内容并保存到文件
    public Student[] getdata();//获取排序后的数据
}

c) 修改实现子类的功能

package com.xzzz.e20200114_chapter1.service.impl;


import com.xzzz.e20200114_chapter1.Student;
import com.xzzz.e20200114_chapter1.service.IStudentService;
import com.xzzz.e20200114_chapter1.util.FileUtil;

import java.io.File;
import java.util.Arrays;

public class StudentServiceImpl implements IStudentService {
    private static final File SAVE_FILE = new File("D:"+File.separator+"student.txt");
    private String content;
    private Student[] students;
    public StudentServiceImpl(){
        this.content = FileUtil.load(SAVE_FILE);//读取已有的文件内容
        this.haddle();
    }

    private void haddle() {
        String result[] = this.content.split("\\|");
        this.students = new Student[result.length];
        for (int i = 0;i<result.length;i++){
            String [] t = result[i].split(":");
            this.students[i] = new Student(t[0],Double.parseDouble(t[1]));
        }
    }

    @Override
    public void append(String str) {
        if (str.startsWith("|")){
            str = str.substring(1);//把前面的分割符去掉
        }
        if(!str.endsWith("|")){
            str  = str +"|";
        }
        FileUtil.append(SAVE_FILE,str);
    }

    @Override
    public Student[] getdata() {
        Arrays.sort(students);
        return students;
    }
}

d) 定义一个菜单

package com.xzzz.e20200114_chapter1;

import com.xzzz.e20200114_chapter1.factory.Factory;
import com.xzzz.e20200114_chapter1.service.IStudentService;

import java.util.Arrays;

public class Menu {

    public Menu() {
        System.out.println("【1】追加字符串数据");
        System.out.println("【2】字符串排序");
        System.out.println("【-1】退出");
        System.out.println("\n\n\n");

        this.choose();

    }

    public void choose() {
        String choose = InputUtil.getString("请进行选择:");

        switch (choose) {
            case "1": {
                IStudentService iss = Factory.getInstance();
                iss.append(InputUtil.getString("请输入内容:"));
                this.choose();
            }
            case "2": {
                IStudentService iss = Factory.getInstance();
                Student result[] = iss.getdata();
                System.out.println(Arrays.toString(result));
                this.choose();
            }
            case "-1": {
                System.out.println("欢迎下次操作!!");
                System.exit(1);//退出
            }
            default: {
                System.out.println("您输入的选项有误!!");
            }
        }
    }
}

e) 修改工厂类

package com.xzzz.e20200114_chapter1.factory;


import com.xzzz.e20200114_chapter1.service.IStudentService;
import com.xzzz.e20200114_chapter1.service.impl.StudentServiceImpl;

public class Factory {
    private Factory() {
    }

    public static IStudentService getInstance() {
        return new StudentServiceImpl();
    }
}
f)	修改测试类
package com.xzzz.e20200114_chapter1;


public class IOCaseDemo {
    public static void main(String[] args) {
        new Menu();
    }
}

结果:

【1】追加字符串数据
【2】字符串排序
【-1】退出
请进行选择:
1
请输入内容:
王五:99
请进行选择:
1
请输入内容:
李四:12
请进行选择:
2
[Student{name=‘王五’, score=99.0}, Student{name=‘张三’, score=85.0}, Student{name=‘李四’, score=12.0}]
请进行选择:
-1
欢迎下次操作!!

6. 奇偶数统计

  编写程序,当程序运行后,根据屏幕提示输入一个数字字符串,输入后统计有多少个偶数数字和奇数数字
  本质的流程就是进行每一个字符串的拆分,而后进行数字的转换处理。

a) 定义事务处理接口

package com.xzzz.e20200114_chapter1.service;
public interface INumberService {
    public int [] stat();
}

b) 定义事务处理接口

package com.xzzz.e20200114_chapter1.service.impl;

import com.xzzz.e20200114_chapter1.InputUtil;
import com.xzzz.e20200114_chapter1.service.INumberService;

public class NumberServiceImpl implements INumberService {
    @Override
    public int[] stat() {
        int [] result = new int[] {0,0};
        String str = InputUtil.getString("请输入数字:") ;
        String data [] = str.split("");
        for(String t :data){
            if (Integer.parseInt(t) %2 ==0){
                result[0] ++;
            }
            else {
                result[1]++;
            }
        }
        return result;
    }
}

c) 定义工厂类

package com.xzzz.e20200114_chapter1.factory;


import com.xzzz.e20200114_chapter1.service.INumberService;
import com.xzzz.e20200114_chapter1.service.impl.NumberServiceImpl;

public class Factory {
    private Factory() {
    }

    public static INumberService getInstance() {
        return new NumberServiceImpl();
    }
}

d) 定义测试类

package com.xzzz.e20200114_chapter1;


import com.xzzz.e20200114_chapter1.factory.Factory;

public class IOCaseDemo {
    public static void main(String[] args) {
        int [] result = Factory.getInstance().stat();
        System.out.println("偶数:" + result[0]+"、奇数:"+result[1]);
    }
}

结果:

请输入数字:
1234567
偶数:3、奇数:4