JAVA经典(商业小应用)
现在有一个电视商品精彩活动
活动规则:
随机出现一个电视的价格(2000-10000),用户去竞猜价格,如果在5次内猜对价格,便可以获得此商品.(超过5次,显示"很可惜,你没有获得奖品,竞猜结束."),在5次之内猜对的话,显示"恭喜你,获得了此奖品."
注:生成随机数的方法.
import java.util.Random;
Random random = new Random();
int price = random.nextInt(8001)+2000;//[0,8001)
或
int price = Math.random();
实现代码如下:
import java.util.Scanner;
import java.util.Random;
public class D2{
public static void main (String[] args){
Random random =new Random();
int price = random.nextInt(8000)+2000;
Scanner scan = new Scanner(System.in);
int i;
for ( i=1;i<=5;i++) {
System.out.println("请猜测公主电动车的价格:");
int num = scan.nextInt();
if(num == price ){
System.out.println("恭喜你获得了此奖品:");
break;
}else if(num >price ){
System.out.println("再小点!");
}else{
System.out.println("再大点!");
}
}
if(i==6){
System.out.println("很可惜你没有获得奖品,下次再努力吧");
}else{
return ;
}
}
}
-----------------------------------------------------------------------------------------------------
完成购买商品结算功能:
1.循环输入商品编号和购物数量,计算消费金额并累加到总金额
2.输入"n"开始结账( 假设享受8折)
3. 输入师傅金额,计算找零.
代码输出如下:
import java.util.Scanner;
public class D3{
public static void main (String[] args){
System.out.println("我行我素购物系统 > 购物结算 ");
System.out.println("");
System.out.println("");
System.out.println("*******************************");
System.out.println("请选择购买的商品编号:");
System.out.println("");
System.out.println("1.T恤 2. 网球鞋 3.网球拍 ");
System.out.println("*******************************");
double sum=0.0;
String z="";
int y;
Scanner scan = new Scanner(System.in);
do{
System.out.println("请输入商品编号:");
int x=scan.nextInt();
System.out.println("请输入购买数量:");
y=scan.nextInt();
if(x==1){
sum +=(y*245);
System.out.println("T恤"+" " + "245"+" "+y*245);
}else if(x==2){ sum +=(y*345);
System.out.println("网球鞋"+" "+"345"+" "+y*345);
}else if(x==3){ sum +=(y*445);
System.out.println("网球拍"+" "+"445"+" "+y*445);
}else {
System.out.println("输入错误");
}
System.out.println();
System.out.println();
System.out.println("是否继续(y/n):");
z=scan.next();
}while(z.equals("y") );
System.out.println("折扣:0.8");
System.out.println("金额总计 $"+sum*0.8);
double jiao=scan.nextInt();
System.out.println("实际交费: $"+jiao);
System.out.println("找钱 $"+(jiao-sum));
return ;
}
}
-----------------------------------------------------------------------------------------------------
有五家衣服专卖店,每家最多购买3件.用户可以选择离开,可以买衣服.最后打印总共买了几件衣服.
代码实现如下:
import java.util.Scanner;
public class D5{
public static void main (String[] args){
Scanner scan = new Scanner(System.in);
int num=0;
for(int j=1;j<=5;j++){
System.out.println("欢迎光临第"+j+"家专卖店");
for(int i=1;i <=3;i++){
System.out.println("要离开吗(y/n)?");
String key= scan.next();
if(key.equals("n")){
System.out.println("买一件衣服");
num++;
}else{
break;
}
}
System.out.println("离店结账");
System.out.println("\n");
System.out.println("\n");
}
System.out.println("总共买了"+num+"件衣服");
return ;
}
}