Java JOptionPane 输出

发布于 2024-11-14 23:14:42 字数 4460 浏览 4 评论 0原文

谁能告诉我我在这里做错了什么。我需要根据用户输入计算一些值到一些 JOptionPane 输入对话框中,然后输出答案。

我将非常感谢我得到的任何帮助。提前致谢!

  1. 输入
    • 要比较的贷款数量(可能超过 1 笔)
    • 售价
    • 首付
    • 对于他们想要比较的每笔贷款,您将询问以下问题
      • 利率
      • 年数
  2. 处理
    • 您需要计算 d 部分中列出的每种情况在给定利率和年数下的每月还款额。
  3. 输出
    • 售价
    • 首付款
    • 贷款金额
    • 每个场景的列表
      • 兴趣
      • 付款

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

    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);             
          }
     }

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);             
          }
     }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

满意归宿 2024-11-21 23:14:42

如果我被迫(大概是被一个伪装成编程老师的大绿色的、特别丑陋的巨魔强迫)使用多个 JOption 窗格进行输入和输出,那么我将如何解决这个问题。这仅供您参考......如果您将其作为您自己的作业提交,您的老师会闻到老鼠的味道,并且巨魔也有谷歌。

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);
  }
}

“要比较的贷款列表”由 Loan 对象数组表示...即:每个“贷款选项”由 Loan 类的一个实例表示,它将特定贷款的所有属性分组为一个整洁的“事物”,然后我们可以将其作为一个整体进行操作。这是一个比您用来存储贷款属性的技术更好的方法,该技术称为“并行数组”......嗯,嗯,它有点过时了,事实上它有一个(油腻的)鲻鱼,它穿着一个(太紧)橙色狩猎套装,配上(藏红花粉色)头带……这在八十年代并不好看,而现在,它很可能会让你着迷殴打、逮捕或两者兼而有之;取决于您所在的地区...基本上:我们现在有更好的方法!

Loan 类还有一些方便的“计算字段”来为我们进行计算。这意味着,如果我们计算还款的方式在未来因某种原因发生变化,我们只有一个地方可以改变它,而所有使用贷款的东西(可能是阅读、写作、排列、总计、收回,甚至批发贷款)都会改变。不必改变......他们只是“免费”接受改变。

在这个人为的用例中,我们所有的贷款金额都相同,只有利率和期限有所不同......因此 Loan 类还有一个名为的 static 变量“原则”,它为 Loan 类的所有实例保留“共同”原则。该原则只能设定一次。任何后续设置原则的尝试都将导致抛出 ReadOnlyException。

无论如何,我希望您能通过另一种方法来解决您在自己进行此练习时可能发现的一些子问题,从而学到一些东西。对未来的一个提示:抓住你同学的代码来完成这个练习并通读它......你可以从其他人如何处理事情中学到很多东西。

干杯。基思.

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.

┼── 2024-11-21 23:14:42

现在您需要检查 showMessageDialog() 返回的结果,如图此处

Now you need to examine the result returned by showMessageDialog(), as shown here.

°如果伤别离去 2024-11-21 23:14:42
String.format("\t \t \t \t \t \n", sellingPrice, ...

这只会输出 5 个选项卡。你想要

String.format("%s %s %s %s %s %n", sellingPrice, ...
String.format("\t \t \t \t \t \n", sellingPrice, ...

That's just going to output 5 tabs. You want

String.format("%s %s %s %s %s %n", sellingPrice, ...
思念绕指尖 2024-11-21 23:14:42
for (int i = 0; i < numberOfLoans; i++)
{
    sb.append(/*...snip...*/ Arrays.toString(annualInterestRatesArray), Arrays.toString(numberOfYearsArray), Arrays.toString(monthlyPaymentArray));
}

您还没有告诉我们问题是什么,但我认为这一点没有达到您想要的效果。您要求程序每次循环时打印出整个三个数组。相反,您可能想访问每笔贷款的特定数组元素,对吧?像...

for (int i = 0; i < numberOfLoans; i++)
{
    sb.append(/*...snip...*/ annualInterestRatesArray[i], numberOfYearsArray[i], monthlyPaymentArray[i]);
}
for (int i = 0; i < numberOfLoans; i++)
{
    sb.append(/*...snip...*/ Arrays.toString(annualInterestRatesArray), Arrays.toString(numberOfYearsArray), Arrays.toString(monthlyPaymentArray));
}

You haven't told us what the problem is, but I don't think this bit is doing what you want. You're asking the program to print out the entirety of your three arrays every time the loop goes round. Instead, you probably want to access the specific array element for each loan, right? Something like...

for (int i = 0; i < numberOfLoans; i++)
{
    sb.append(/*...snip...*/ annualInterestRatesArray[i], numberOfYearsArray[i], monthlyPaymentArray[i]);
}
无戏配角 2024-11-21 23:14:42

您的 JOptionPane.showMessageDialog(null... 位于 for 循环内。因此它将显示它与 numberOfLoans2 的值一样多的次数。如果您不希望这样,请将其移到

 String toDisplay = sb.toString();

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

for 循环之外。

Your JOptionPane.showMessageDialog(null... is inside a for loop. So it will show it as many times as the value of numberOfLoans2 . If you dont want that, move your

 String toDisplay = sb.toString();

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

outside the for-loop.

说不完的你爱 2024-11-21 23:14:42

在您的答案打印方法中,numberOfLoans2 变量在两个位置使用:在 for 循环中进行多次打印(外循环),在 for 循环中进行数学计算(内循环)。外面的可能没什么用,把它去掉,也许就能看到结果了。请记住删除循环元素末尾的结尾 } 以保持结构正常:)

In your answer printing method the numberOfLoans2 variable is used in two places: in a for loop making the printing happen many times (outer loop) and in a for loop making the mathematic calculation (inner loop). Probably the outer one is with no use, so remove it and the result may be shown once. Remember to remove the ending } on the end of the loop element to keep the structure ok :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文