1. 程式人生 > >PAT乙級——1081(字串判斷)Java實現

PAT乙級——1081(字串判斷)Java實現

題目:檢查密碼 (15 分)

本題要求你幫助某網站的使用者註冊模組寫一個密碼合法性檢查的小功能。該網站要求使用者設定的密碼必須由不少於6個字元組成,並且只能有英文字母、數字和小數點 .,還必須既有字母也有數字。

輸入格式:
輸入第一行給出一個正整數 N(≤ 100),隨後 N 行,每行給出一個使用者設定的密碼,為不超過 80 個字元的非空字串,以回車結束。

輸出格式:
對每個使用者的密碼,在一行中輸出系統反饋資訊,分以下5種:

如果密碼合法,輸出Your password is wan mei.
如果密碼太短,不論合法與否,都輸出Your password is tai duan le.


如果密碼長度合法,但存在不合法字元,則輸出Your password is tai luan le.
如果密碼長度合法,但只有字母沒有數字,則輸出Your password needs shu zi.
如果密碼長度合法,但只有數字沒有字母,則輸出Your password needs zi mu.

輸入樣例:
5
123s
zheshi.wodepw
1234.5678
WanMei23333
pass*word.6

輸出樣例:
Your password is tai duan le.
Your password needs shu zi.
Your password needs zi mu.
Your password is wan mei.
Your password is tai luan le.

題目分析及實現

這個題目不難,一開始使用Scanner 來獲取輸入的資料,有一個用例一直通不過,後來發現是使用 next() 方法時,使用者有時候在一行裡會輸出空格,會被不小心分離,使用 nextline() 的話一直在等待下一個的輸入,有問題。

後改用 BufferedReader() 來獲取輸入,逐行讀入,解決。還是這個好用,以後試著多用這個。

另還有一個思路也不錯,數一下每一個密碼中字母的個數,點的個數,數字的個數,相加小於總長度,則有非法字元,沒有數字或者沒有字母,則也可以通過個數判斷。

//AC
import java.io.BufferedReader;
import
java.io.InputStreamReader; public class Main { public static void main(String[] args)throws Exception { BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in)); int num = Integer.parseInt(bReader.readLine()); String[] password = new String[num]; for (int i = 0; i < num; i++) password[i] = bReader.readLine(); bReader.close(); Loop:for (int i = 0; i < num; i++) { if (password[i].length() < 6) { System.out.println("Your password is tai duan le."); continue Loop; } else { int number = 0;//判斷數字個數 int word = 0;//判斷字母個數 for (int j = 0; j < password[i].length(); j++) { char temp = password[i].charAt(j); if (temp < '.' || (temp > '.' && temp < '0') || (temp > '9' && temp < 'A') || (temp > 'Z' && temp < 'a') || temp > 'z') { //若存在其他字元 System.out.println("Your password is tai luan le."); continue Loop; } else if (number == 0 && temp <= '9' && temp >= '0') number++; else if (word == 0 && ((temp <= 'Z' && temp >= 'A') || (temp <= 'z' && temp >= 'a'))) word++; } if(number == 0) { System.out.println("Your password needs shu zi."); continue Loop; } else if (word == 0) { System.out.println("Your password needs zi mu."); continue Loop; } else System.out.println("Your password is wan mei."); } } } }