public class Example {
public static void main(String[] args) {
System.out.println("请用户输入付款方式:");
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
System.out.println("请用户输入付款金额:");
double money = sc.nextDouble();
System.out.println(Person.buy(name).pay(money));
}
}
abstract class Payment {
public abstract double pay(double money);
}
class Zfb extends Payment {
Random r = new Random();
@Override
public double pay(double money) {
return money;
}
}
class Person {
public static Payment buy(String name) {
if ("Zfb".equals(name)) {
return new Zfb();
} else if ("Cash".equals(name)) {
return new Cash();
} else {
return new Cash();
}
}
}
public static void main(String[] args) {
Person p = new Person();
Scanner sc = new Scanner(System.in);
System.out.println("请输入付款金额:");
double money = 0;
if(sc.hasNextDouble()||sc.hasNextInt()){
money = sc.nextDouble();
}
System.out.println("请选择付款方式:");
System.out.println(" 1:支付宝\n 2:现金\n 任意数字:其它付款方式");
int select = 2;
if(sc.hasNextInt()){
select = sc.nextInt();
}
switch(select){
case 1:
System.out.println("你最终需付款的金额为:"+p.buy("Zfb").pay(money));
break;
default:
case 2:
System.out.println("你最终需付款的金额为:"+p.buy("Cash").pay(money));
break;
}
}
}
package com.zfb.pay;
public abstract class Payment {
public abstract double pay(double money);
}
package com.zfb.pay;
import java.util.Random;
public class Zfb extends Payment {
public double pay(double money) {
Random r = new Random();
double m =r.nextInt(3)+5;
return money*(m/10);
}
}
package com.zfb.pay;
public class Cash extends Payment {
@Override
public double pay(double money) {
return money;
}
}
package com.zfb.person;
import com.zfb.pay.*;
public class Person {
public static Payment buy(String pay){
if("Zfb".equals(pay)){
return new Zfb();
}else if("Cash".equals(pay)){
return new Cash();
}
return new Cash();
}
}