栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

引自其他博客的java代码改进【基本方法的使用】

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

引自其他博客的java代码改进【基本方法的使用】

题目背景

现有电视商品价格竞猜活动,活动的规则:随机出现一个商品名,用户猜测它的价值,如果在规定次数内猜对,便可获得此商品。模拟竞猜活动,运行结果如下所示: (选作)
分析:
1、准备一批用来竞猜的商品
2、随机获取一件商品
Java程序:
1、定义对象所归属的类:商品类–Goods(属性: 商品的名称String name 商品对应的实际单价 int price)
2、模拟购入一批商品
多个Goods对象
3、

请猜测“公主电动车”的价格:1000
再大点!
再猜一次吧:5000
再小点!
再猜一次吧:2500
在小点!
再猜一次吧:2200
4次内没有猜对,下次努力吧!

改进代码如下

创建一个主类放在包DEMO下面

package DEMO;

import java.util.Scanner;

public class OnessMechine {
    public static void main(String[] args) {
        String name=initial().name;
        int price=initial().price;
        System.out.println(name + "" + price);
        Guess(name,price);
    }

private static Goods initial() {
    Goods goods1 = new Goods("冰箱", 2000);
    Goods goods2 = new Goods("洗衣机", 2200);
    Goods goods3 = new Goods("空调", 1000);
    Goods goods4 = new Goods("电话", 7000);
    Goods goods5 = new Goods("电脑", 5000);
    Goods[] gs = new Goods[5];
    gs[0] = goods1;
    gs[1] = goods2;
    gs[2] = goods3;
    gs[3] = goods4;
    gs[4] = goods5;
    int b = (int) Math.floor(Math.random() * 5);
    Goods goods = gs[b];

    return goods;
}

public static void Guess(String name, int price) {
    Scanner scanner = new Scanner(System.in);
    int i = 0;
    for (; i < 4; i++) {
        int a = scanner.nextInt();
        if (a > price) {
            System.out.println("猜大了,再小一点");
        } else if (a < price) {
            System.out.println("猜小了,再大一点");
        } else if (a == price) {
            System.out.println("猜对了,送" + name + "你了");
            break;
        }
    }
    if (i == 4)
        System.out.println("猜了4次了,不能猜了");

}
}


创建一个Goods类放在DEMO包下面

package DEMO;

public class Goods {
    String name;
    int price;
    public Goods(String name,int price){
        this.name=name;
        this.price=price;
    }
}

原博客地址

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1003224.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号