验证码题目中碰到的问题

for循环中的String 不能直接被判断为 null 模式,因为 判断为 null模式会导致程序报错。判断写出空指针异常报错。应该的方式是 加一个判断。把代码判断的语句直接写到if语句中。

我的错误代码是:
package com.guang.DataFrom;

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

public class DataFrom {
public static void main(String[] args) throws IOException{
File f = new File(“D:\data.txt”);
f.createNewFile();
Scanner sc = new Scanner(System.in);
String[] strs = new String[3];

    for(int a = 0 ;a < 3;a++){
        System.out.println("请输入第"+ (a+1) +"个验证码:");
        String str = sc.next();
        strs[a] = str;
    }

    BufferedWriter bo = new BufferedWriter(new FileWriter(f));

    for(int a = 0; a < 3; a++){
        bo.write(strs[a]);
        bo.write(System.lineSeparator());
    }

    bo.flush();
    bo.close();

    BufferedReader br = new BufferedReader(new FileReader(f));

    System.out.println("请输入登录验证码:");
    String yan = sc.next();
    String line;
    while( true ){
        if( br.readLine().equals(yan)){
        	line = br.readLine();
            System.out.println("验证码存在");
            break;
        }else if( line == null ){
            System.out.println("验证码不存在");
            break;
        }
        }
    br.close();

    }
}

我的正确代码是:

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

public class DataFrom {
public static void main(String[] args) throws IOException{
File f = new File(“D:\data.txt”);
f.createNewFile();
Scanner sc = new Scanner(System.in);
String[] strs = new String[3];

    for(int a = 0 ;a < 3;a++){
        System.out.println("请输入第"+ (a+1) +"个验证码:");
        String str = sc.next();
        strs[a] = str;
    }

    BufferedWriter bo = new BufferedWriter(new FileWriter(f));

    for(int a = 0; a < 3; a++){
        bo.write(strs[a]);
        bo.write(System.lineSeparator());
    }

    bo.flush();
    bo.close();

    BufferedReader br = new BufferedReader(new FileReader(f));

    System.out.println("请输入登录验证码:");
    String yan = sc.next();

    while( true ){
        if( br.readLine().equals(yan)){
            System.out.println("验证码存在");
            break;
        }else if( br.readLine() != null ){
            System.out.println("验证码不存在");
            break;
        }
        }
    br.close();

    }
}

String语句不能作为null判断 不然会空指针异常。

猜你喜欢

转载自blog.csdn.net/u014452148/article/details/85781251