簡體   English   中英

帶嵌套循環的Java驗證

[英]Java validation with nested loops

該程序運行良好,但是嵌套的do-while循環無法正常工作。 如果您看到了一段時間的條件,則可以看到它必須是一個驗證,並且如果它不在這些數字的范圍內,則必須再次提出問題。 您可以看到,如果委托人程序從程序中退出,則它必須驗證委托人不等於0。

我聲明:

import java.util.Scanner;
import java.text.DecimalFormat;
public class ACMEMORTGAGE
{
   public static void main (String args [])

   {
       //Declare variables 
        double rate=0, monthlyPayments, numberMonthlyPayments, paymentAmount;
        int mortgageTerm, principal, years=0;

        Scanner key=new Scanner(System.in);

        DecimalFormat decimalPlaces=new DecimalFormat("$0.00");
        do
        {
            System.out.print("Enter principal amount (0 to end program):");
            principal=key.nextInt();

            do

            {
            System.out.print("Enter mortgage amortization (1, 2, 3, 5, 10.):");
            mortgageTerm=key.nextInt();

            if (mortgageTerm==1)
            {
                rate=0.035;
            }
            else if (mortgageTerm==2)
            {
                rate=0.039;
            }
            else if (mortgageTerm==3)
            {
               rate=0.044;
            }
            else if (mortgageTerm==5)
            {
               rate=0.05;
            }
             else if (mortgageTerm==10)
            {
                rate=0.060;  
            }


            } while (mortgageTerm==1 || mortgageTerm==2 || mortgageTerm==3 || mortgageTerm==5 || mortgageTerm==10);


            do
           {     
            System.out.print("Enter mortgage ammortization period (5, 10, 15, 20, 25):");
            years=key.nextInt();

           } while (years==5 && years==10 && years==15 && years==20 && years==25);               

       double i, n, x;

       i=rate/12;
       n=12*years;


       monthlyPayments= ((principal*(Math.pow(i+1, n)*(i))) / (Math.pow(i+1, n) - 1));
       System.out.print("Monthly payments amount:");    
       System.out.println(decimalPlaces.format(monthlyPayments));

     }while (principal!=0);

   }

}

您正在使用賦值運算符( = ),而不是比較操作符( ==每個) if這是一個錯誤。 在C語言中,您可以執行此操作(通常表示錯誤),而在Java中,必須在if子句中使用布爾表達式。 應該:

if (years == 1)

等等。

if (years=1)

在這里,您將為years分配值1 因此, if expression的結果不是boolean表達式。

現在,由於Java期望if的條件求值為boolean值,因此它給出了不兼容的類型。

您應該使用:-

if(years == 1)

同樣,您需要將while語句更改為:-

while (years==1 && years==2 && ...);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM