java基础案例8-3模拟银行取钱

package com.itheima;

import java.util.Scanner;

//用户1
class User1 extends Thread{
    Scanner in = new Scanner(System.in);
    public void run(){
        try {
            int balance = 0;
            while(true) {
            System.out.println("(1)存钱   (2)取钱   (3)退出");
            System.out.println("请输入需要进行的操作(用户1):");
            int d = in.nextInt();

            if (d == 1) {
                System.out.println("请放入人民币");
                System.out.println("检查到人民币2000元,成功存入");
                balance += 2000;
                System.out.println("当前的余额为(用户1):" + balance + "元");
                Thread.sleep(5000);
            } else if (d == 2) {
                System.out.println("请输入需要的取出的金额(用户1):");
                d = in.nextInt();
                if (d > balance) {
                    System.out.println("余额不足");
                } else {
                    System.out.println("成功取出");
                    balance -= d;
                    System.out.println("当前的余额为(用户1):" + balance + "元");
                }
                Thread.sleep(5000);
            } else
                break;
        }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

//用户2
class User2 extends Thread{
    Scanner in = new Scanner(System.in);
    public void run(){
        try {
            int balance = 0;
            while(true) {
            System.out.println("(1)存钱   (2)取钱   (3)退出");
            System.out.println("请输入需要进行的操作(用户2):");
            int d = in.nextInt();
            if (d == 1) {
                System.out.println("请放入人民币");
                System.out.println("检查到人民币2000元,成功存入");
                balance += 2000;
                System.out.println("当前的余额为(用户2):" + balance + "元");
                Thread.sleep(5000);
            } else if (d == 2) {
                System.out.println("请输入需要的取出的金额(用户2):");
                d = in.nextInt();
                if (d > balance) {
                    System.out.println("余额不足");
                } else {
                    System.out.println("成功取出");
                    balance -= d;
                    System.out.println("当前的余额为(用户2):" + balance + "元");
                }
                Thread.sleep(5000);
            } else
                break;
        }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public class Main {
    public static void main(String[] args)throws Exception{
        //两个线程
        new User1().start();
        new User2().start();
    }
}

  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值