- /*
- 输入股票代码、名称、价格等信息
- 打印出盈亏情况
- */
- import java.util.*;
- import javax.swing.*; //JOptionPane窗口录入用
- import java.text.DecimalFormat; //格式化小数点用
- // ---------- 主函数 --------------------
- public class GP_Test {
- public static void main(String[] args) {
- // 读取数据
- String cm = JOptionPane.showInputDialog("股票代码: ");
- String n = JOptionPane.showInputDialog("股票名称: ");
- String input1 = JOptionPane.showInputDialog("买入成本: ");
- double c = Double.parseDouble(input1); //string 转 double
- String input2 = JOptionPane.showInputDialog("现在价格: ");
- double c_n = Double.parseDouble(input2); //string 转 double
- String input3 = JOptionPane.showInputDialog("买入数量: ");
- int a = Integer.parseInt(input3); //string 转 int
- // 构造类,调用方法
- GP gp = new GP(cm, n, c, c_n, a);
- double pal_r = gp.profitAndLoss_ratio(); //盈亏百分比
- double pal = pal_r * (c*a); //盈亏额
- // 格式化(只保留两位小数)
- double pal_r1 = new Double( new DecimalFormat( ".00" ).format( pal_r ) );
- double pal1 = new Double( new DecimalFormat( ".00" ).format( pal ) );
- // 输出
- gp.gpInfo();
- gp.printProfitAndLoss(pal_r, pal1, pal_r1);
- }
- }
- // ---------- 类部分 --------------------
- class GP {
- // 构造器
- public GP(String cm, String n, double c, double c_n, int a) {
- code = cm;
- name = n;
- cost = c;
- cost_now = c_n;
- amount = a;
- }
- // 方法
- public double profitAndLoss_ratio() { //盈亏百分比
- return (cost_now - cost)/cost;
- }
- public void gpInfo() { //打印股票信息
- System.out.println("代码: " + code);
- System.out.println("名称: " + name);
- System.out.println("成本: " + cost);
- System.out.println("现价: " + cost_now);
- System.out.println("股数: " + amount);
- }
- //打印盈亏情况
- public void printProfitAndLoss(double pal_r, double pal1, double pal_r1) {
- System.out.print("盈亏情况:" + (pal_r1 * 100) + "%,");
- if (pal_r > 0)
- System.out.print("盈利" + pal1 + "元");
- else if (pal_r < 0)
- System.out.print("亏损" + (pal1) + "元");
- else
- System.out.print("持平");
- System.out.println();
- }
- // 成员
- private String code; //股票代码
- private String name; //名称
- private double cost; //成本
- private double cost_now; //现价
- private int amount; //股数
- }
java的类,输入框,转换和格式化
最新推荐文章于 2021-02-16 16:49:15 发布