第20 章 : JavaIO编程案例

91 数字大小比较

输入3个整数,并求出3个整数最大值和最小值

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


class InputUtil {
/**
* 读取指定个数的整数输入
*
* @param num 指定要输入的整数个数
* @return 所有读取的整数数组
* @throws IOException
*/
public static int[] getIntList(int num) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

System.out.println("请输入" + num + "个整数:");

int[] list = new int[num];
int count = 0;

while (count < num) {
String msg = reader.readLine();

if (msg.matches("\\d+")) {
list[count++] = Integer.parseInt(msg);
} else {
System.out.println("请输入整数");
}
}

reader.close();
return list;
}
}


class NumberUtil {
/**
* 获取int 型数组中最大值和最小值
*
* @param list 整数数组
* @return int[] {max, min}
*/
public static int[] getMaxMin(int[] list) {
int max = list[0];
int min = list[0];

for (int x : list) {
if (x > max) {
max = x;
}
if (min > x) {
min = x;
}
}
return new int[]{max, min};
}

}


class Demo {
public static void main(String[] args) throws IOException {

// 读取3个数据
int[] list = InputUtil.getIntList(3);
int[] data = NumberUtil.getMaxMin(list);

System.out.println("最大值:" + data[0]);
System.out.println("最小值:" + data[1]);

}
}

92 文件保存

从键盘输入文件名和文件内容,然后将文件内容保存到文件中

1、定义接口

2、工具类

3、实现接口类

4、工厂类

5、测试函数

import java.io.*;


class InputUtil {
private static final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

public static String getInput(String prompt) {

System.out.println(prompt);
String msg = null;

while (true) {
try {
msg = reader.readLine();
if (!"".equals(msg)) {
break;
} else {
System.out.println("请输入非空字符串:");
}
} catch (IOException e) {

}
}
return msg;
}
}

interface IFileService {
public static final String FILE_DIR = "demo";

public boolean save();
}


class FileServiceImpl implements IFileService {

private String filename;
private String content;

public FileServiceImpl() {
this.filename = InputUtil.getInput("请输入文件名");
this.content = InputUtil.getInput("请输入文件内容");
}

@Override
public boolean save() {
String fullname = this.FILE_DIR + File.separator + this.filename;

PrintWriter writer = null;
try {
writer = new PrintWriter(fullname);
writer.print(this.content);

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

}
return false;
}
}


class Factory{
private Factory(){}

public static FileServiceImpl getInstance(){
return new FileServiceImpl();

}
}

class Demo {
// 项目启动时创建文件夹
static {
File file = new File(IFileService.FILE_DIR);
if (!file.exists()) {
file.mkdirs();
}
}

public static void main(String[] args) throws IOException {
FileServiceImpl fileService = Factory.getInstance();
fileService.save();
}
}

93 字符串逆序显示

键盘传入多个字符串到程序中,并将它们按照逆序输出到屏幕

设计考虑:

1、字符串内容随时修改,使用StringBuffer

2、由用户自己决定是否继续输入

实现步骤

1、定义接口 操作标准

2、定义实现类

3、定义工厂类

4、编写辅助类

5、编写测试类

实现代码

IStringService.java

public interface IStringService {
public void append(String str);
public String[] reverse();
}

StringServiceImpl.java

public class StringServiceImpl implements IStringService{
private StringBuffer data = new StringBuffer();

public void append(String str){
this.data.append(str).append("|");
}

public String[] reverse(){
String[] list = this.data.toString().split("\\|");

String[] tmp = new String[list.length];

for(int i=0; i<list.length; i++){
tmp[i] = list[list.length - i - 1];
}

return tmp;
}
}

InputUtil.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

class InputUtil {
private static final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

public static String getString(String prompt) {

System.out.println(prompt);
String msg = null;

while (true) {
try {
msg = reader.readLine();
if (!"".equals(msg)) {
break;
} else {
System.out.println("请输入非空字符串:");
}
} catch (IOException e) {

}
}
return msg;
}

public static void main(String[] args) {
System.out.println(InputUtil.getString("请输入"));
}
}

Factory.java

class Factory{
private Factory(){}

public static StringServiceImpl getInstance(){
return new StringServiceImpl();

}
}

Menu.java

import java.util.Arrays;

public class Menu {
private StringServiceImpl stringServiceImpl;

public Menu() {
this.stringServiceImpl = Factory.getInstance();
this.choose();
}

public void choose() {
help();

String msg = InputUtil.getString("请选择:");
switch (msg) {
case "1":
this.stringServiceImpl.append(InputUtil.getString("请输入字符串:"));
choose();

case "2":
System.out.println(Arrays.toString(this.stringServiceImpl.reverse()));
choose();

case "0":
System.exit(0);

default:
choose();
}

}

public static void help() {
System.out.println("[1]输入内容:");
System.out.println("[2]输出反转内容:");
System.out.println("[0]退出");
}
}

Demo.java

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

94 数据排序处理

键盘输入数据 ​​姓名:成绩|姓名:成绩​

eg:

Tom:89|Jack:91|Tony:86

按照成绩由高到低排序

思路:

Comparable + Arrays

代码实现

IStudentService.java

public interface IStudentService {
Student[] getData();
}

Student.java

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 + ", " + score + '>';
}

@Override
public int compareTo(Student obj) {
return Double.compare(obj.score, this.score);
}
}

StudentServiceImpl.java

import java.util.Arrays;

public class StudentServiceImpl implements IStudentService {
private String content;
private Student[] students;

public StudentServiceImpl(String content) {
this.content = content;
this.handle();
}

private void handle(){
String[] list = this.content.split("\\|");
this.students = new Student[list.length];

for(int i=0; i<list.length; i++){
String[] items = list[i].split(":");
this.students[i] = new Student(items[0], Double.parseDouble(items[1]));
}
}

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

Factory.java

public class Factory {
private Factory(){}

public static StudentServiceImpl getInstance(){
return new StudentServiceImpl(InputUtil.getString("请输入数据:"));
}
}

Demo.java

import java.util.Arrays;

public class Demo {
public static void main(String[] args) {
// Tom:89|Jack:91|Tony:86
System.out.println(Arrays.toString(Factory.getInstance().getData()));
// [Student<Jack, 91.0>, Student<Tom, 89.0>, Student<Tony, 86.0>]
}
}

95 数据排序处理深入

扩展上一节内容,将输入信息保存到文件中,还可以添加信息,并且查看全部数据

确认保存位置

格式统一

FileUtil.java文件读取工具类

package util;

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

public class FileUtil {
public static String read(File file) throws FileNotFoundException {
Scanner scanner = new Scanner(file);
StringBuilder contents = new StringBuilder();

while (scanner.hasNext()) {
contents.append(scanner.next());
}

scanner.close();

return contents.toString();
}

public static void append(File file, String content) throws IOException {
PrintWriter writer = new PrintWriter(new FileWriter(file, true));
writer.write(content);
writer.close();
}

public static void save(File file, String content) throws IOException {
PrintWriter writer = new PrintWriter(file);
writer.write(content);
writer.close();
}

public static void main(String[] args) throws IOException {
File file = new File("demo.txt");

FileUtil.save(file, "你好");
FileUtil.append(file, "你也好");
System.out.println(FileUtil.read(file));
}
}

96 奇偶数统计

输入字符串拆分后统计奇数,偶数个数

接口INumberService.java

public interface INumberService {
public int[] handle();
}

实现类 NumberServiceImpl.java

import util.InputUtil;

public class NumberServiceImpl implements INumberService{
private String str;

public NumberServiceImpl(){
this.str = InputUtil.getString("请输入数字串:");
}

@Override
public int[] handle() {

String[] numbers = this.str.split("");

// 偶数, 奇数
int[] result = new int[]{0, 0};
for(String num : numbers){
if(Integer.parseInt(num) % 2 == 0){
result[0] ++;
} else{
result[1] ++;
}
}
return result;
}
}

测试类 Demo.java

import java.util.Arrays;

public class Demo {
public static void main(String[] args) {
System.out.println(Arrays.toString(new NumberServiceImpl().handle()));

// 1234567890
// [5, 5]
}
}

97 用户登录

输入用户名和密码 root 123456

如果没有输入则提示输入

输入错误3次退出

提示登录成功

真实业务只实现核心功能,辅助逻辑处理交给代理控制

接口类

IUserService

isExit

login

实现类

UserServiceImpl

代理类

UserServiceProxy

工厂类

Factory

测试类

Demo

实现代码

IUserService.java

public interface IUserService {
public boolean isExit();
public boolean login(String name, String password);
}

UserServiceImpl.java

public class UserServiceImpl implements IUserService{
private int tryCount = 0;

@Override
public boolean isExit() {
// 超过三次错误
return this.tryCount >= 3;
}

/**
* 实现核心逻辑
*/
@Override
public boolean login(String name, String password) {
this.tryCount ++;

if("root".equals(name) && "123456".equals(password)){
return true;
} else{
return false;
}
}
}

UserServiceProxy.java

import util.InputUtil;

public class UserServiceProxy implements IUserService {
private IUserService userService;

public UserServiceProxy(IUserService userService) {
this.userService = userService;
}

@Override
public boolean isExit() {
return this.userService.isExit();
}

/**
* 实现辅助逻辑
*/
@Override
public boolean login(String name, String password) {
while (!this.isExit()) {
String inputName = InputUtil.getString("请输入用户名:");
String inputPassword = InputUtil.getString("请输入密码:");

if (this.userService.login(inputName, inputPassword)) {
System.out.println("登录成功");
System.exit(0);
} else {
System.out.println("用户名或密码错误,请重试");
}
}

System.out.println("重试次数过多,请稍后重试");
return true;

}
}

Factory.java

import util.InputUtil;

public class Factory {
private Factory(){}

public static IUserService getInstance(){
return new UserServiceProxy(new UserServiceImpl());
}
}

Demo.java

public class Demo {
public static void main(String[] args) {
Factory.getInstance().login(null, null);

}
}

98 投票选举

1、输入候选人名单

2、统计每个候选人票数

3、显示最终投票结果

思路分析

1、定义数据结构:
Student
name
sid
vote

2、操作接口类
IVoteService
void inc(int sid)
Student[] result() 排序数据
Student[] getData() 未排序数据

3、实现类
VoteServiceImpl

4、工厂类
Factory

5、测试类
Demo

实现代码

数据结构 Student.java

public class Student implements Comparable<Student> {
private String name;
private int sid;
private int vote;

public Student(String name, int sid, int vote) {
this.name = name;
this.sid = sid;
this.vote = vote;
}

public String getName() {
return name;
}

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

public int getSid() {
return sid;
}

public void setSid(int sid) {
this.sid = sid;
}

public int getVote() {
return vote;
}

public void setVote(int vote) {
this.vote = vote;
}

@Override
public int compareTo(Student obj) {
return obj.vote - this.vote;
}

@Override
public String toString() {
return String.format("[%s] %s - %s", sid, name, vote);
}
}

接口 IVoteService.java

public interface IVoteService {
public void inc(int sid);

public Student result();

public Student[] getData();
}

实现类 VoteServiceImpl.java

import util.InputUtil;

import java.util.Arrays;

public class VoteServiceImpl implements IVoteService {
private Student[] students;

public VoteServiceImpl() {
this.students = new Student[]{
new Student("张三", 1, 0),
new Student("李四", 2, 0),
new Student("王五", 3, 0),
};
}

@Override
public void inc(int sid) {
for(Student s : this.students){
if(s.getSid() == sid){
s.setVote(s.getVote() + 1);
}
}
}

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

@Override
public Student[] getData() {
return this.students;
}
}

工产类 Factory.java

public class Factory {
private Factory(){}

public static IVoteService getInstance(){
return new VoteServiceImpl();
}
}

菜单类 Menu.java

import util.InputUtil;

import java.util.Arrays;

public class Menu {
private IVoteService voteService;

public Menu() {
this.voteService = Factory.getInstance();
this.choose();
}

public void choose(){
this.help();
String num = InputUtil.getString("请选择:");

switch (num){
case "1":
String sid = InputUtil.getString("请输入候选人id");
this.voteService.inc(Integer.parseInt(sid));
this.choose();
break;
case "2":
System.out.println(Arrays.toString(this.voteService.getData()));
this.choose();
break;
case "3":
System.out.println(this.voteService.result());
this.choose();
break;
case "0":
System.out.println("拜拜...");
System.exit(0);
default:
help();
this.choose();
}
}

public void help(){
System.out.println("【1】候选人增加票数");
System.out.println("【2】显示投票统计");
System.out.println("【3】显示统计结果");
System.out.println("【0】退出系统");
}
}

测试类 Demo.java

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