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

	运行代码之前务必在user.txt中创建五个以上的用户。
Copy after login
Copy after login
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+"]已处于登录状态,无需重复登录!\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表示用户重复登录
        System.out.print("======>请输入您的登录密码:");
        while(!scanner.next().equals(userMess.get(2))&&inputTimes>0)
            System.out.print("===>密码输入错误!"+((--inputTimes)>0?"您还剩"+inputTimes+"次机会!":"三次机会已经用完了!输入任意退出"));
        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("======>请设置您的(六位数字)登录密码:");
        String regex = "[0-9]{6}", pwd;
        while (!(pwd = scanner.nextLine()).matches(regex))
            System.out.print("==>密码格式不正确,请重新设置您的(六位数字)登录密码:");
        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){ }
    }}
Copy after login

                 

##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

	运行代码之前务必在user.txt中创建五个以上的用户。
Copy after login
Copy after login
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

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.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Square Root in Java Square Root in Java Aug 30, 2024 pm 04:26 PM

Guide to Square Root in Java. Here we discuss how Square Root works in Java with example and its code implementation respectively.

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Random Number Generator in Java Random Number Generator in Java Aug 30, 2024 pm 04:27 PM

Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

Armstrong Number in Java Armstrong Number in Java Aug 30, 2024 pm 04:26 PM

Guide to the Armstrong Number in Java. Here we discuss an introduction to Armstrong's number in java along with some of the code.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

See all articles