Java的JOptionPane输出

Java的JOptionPane输出

本文介绍了Java的JOptionPane输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以告诉我我在这里做错了吗?我需要计算一些从用户输入到某些JOptionPane输入对话框的值,然后输出答案。

我非常感谢任何帮助。
$ b


  1. 输入

    • 要比较的贷款数量(可能更多比1)

    • 售价

    • 预付款

    • 以比较


      • 利率

      • 年数



    • 处理

      • 您需要计算d部分对于给定的利率和年数。


      • 输出

        • 售价

        • 预付款

        • 贷款额

        • 每个场景列表

          • 兴趣


          • 付款

        • >

这是我的代码到目前为止:

 包javamortgagecalculator; 
import javax.swing.JOptionPane;
import java.util。*;
public class JavaMortgageCalculator {
public static void main(String [] args){
// A。输入贷款数量来比较
字符串numberOfLoansString = JOptionPane.showInputDialog(输入比较的贷款数量);
//将numberOfLoansString转换为int
int numberOfLoans = Integer.parseInt(numberOfLoansString);

// B。输入Home
的销售价格String sellingPriceString = JOptionPane.showInputDialog(输入贷款金额);
//将homeCostString转换为double
double sellingPrice = Double.parseDouble(sellingPriceString);

// C。在主页上输入预付款
字符串downPaymentString = JOptionPane.showInputDialog(输入家庭首付);
double downPayment = Double.parseDouble(downPaymentString);

//通过从homeCost减去预付款来获得贷款额度
double loanAmount = sellingPrice - downPayment;

// D。询问以下有多少个他们想要比较的贷款
// D1获得利率
double [] annualInterestRatesArray = new double [numberOfLoans];
double [] monthlyInterestRateArray = new double [numberOfLoans];
int [] numberOfYearsArray = new int [numberOfLoans];
double [] monthlyPaymentArray = new double [numberOfLoans];
double [] totalPaymentArray = new double [numberOfLoans];
int counter = 1;

(int i = 0; i< numberOfLoans; i ++)
{
字符串annualInterestRateString = JOptionPane.showInputDialog(Enter the interest rate for Scenario+ counter);
double annualInterestRate = Double.parseDouble(annualInterestRateString);
annualInterestRatesArray [i] =(annualInterestRate);

//获取每月利率
double monthlyInterestRate = annualInterestRate / 1200;
monthlyInterestRateArray [i] =(monthlyInterestRate);

// D2获取年数
字符串numberOfYearsString = JOptionPane.showInputDialog(输入方案的年数+ counter);
int numberOfYears = Integer.parseInt(numberOfYearsString);
numberOfYearsArray [i] =(numberOfYears);

//计算每月付款
double monthlyPayment = loanAmount * monthlyInterestRate /(1 - 1 / Math.pow(1 + monthlyInterestRate,numberOfYears * 12));
//格式为小数点后保持monthlyPayment两位数
monthlyPayment =(int)(monthlyPayment * 100)/ 100.0;
//将monthlyPayment的值存储在数组
monthlyPaymentArray [i] =(monthlyPayment);

//计算总付款
double totalPayment = monthlyPaymentArray [i] * numberOfYears * 12;
//在小数点后保留totalPayment两位数的格式
totalPayment =(int)(totalPayment * 100)/ 100.0;
totalPaymentArray [i] =(totalPayment);

counter ++;
}

StringBuilder sb = new StringBuilder();
for(int i = 0; i< numberOfLoans; i ++){
sb.append(String.format(\ t \t \t \t \\\\\\\\ ,sellPrice,downPayment,loanAmount,Arrays.toString(annualInterestRatesArray),Arrays.toString(numberOfYearsArray),Arrays.toString(monthlyPaymentArray)));
}
String toDisplay = sb.toString();

JOptionPane.showMessageDialog(null,sb.toString(),toDisplay,JOptionPane.INFORMATION_MESSAGE);



$ div $解析方案

如果我被迫大概是由一个大型的绿色,特别是一个冒充编程老师的丑陋的巨魔,使用多个JOption窗格来输入和输出,然后这里是我如何解决这个问题。这只是为了您的信息...如果你把它作为你自己的工作,你的老师会闻到一只老鼠,而巨魔也有谷歌。

 封装论坛; 
import javax.swing.JOptionPane;
import java.text.DecimalFormat;
$ b / **
*比较抵押贷款的总成本(aka普通年金确定)
* /
公共类MortgageCalculator
{
public static void main(String [] args)
{
// 1.输入
final double price = Enter.aDouble(购买属性);
最终双重存款= Enter.aDouble(首付);
Loan.setPrinciple(price - deposit);

int numLoans = Enter.anInteger(要比较的贷款数量);
贷款[]贷款=新贷款[numLoans];
for(int i = 0; i< numLoans; ++ i){
loans [i] = new Loan(
Enter.aDouble(Loan年利率+(i +1)+(例如:6.75))/ 100.0 / 12.0
,Enter.anInteger(贷款年数+(i + 1)+(例如20))* 12
);
}

// 3.输出
final String caption =
Principle+ Format.money(Loan.getPrinciple())
+ = Price+ Format.money(price)
+ - Deposit+ Format.money(deposit);

StringBuilder结果=新的StringBuilder(64 + numLoans * 64);
results.append(月费率,月份,每月还款额,总还款额);
for(Loan l:loans){
results.append(String.format(%5s,%d,%13s,%13s\\\

,Format.percent(l .rate)
,l.periods
,Format.money(l.payment())
,Format.money(l.totalPayment())
));

JOptionPane.showMessageDialog(null,results.toString(),caption,JOptionPane.INFORMATION_MESSAGE);


static class Format
{
static java.text.Format MONEY = new DecimalFormat($#,###。##);
static String money(double amount){
return MONEY.format(amount);
}

static java.text.Format PERCENT = new DecimalFormat(0。###%);
static String percent(double amount){
return PERCENT.format(amount);


static StringBuilder join(String,Object ... values){
StringBuilder result = new StringBuilder(values.length * 16);
if(values.length> 0){
result.append(values [0] .toString());
for(int i = 1; i< values.length; ++ i){
result.append(between)
.append(values [i] .toString());
}
}
返回结果;

$ b $ // end class格式

静态类输入
{
public static int anInteger(String fieldDesc){
return Integer.parseInt(JOptionPane.showInputDialog(Enter the+ fieldDesc));


public static double aDouble(String fieldDesc){
return Double.parseDouble(JOptionPane.showInputDialog(Enter the+ fieldDesc));
}
} // end class输入

} //结束类MortgageCalculator

类贷款
{
private static双重原则= 34324.121221312432;
最终双倍利率;
final int句点;

static void setPrinciple(double principle){
if(Loan.principle!= 34324.121221312432)
抛出新的ReadOnlyException(原理不能改变一次。 ;
Loan.principle =原则;


static double getPrinciple(){
return Loan.principle;
}

/ **
*初始化一个新的贷款对象
* @param双倍利率每个时期的利率,以百分比表示。
*例如:0.00625是每年7.5%。
* @param整数期贷款的期数,通常是几个月。
* /
贷款(双倍利率,整数周期){
this.rate = rate;
this.periods =句点;


// 2.处理
双重付款(){
返回原则*费率/(1 - 1 / Math.pow(1 +费率,句点));


double totalPayment(){
return periods * payment();



$ b class ReadOnlyException extends RuntimeException
{
private static final long serialVersionUID = 0L;
public ReadOnlyException(String message){
super(message);






比较贷款清单由一个贷款对象的数组...即:每个贷款期权由贷款类的一个实例,将特定贷款的所有属性组合成一个整洁的事物,然后我们就可以把它整体化。这比你用来存储贷款属性的技术更好,这就是所谓的平行阵列......嗯,这有点过时,事实上它有一个(油腻)m鱼,它穿着(太紧)的橙色野生动物园服(西红柿粉红色)头带......在八十年代这不是一个好看,而且这些日子,好吧,它可能会让你被殴打,被捕,或两者兼而有之。取决于你的语言环境...基本上:现在我们有更好的方法了!



Loan 类也有一个方便的计算场对我们做计算。这意味着,如果我们计算还款的方式在未来出于某种原因而改变,我们只有一个地方可以改变它,所有使用贷款(可以是读,写,排序,总计,收回甚至批发贷款)的地方没有必要改变...他们只是拿起免费的变化。

在这个人为设计的用例中,我们所有的贷款都是相同的。利率和期限各不相同...所以 Loan 类也有一个叫做原则的 static 变量,持有贷款类的所有实例的共同原则。原则只能设置一次。任何随后的设置prinicple的尝试都会导致抛出一个ReadOnlyException。

无论如何,我希望你学会了另一种解决一些子问题的方法你可能在自己做这个练习的时候发现了。一个未来的提示:抓住你的班级代码进行这个练习,并通读它...你可以从其他人如何处理事情学到很多。

干杯。基思。

Can anybody tell me what I am doing wrong here. I need to calculate some values from user-input into some JOptionPane-input-dialog-boxes, then outputting the answers.

I would greatly appreciate any help I get. Thanks In Advance!

  1. Input
    • Number of loans to compare (Could be more than 1)
    • Selling price
    • Down payment
    • You will ask the following for each loan they want to compare
      • Interest rate
      • Number of years
  2. Processing
    • You will need to calculate the monthly payment for each scenario listed in part d for the given interest rates and number of years.
  3. Output
    • Selling price
    • Down Payment
    • Loan Amount
    • List for each scenario
      • interest
      • years
      • payment

Here's my code so far:

    package javamortgagecalculator;
    import javax.swing.JOptionPane;
    import java.util.*;
    public class JavaMortgageCalculator {
         public static void main(String[] args) {
              //A. Enter the Number Of Loans to compare
              String numberOfLoansString = JOptionPane.showInputDialog("Enter the Number Of Loans to Compare");
              //Convert numberOfLoansString to int
              int numberOfLoans = Integer.parseInt(numberOfLoansString);

              //B. Enter the Selling Price of Home
              String sellingPriceString = JOptionPane.showInputDialog("Enter the Loan Amount");
              //Convert homeCostString to double
              double sellingPrice = Double.parseDouble(sellingPriceString);

              //C. Enter the Down Payment on the Home
              String downPaymentString = JOptionPane.showInputDialog("Enter the down payment on the Home");
              double downPayment = Double.parseDouble(downPaymentString);

              //Get the loanAmount by Subtracting the Down Payment from homeCost
              double loanAmount = sellingPrice - downPayment;

              //D. Ask the following for as many number of loans they wish to compare
              //D1 Get the interest rate
              double[] annualInterestRatesArray = new double[numberOfLoans];
              double[] monthlyInterestRateArray = new double[numberOfLoans];
              int[] numberOfYearsArray = new int[numberOfLoans];
              double[] monthlyPaymentArray = new double[numberOfLoans];
              double[] totalPaymentArray = new double[numberOfLoans];
              int counter = 1;

              for (int i=0; i < numberOfLoans; i++)
              {
                  String annualInterestRateString = JOptionPane.showInputDialog("Enter           the interest rate for Scenario " + counter);
                  double annualInterestRate = Double.parseDouble(annualInterestRateString);
                  annualInterestRatesArray[i] = (annualInterestRate);

                  //Obtain monthly interest rate
                  double monthlyInterestRate = annualInterestRate / 1200;
                  monthlyInterestRateArray[i] = (monthlyInterestRate);

                  //D2 Get the number of years
                  String numberOfYearsString = JOptionPane.showInputDialog("Enter the      number of years for Scenario " + counter);
                  int numberOfYears = Integer.parseInt(numberOfYearsString);
                  numberOfYearsArray[i] = (numberOfYears);

                  //Calculate monthly payment
                  double monthlyPayment = loanAmount * monthlyInterestRate / (1 - 1 / Math.pow(1 + monthlyInterestRate, numberOfYears * 12));
                  //Format to keep monthlyPayment two digits after the decimal point
                  monthlyPayment = (int)(monthlyPayment * 100) / 100.0;
                  //Store monthlyPayment values in an array
                  monthlyPaymentArray[i] = (monthlyPayment);

                  //Calculate total Payment
                  double totalPayment = monthlyPaymentArray[i] * numberOfYears * 12;
                  //Format to keep totalPayment two digits after the decimal point
                  totalPayment = (int)(totalPayment * 100) / 100.0;
                  totalPaymentArray[i] = (totalPayment);

                  counter++;
              }

              StringBuilder sb = new StringBuilder();
              for (int i = 0; i < numberOfLoans; i++) {
                     sb.append(String.format("\t \t \t \t \t \n", sellingPrice, downPayment, loanAmount, Arrays.toString(annualInterestRatesArray),           Arrays.toString(numberOfYearsArray), Arrays.toString(monthlyPaymentArray)));
              }
              String toDisplay=sb.toString();

              JOptionPane.showMessageDialog(null, sb.toString(), toDisplay, JOptionPane.INFORMATION_MESSAGE);
          }
     }
解决方案

If I was forced, presumably by a large green, and particularly ugly troll masquerading as a programming teacher, to use multiple JOption panes for input and output then here's how I'd tackle the problem. This is meant for your information only... if you hand this in as your own work your teacher will smell a rat, and trolls have google too.

package forums;
import javax.swing.JOptionPane;
import java.text.DecimalFormat;

/**
 * Compares total cost of mortgages (aka ordinary annuity certains)
 */
public class MortgageCalculator
{
  public static void main(String[] args)
  {
    // 1. input
    final double price = Enter.aDouble("the purchase of the property");
    final double deposit = Enter.aDouble("down payment");
    Loan.setPrinciple(price - deposit);

    int numLoans = Enter.anInteger("number of loans to compare");
    Loan[] loans = new Loan[numLoans];
    for ( int i=0; i<numLoans; ++i ) {
      loans[i] = new Loan(
          Enter.aDouble("Annual interest rate for Loan " + (i+1) + "  (eg: 6.75)") / 100.0 / 12.0
        , Enter.anInteger("number of years for Loan " + (i+1) + "  (eg 20)") * 12
      );
    }

    // 3. Output
    final String caption =
        "Principle " + Format.money(Loan.getPrinciple())
      + " = Price " + Format.money(price)
      + " - Deposit " + Format.money(deposit);

    StringBuilder results = new StringBuilder(64 + numLoans * 64);
    results.append("Monthly Rate, Months, Monthly Repayment, Total Repayments\n");
    for ( Loan l : loans ) {
      results.append(String.format("%5s, %d, %13s, %13s\n"
        , Format.percent(l.rate)
        , l.periods
        , Format.money(l.payment())
        , Format.money(l.totalPayment())
      ));
    }
    JOptionPane.showMessageDialog(null, results.toString(), caption, JOptionPane.INFORMATION_MESSAGE);
  }

  static class Format
  {
    static java.text.Format MONEY = new DecimalFormat("$#,###.##");
    static String money(double amount) {
      return MONEY.format(amount);
    }

    static java.text.Format PERCENT = new DecimalFormat("0.###%");
    static String percent(double amount) {
      return PERCENT.format(amount);
    }

    static StringBuilder join(String between, Object... values) {
      StringBuilder result = new StringBuilder(values.length * 16);
      if ( values.length > 0 ) {
        result.append(values[0].toString());
        for ( int i=1; i<values.length; ++i ) {
          result.append(between)
            .append(values[i].toString());
        }
      }
      return result;
    }

  } // end class Format

  static class Enter
  {
    public static int anInteger(String fieldDesc) {
      return Integer.parseInt(JOptionPane.showInputDialog("Enter the "+ fieldDesc));
    }

    public static double aDouble(String fieldDesc) {
      return Double.parseDouble(JOptionPane.showInputDialog("Enter the "+ fieldDesc));
    }
  } // end class Enter

} // end class MortgageCalculator

class Loan
{
  private static double principle = 34324.121221312432;
  final double rate;
  final int periods;

  static void setPrinciple(double principle) {
    if (Loan.principle != 34324.121221312432)
      throw new ReadOnlyException("The Principle can't be changed once set.");
    Loan.principle = principle;
  }

  static double getPrinciple() {
    return Loan.principle;
  }

  /**
   * Initialises a new loan objects
   * @param double rate The interest rate per period, as a percentage.
   *  eg: 0.00625 is 7.5% per annum.
   * @param int periods The number of periods of the loan, typically months.
   */
  Loan(double rate, int periods) {
    this.rate = rate;
    this.periods = periods;
  }

  // 2. processing
  double payment() {
    return principle * rate / (1 - 1/Math.pow(1+rate,periods) );
  }

  double totalPayment() {
    return periods * payment();
  }

}

class ReadOnlyException extends RuntimeException
{
  private static final long serialVersionUID = 0L;
  public ReadOnlyException(String message) {
    super(message);
  }
}

The "list of loans to compare" is represented by an array of Loan objects... I.e: each "loan option" is represented by an instance of the Loan class, which groups all the attributes of a particular loan into one nice tidy "thing" which we can then manipulate as a whole. This a better appraoch than the technique you're using to store loan attributes, which is called "parallel arrays"... and well, umm, it's a bit outdated, in-fact it's got a (greasy) mullet, it's wearing a (too tight) orange safari suit with a (safron pink) head-band... It wasn't a good look in the eighties, and these days, well it's likely to get you beaten-up, arrested, or both; depending on your locale... Basically: We have have better ways now!

The Loan class also has a couple of handy "calculated fields" to do the computations for us. This means that if the WAY we calculate repayments changes for some reason in future, we only have one place to change it, and everything that uses Loans (which could be reading, writing, permuting, totalling, repossessing, or even wholesaling loans) does NOT have to change... they just pick up the change "for free".

In this contrived use-case all our Loans will be for the same ammount, only the interest rates and periods vary... so the Loan class also has a static variable called "principle", which holds THE "common" principle for ALL instances of the Loan class. The principle may only be set once. Any subsequent attempt to set the prinicple will cause a ReadOnlyException to be thrown.

Anyway, I hope that you learn something from seeing another way to tackle some of the sub-problems you may have dicovered while doing this exercise yourself. One tip for the future: Grab your class-mates code for this exercise and read through it... you can learn a LOT from how other people tackle things.

Cheers. Keith.

这篇关于Java的JOptionPane输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 11:44