欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

自动贩卖机Java类和对象

程序员文章站 2022-06-04 17:04:01
...

food.class

package OOP.Sale;
import java.util.Scanner;
public class food {
    //属性
    String foodname;
    int price;
    int number;//剩余量
    //方法
public
    void show(){
        System.out.println(this.foodname+"的价格是"+this.price+",剩余数量为"+this.number);
        //this指向当前类
    }
    void getmoney(){
        System.out.println("付款金额:");
        Scanner m= new Scanner(System.in);
        int money=m.nextInt();
        if(money>price&&number>0)
        {
            System.out.println("给你"+this.foodname);
            System.out.println("剩余数量为:"+(this.number-1));
            System.out.println("找零"+(money-this.price)+"元");
        }
        else
            System.out.println("支付失败");
    }
}

Application.class

package OOP.Sale;
import java.util.Scanner;
public class Application {
    public static void main(String[] args) {
        System.out.println("选择商品标号(4为取消支付):");
        Scanner c = new Scanner(System.in);
        int choose = c.nextInt();
        switch (choose) {
            case 1:
                food Coca = new food();
                Coca.foodname = "可乐";
                Coca.number = 10;
                Coca.price = 3;
                Coca.show();
                Coca.getmoney();
                break;
            case 2:
                food mian = new food();
                mian.foodname = "方便面";
                mian.number = 60;
                mian.price = 2;
                mian.show();
                mian.getmoney();
                break;
            case 3:
                food bread = new food();
                bread.foodname = "面包";
                bread.number = 50;
                bread.price = 5;
                bread.show();
                bread.getmoney();
                break;
            case 4:
                System.out.println("取消支付");
                break;
        }
    }
}

相关标签: Java