驗證碼題目中碰到的問題
阿新 • • 發佈:2019-01-06
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判斷 不然會空指標異常。