C#簡單的四位純數字驗證碼


驗證碼練手,整型、四位驗證碼

大體意思就是:四位純數字驗證,只要驗證不成功就無限驗證

剛開始在糾結怎么讓整個過程循環起來,什么循環放到最外層,其實就是一個循環,看來自己的循環練習的還是不夠多,不夠靈活

看代碼

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace _11._1練習
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             while (true)
14             {
15 
16 
17                 //隨機驗證碼     整型
18                 Random x = new Random();
19                 int ranx = x.Next(1000, 9999);
20 
21 
22 
23 
24                 //把整型的隨機數轉換成字符串,方便進行字符串比對
25                 string ran = Convert.ToString(ranx);
26 
27 
28 
29                 //打印驗證碼     
30                 Console.WriteLine("驗證碼:" + ranx);
31                 Console.WriteLine();
32                 Console.Write("驗  證:");
33 
34 
35 
36 
37                 //獲取用戶輸入的內容
38                 string user = Console.ReadLine();
39 
40 
41 
42                 //防止用戶誤操作,把空格替換成空字符串
43                 string str = user.Replace(" ", "");
44 
45 
46 
47 
48                 //檢測用戶輸入內容的長度,長度符合---下一步,長度不符合---長度錯誤
49                 int strleg = str.Length;
50                 if (strleg == 4)
51                 {
52                     //開始比對字符串
53 
54                     if (str == ran)
55                     {
56                         Console.WriteLine();
57                         Console.ForegroundColor = ConsoleColor.Red;
58                         Console.WriteLine("驗證成功!!!");
59                         break;
60                     }
61                     else
62                     {
63                         Console.ForegroundColor = ConsoleColor.Red;
64                         Console.WriteLine();
65                         Console.WriteLine("輸入錯誤!!!");
66                         Console.ForegroundColor = ConsoleColor.White;
67                         Console.WriteLine();
68                     }
69                 }
70                 else
71                 {
72                     Console.ForegroundColor = ConsoleColor.Red;
73                     Console.WriteLine();
74                     Console.WriteLine("長度錯誤!!!");
75                     Console.ForegroundColor = ConsoleColor.White;
76                     Console.WriteLine();
77                 }
78             }
79 
80 
81 
82 
83             Console.ReadLine();
84         }
85     }
86 }

為了方便檢查代碼,加了挺多的注釋,並且每個過程都會空格開,個人感覺這個習慣挺好,因為在檢查代碼或者是卡斷點的時候,自己的思路更清晰、更透徹

嗯,放一張效果圖吧,小黑窗其實也蠻有意思的

還是需要多練習,鍵盤上貼紙了,看什么時候能把鍵盤紙敲爛


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM