4、[简答题] 【高效字符流和集合的综合使用】 描述: 分析以下需求,并用代码实现 实现一个验证码小程序,要求如下: 1. 在项目根目录下新建一个文件:data.txt,键盘录入3个字符串验证码,并存入data.txt中,要求一个验证码占一行; 2. 键盘录入一个需要被校验的验证码,如果输入的验证码在data.txt中存在:在控制台提示验证成功,如果不存在控制台提示验证失败

4、[简答题] 【高效字符流和集合的综合使用】
描述:
分析以下需求,并用代码实现
实现一个验证码小程序,要求如下:
1. 在项目根目录下新建一个文件:data.txt,键盘录入3个字符串验证码,并存入data.txt中,要求一个验证码占一行;
2. 键盘录入一个需要被校验的验证码,如果输入的验证码在data.txt中存在:在控制台提示验证成功,如果不存在控制台提示验证失败

package day_10_test;

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

//4、[简答题] 【高效字符流和集合的综合使用】
//描述:
//分析以下需求,并用代码实现
//实现一个验证码小程序,要求如下:
//1. 在项目根目录下新建一个文件:data.txt,键盘录入3个字符串验证码,并存入data.txt中,要求一个验证码占一行;
//2. 键盘录入一个需要被校验的验证码,如果输入的验证码在data.txt中存在:在控制台提示验证成功,如果不存在控制台提示验证失败
public class Test04 {
    public static void main(String[] args) throws IOException {
        //1.在根目录下新建一个文件:date.txt
        //2.键盘输入3个字符串验证码,并存入data.txt中,
        //3.一个验证码一行
        writeCode();
        //键盘录入一个验证码,判断是否在data.txt中存在
        verificationCode();
    }
    public static void verificationCode() throws IOException {
        //创建ArrayList集合,用于存储文件中的3个验证码
        ArrayList<String> list = new ArrayList<>();
        BufferedReader br = new BufferedReader(new FileReader(new File("data.txt")));
        String line = null;
        //循环读取每一行
        while ((line = br.readLine()) != null) {
            list.add(line);
        }
        br.close();
        //创建键盘输入
        Scanner sc = new Scanner(System.in);
        String code = sc.nextLine();
        //验证码判断
        if (list.contains(code)) {
            System.out.println("验证成功");
        }else {
            System.out.println("验证码失败");
        }
    }

    /**
     * 录入字符串验证码
     *
     */
    public static void writeCode() throws IOException {
        //创建高效字符缓冲输出流对象并和data.txt文件关联
        BufferedWriter bis = new BufferedWriter(new FileWriter(new File("data.txt")));
        
        String str = null;
        Scanner scanner = new Scanner(System.in);
        for (int i = 0; i <3; i++) {
            System.out.println("请输入"+(i+1)+"个字符串验证码");
            str = scanner.nextLine();
            bis.write(str);
            bis.newLine();//写完一个换行
        }

        bis.close();
    }
}
posted @ 2022-06-02 16:55  不只是智能hello  阅读(87)  评论(0)    收藏  举报