消费者购买超市5件商品,输入商品名和价格,输出购买的商品信息,并输出应付的总价。
要求:定义Goods类及其成员变量和方法。
(1)定义Goods类:成员变量有 name, price
(2)定义Goods类的带两个参数的构造方法。
(3)定义Goods类的toString()方法,getPrice()方法。
主程序如下:
class Main{
public static void main(String args[]){
Goods ga[] =new Goods[5];
Scanner sc = new Scanner(System.in);
for(int i =0;i<5;i++){
ga[i]= new Goods(sc.next(),sc.nextDouble());
}
double shouldPay = 0;
for(Goods g:ga){
shouldPay += g.getPrice();
System.out.println(g.toString());
}
System.out.println("should pay:"+shouldPay);
}
}
输入格式:
输入5行数据,每行一个商品信息,包括商品名和价格,以一个空格分隔。
例:
book 5.5
pencil 1.2
pen 8.0
ruler 2.5
eraser 1.0
输出格式:
输入信息有6行,前5行是商品信息,每行包括商品名和价格,以一个逗号分隔。
第6行为商品的应付总价,格式是:should pay:总价
例:
book,5.5
pencil,1.2
pen,8.0
ruler,2.5
eraser,1.0
should pay:18.2
输入样例:
book 5.5
pencil 1.2
pen 8.0
ruler 2.5
eraser 1.0
输出样例:
book,5.5
pencil,1.2
pen,8.0
ruler,2.5
eraser,1.0
should pay:18.2
代码如下:
//goods类
package scanner;
public class Goods {
private String name;
private double price;
public Goods(String name,double price) {
this.name = name;
this.price = price;
}
public String toString() {
return this.name+","+this.price;
}
double getPrice() {
return price;
}
//主程序
package scanner;
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Goods ga[] = new Goods[5];
Scanner sc = new Scanner(System.in);
Goods s = new Goods(sc.next(),sc.nextDouble());
for (int i = 0; i < 5; i++) {
ga[i] = new Goods(sc.next(), sc.nextDouble());
}
double shouldPay = 0;
for (Goods g : ga) {
shouldPay += g.getPrice();
System.out.println(g.toString());
}
System.out.println("should pay:" + shouldPay);
}
}
此文章仅为自用学习笔记