国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
JAVA implements user lottery
Requirement analysis
Results achieved
Notes
Home Java JavaBase Detailed explanation of JAVA implementation of user lottery

Detailed explanation of JAVA implementation of user lottery

Nov 25, 2020 pm 05:17 PM
java lottery

java basic tutorial column introduces the method of implementing user lottery:

Detailed explanation of JAVA implementation of user lottery

JAVA implements user lottery

Requirement analysis

1) Implement three basic functions: login, registration, and lottery.
2) Login: The user enters the account and password to log in. After entering the account, it will match the registered user. If the entered user does not exist, exit. There are three opportunities to enter the password. After successful login, the main interface will display the account of the logged in user. information.
3) Registration: The user first enters the account name. The system checks whether the name exists. If it exists, the user is asked to change the name. Otherwise, enter the password. The password requires a 6-digit string. After successful registration, the system randomly assigns a A four-digit ID number that is unique from existing users.
4) Lottery: Prerequisite for function implementation: The user must be logged in. When this prerequisite is met, the system randomly selects 5 different users from existing users and marks them as lucky users, and determines whether the logged-in user has been selected.
5) Data storage: Use the file system, import the java.io.* package,
6) Data structure: Login user information is stored in ArrayList, lucky user number and id are stored in HasMap where id is Key and name is Value.

Results achieved

1) Login:
2) Registration:
3) Lottery:

Notes

	運行代碼之前務(wù)必在user.txt中創(chuàng)建五個以上的用戶。
import?java.util.Scanner;import?java.util.ArrayList;import?java.io.*;import?java.util.StringTokenizer;public?class?Dos?{
????static?boolean?logined=false;
????public?static?void?main(String[]?args)?{
????????User?user=new?User();
????????int?k=0;
????????while(?(k=Main(user))>=1&&k<5){
            switch (k){
                case 1:
                    System.out.print((k=user.login(user))==-1?"此用戶不存在!\n":"");
                    System.out.print((k==-2)?"===<<警告>>用戶:["+user.userName+"]已處于登錄狀態(tài),無需重復(fù)登錄!\n":"");
????????????????????break;
????????????????case?2:
????????????????????user.regist();
????????????????????break;
????????????????case?3:
????????????????????user.getLuckly();
????????????????????break;
????????????????default:System.exit(0);
????????????}
????????}
????}
????static?int?Main(User?user){
????????System.out.println("**********************************************");
????????System.out.println("********************主菜單********************");
????????System.out.println("**********************************************");
????????System.out.println("******??????????<1>?登???錄?????????????******");
????????System.out.println("******??????????<2>?注???冊?????????????******");
????????System.out.println("******??????????<3>?抽???獎?????????????******");
????????System.out.println("******??????????<4>?退???出?????????????******");
????????System.out.println("**********************************************");
????????System.out.println("==============================================");
????????System.out.println(logined???"-[已登錄]-??(1)用戶名:"+user.userName+"???(2)用戶賬號:"+user.userId:"-[未登錄]-???(1)用戶名:NaN???(2)用戶賬號:NaN");
????????System.out.println("==============================================");
????????System.out.print("###===>請輸入您的選擇:");
????????return?(new?Scanner(System.in)).nextInt();
????}}public?class?User{
????String?userName,userId,userPwd;
????public?User(){}
????public?User(String?userName,?String?userId,?String?userPwd)?{
????????this.userName?=?userName;
????????this.userId?=?userId;
????????this.userPwd?=?userPwd;
????}
????public?String?getUserName()?{
????????return?userName;
????}
????public?void?setUserName(String?userName)?{
????????if(!userName.equals(""))?{
????????????ArrayList<String>?temp;
????????????this.userId=(temp=(new?operatorFile(this.userName?=?userName)).getUserMess(0)).get(1);
????????????this.userPwd=temp.get(2);
????????}
????}
????public?String?getUserId()?{
????????return?userId;
????}
????public?String?setUserId()?{
????????String?userId="";
????????while((new?operatorFile(userId=String.valueOf?((int)?(Math.random()*9000+1000)))).getUserMess(1).size()>0){?}
????????return?(this.userId?=?userId);
????}
????public?String?getUserPwd()?{
????????return?userPwd;
????}
????public?int?login(User?u)?{
????????int?inputTimes=3;
????????Scanner?scanner=new?Scanner(System.in);
????????operatorFile?getUserMessage=new?operatorFile();
????????System.out.print("======>請輸入您的用戶名:");
????????String?uName="";
????????getUserMessage.setUser(uName=scanner.nextLine());
????????ArrayList<String>?userMess=getUserMessage.getUserMess(0);
????????if(userMess.size()<1)       return -1;//返回-1表示用戶不存在
        if (uName.equals(userName))     return -2;//返回-2表示用戶重復(fù)登錄
        System.out.print("======>請輸入您的登錄密碼:");
????????while(!scanner.next().equals(userMess.get(2))&&inputTimes>0)
????????????System.out.print("===>密碼輸入錯誤!"+((--inputTimes)>0?"您還剩"+inputTimes+"次機會!":"三次機會已經(jīng)用完了!輸入任意退出"));
????????System.out.println(inputTimes>0?"==>登錄成功!您本次輸入密碼"+(4-inputTimes)+"次!":"==>登錄失敗!");
????????setUserName(inputTimes>0?uName:"");
????????Dos.logined=inputTimes>0?true:false;
????????return?0;
????}
????public?void?regist()?{
????????User?u=new?User();
????????Scanner?scanner=new?Scanner(System.in);
????????System.out.print("===>請輸入新的用戶名:");
????????String?name;
????????while(new?operatorFile(name=scanner.nextLine()).getUserMess(0).size()?>?0)
????????????System.out.print("已存在此用戶,注冊失?。n===>請重新輸入新的用戶名:");
????????System.out.print("======>請設(shè)置您的(六位數(shù)字)登錄密碼:");
????????String?regex?=?"[0-9]{6}",?pwd;
????????while?(!(pwd?=?scanner.nextLine()).matches(regex))
????????????System.out.print("==>密碼格式不正確,請重新設(shè)置您的(六位數(shù)字)登錄密碼:");
????????System.out.println("已為用戶:?"+(u.userName=name)+"?生成唯一ID:?"+(u.userPwd=pwd));
????????(new?operatorFile()).writeUserMess(u);
????????System.out.println("=======>注冊成功!");
????}
????public?static?HashMap<String,String>?lucklyUsers=new?HashMap<>();
????public?void?getLuckly()?{
????????if?(!Dos.logined)???{
????????????System.out.println("===>警告:沒有用戶登錄,無法抽獎!");
????????????return?;
????????}
????????while(lucklyUsers.size()<5)
????????{
????????????String?id="";
????????????ArrayList<String>?u;
????????????while((u=(new?operatorFile(id=String.valueOf?((int)?(Math.random()*9000+1000)))).getUserMess(1)).size()<1){ }
            lucklyUsers.put(u.get(1),u.get(0));
        }
        Iterator iterator=lucklyUsers.entrySet().iterator();
        int no=1;
        boolean LUCKLY=false;
        System.out.println("====>恭喜以下用戶獲得幸運稱號:");
????????while(iterator.hasNext()){
????????????Map.Entry?entry=(Map.Entry)?iterator.next();
????????????System.out.println("幸運用戶["+(no++)+"]??用戶名:"+entry.getValue()+"???用戶編號:"+entry.getKey());
????????????LUCKLY?=?entry.getKey().equals(this.userId)???true?:?LUCKLY;
????????}
????????System.out.println(LUCKLY?"=========>恭喜您在本次抽獎中獲得幸運稱號!":"=========>很遺憾,今日您未獲獎?!-_-!");
????}
????public?String?toString(){
????????return?this.userName+"?"+this.userId+"?"+this.userPwd;
????}}public?class?operatorFile?{
????String?user;
????public?void?setUser(String?user)?{
????????this.user?=?user;
????}
????public?operatorFile(String?user)?{
????????this.user?=?user;
????}
????public?operatorFile()?{?}
????public?ArrayList<String>?getUserMess(int?index){
????????ArrayList<String>?temp=new?ArrayList<String>();
????????File?file=new?File("user.txt");
????????String?line="";
????????try{
????????????BufferedReader?br=new?BufferedReader(new?FileReader(file));
????????????while?((line?=?br.readLine())!=null?&&?line!="\n"){
????????????????temp.clear();
????????????????StringTokenizer?sk=new?StringTokenizer(line);
????????????????while?(sk.hasMoreTokens())?{
????????????????????temp.add(sk.nextToken());
????????????????}
????????????????if?(temp.get(index).equals(this.user))??break;
????????????}
????????}
????????catch(IOException?e){}
????????return?(line==null)?new?ArrayList<String>():temp;
????}
????public?void?writeUserMess(User?u){
????????try{
????????????BufferedWriter?bw=new?BufferedWriter(new?FileWriter(new?File("user.txt"),true));
????????????bw.write(u.toString()+"\n");
????????????bw.close();
????????}
????????catch?(IOException?e){?}
????}}

? ? ? ? ? ? ? ? ?

##JAVA Implementation of User Lottery

Requirements Analysis

1) Implement three basic functions: login, registration, and lottery.

2) Login: The user enters the account and password to log in. After entering the account, it will match the registered user. If the entered user does not exist, exit. There are three opportunities to enter the password. After successful login, the main interface will display the account of the logged in user. information.
3) Registration: The user first enters the account name. The system checks whether the name exists. If it exists, the user is asked to change the name. Otherwise, enter the password. The password requires a 6-digit string. After successful registration, the system randomly assigns a A four-digit ID number that is unique from existing users.
4) Lottery: Prerequisite for function implementation: The user must be logged in. When this prerequisite is met, the system randomly selects 5 different users from existing users and marks them as lucky users, and determines whether the logged-in user has been selected.
5) Data storage: Use the file system, import the java.io.* package,
6) Data structure: Login user information is stored in ArrayList, lucky user number and id are stored in HasMap where id is Key and name is Value.

Results achieved

1) Login:


2) Registration:
3) Lottery:

Note

	運行代碼之前務(wù)必在user.txt中創(chuàng)建五個以上的用戶。
rrree

Related free learning recommendations:java basic tutorial

The above is the detailed content of Detailed explanation of JAVA implementation of user lottery. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1502
276
How to handle transactions in Java with JDBC? How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

Understanding the Java Virtual Machine (JVM) Internals Understanding the Java Virtual Machine (JVM) Internals Aug 01, 2025 am 06:31 AM

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

How to work with Calendar in Java? How to work with Calendar in Java? Aug 02, 2025 am 02:38 AM

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Aug 04, 2025 pm 12:48 PM

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

How does garbage collection work in Java? How does garbage collection work in Java? Aug 02, 2025 pm 01:55 PM

Java's garbage collection (GC) is a mechanism that automatically manages memory, which reduces the risk of memory leakage by reclaiming unreachable objects. 1.GC judges the accessibility of the object from the root object (such as stack variables, active threads, static fields, etc.), and unreachable objects are marked as garbage. 2. Based on the mark-clearing algorithm, mark all reachable objects and clear unmarked objects. 3. Adopt a generational collection strategy: the new generation (Eden, S0, S1) frequently executes MinorGC; the elderly performs less but takes longer to perform MajorGC; Metaspace stores class metadata. 4. JVM provides a variety of GC devices: SerialGC is suitable for small applications; ParallelGC improves throughput; CMS reduces

Understanding Network Ports and Firewalls Understanding Network Ports and Firewalls Aug 01, 2025 am 06:40 AM

Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c

go by example defer statement explained go by example defer statement explained Aug 02, 2025 am 06:26 AM

defer is used to perform specified operations before the function returns, such as cleaning resources; parameters are evaluated immediately when defer, and the functions are executed in the order of last-in-first-out (LIFO); 1. Multiple defers are executed in reverse order of declarations; 2. Commonly used for secure cleaning such as file closing; 3. The named return value can be modified; 4. It will be executed even if panic occurs, suitable for recovery; 5. Avoid abuse of defer in loops to prevent resource leakage; correct use can improve code security and readability.

Comparing Java Build Tools: Maven vs. Gradle Comparing Java Build Tools: Maven vs. Gradle Aug 03, 2025 pm 01:36 PM

Gradleisthebetterchoiceformostnewprojectsduetoitssuperiorflexibility,performance,andmoderntoolingsupport.1.Gradle’sGroovy/KotlinDSLismoreconciseandexpressivethanMaven’sverboseXML.2.GradleoutperformsMaveninbuildspeedwithincrementalcompilation,buildcac

See all articles