1

此应用程序验证用户正在输入正确的数据。我已经完成了大约 95%,但我不知道继续?(y/n) 部分。如果您点击 y 或 n 以外的任何内容(或者如果您将该行留空),它应该会打印一个错误:所以这就是应用程序在控制台中应该看起来的样子:

继续?(是/否):

错误!此条目是必需的。再试一次。

继续?(是/否):x

错误!条目必须是“y”或“n”。再试一次。

继续?(是/否):n

这是我的代码:

public static void main(String[] args) {
   System.out.println("Welcome to the Loan Calculator");
   System.out.println();

   Scanner sc = new Scanner(System.in);
   String choice = "y";
   while (choice.equalsIgnoreCase("y"))
   {
       System.out.println("DATA ENTRY");
       double loanAmount = getDoubleWithinRange(sc, "Enter loan amount: ", 0, 1000000);
       double interestRate = getDoubleWithinRange(sc, "Enter yearly interest rate: ", 0, 20);
       int years = getIntWithinRange(sc, "Enter number of years: ", 0, 100);

       double monthlyInterestRate = interestRate/12/100;
       int months = years * 12; 
       double monthlyPayment = calculateMonthlyPayment(loanAmount, monthlyInterestRate, months);


       NumberFormat currency = NumberFormat.getCurrencyInstance();
       NumberFormat percent = NumberFormat.getPercentInstance();
       percent.setMinimumFractionDigits(1);

       String results = "Loan amount: \t\t" + currency.format(loanAmount) + "\n"
               + "Yearly interest rate: \t" + percent.format(interestRate/100) + "\n"
               + "Number of years: \t" + years + "\n"
               + "Monthly payment: \t" + currency.format(monthlyPayment) + "\n";

       System.out.println();
       System.out.println("FORMATTED RESULTS");
       System.out.println(results);

      String getContinue = getContinueWithinRange(sc, "Continue? (y/n): ", "y", "n");
      System.out.print(getContinue);
      System.out.println();
   }

}
public static double getDoubleWithinRange(Scanner sc, String prompt, double min, double max)
{
    double d = 0.0;
    boolean isValid = false; 
    while (isValid == false)
    {
        d = getDouble(sc, prompt);
        if (d <=min) {
            System.out.println("Error! Number must be greater than " + min + ".");
        }
        else if (d >= max) {
            System.out.println("Error! Number must be less than " + max + ".");
        }
        else {
            isValid = true;
        }
    }
    return d; 
}
public static double getDouble(Scanner sc, String prompt)
{
    double d = 0.0;
    boolean isValid = false;
    while (isValid == false)
    {
        System.out.print(prompt);
        if (sc.hasNextDouble())
        {
            d = sc.nextDouble();
                    isValid = true;
        }
        else
        {
            System.out.println("Error! Invalid decimal value. Try Again.");
        }
        sc.nextLine();
    }
    return d; 
}
public static int getIntWithinRange(Scanner sc, String prompt, int min, int max)
{
    int i = 0;
    boolean isValid = false;
    while (isValid == false)
    {
        i = getInt(sc, prompt);
        if (i <= min) {
            System.out.println("Error! Number must be greater than " + min + ".");
        }
        else if (i >= max) {
            System.out.println("Error! Number must be less than " + max + ".");
        }
        else {
            isValid = true;
        }
    }
    return i; 
}
public static int getInt(Scanner sc, String prompt)
{
    int i = 0;
    boolean isValid = false;
    while (isValid == false)
    {
        System.out.print(prompt);
        if(sc.hasNextInt())
        {
            i = sc.nextInt();
            isValid = true;
        }
        else 
        {
            System.out.println("Error! Invalid integer value. Try again.");
        }
        sc.nextLine();
    }
    return i;

}
public static double calculateMonthlyPayment(double loanAmount, double monthlyInterestRate, double months)
{
    double monthlyPayment = 0;
    for (int i = 1; i <= months; i++)
    {
        monthlyPayment = loanAmount * monthlyInterestRate/(1 - 1/Math.pow(1 + monthlyInterestRate, months));
    }
    return monthlyPayment;
}
      System.out.print(getContinue);
      System.out.println();        
public static String getContinueWithinRange(Scanner sc, String prompt, String yContinue, String nContinue)
{ 
String i = ""; 
boolean isValid = false;
while (isValid == false)
{
       i = getContinue(sc, prompt);
       if (!yContinue.equalsIgnoreCase("") && !nContinue.equalsIgnoreCase("")){
           System.out.println("Error! Entry must be 'y' or 'n'. Try again.");
       }        
       else{
           isValid = true;
       }
}
return i;
 }
public static String getContinue(Scanner sc, String prompt)
 {
 String i = "";
 boolean isValid = false;
 while(isValid == false)
 {
        System.out.print(prompt);
        if (i.length() > 0)
        {

            i = sc.nextLine(); 
            isValid = true;
        }
        else
        {
            System.out.println("Error! Entry is required. Try again.");
        }       
        sc.nextLine();
 }
 return i;
}
}
4

3 回答 3

1

将 getContinue() 中的 while 循环的内容更改为:

System.out.print(prompt);
i = sc.nextLine();
if (i.length() > 0)
{
    isValid = true;
}
else
{
    System.out.println("Error! Entry is required. Try again.");
}       

这首先打印提示,然后将输入读入将返回的变量,然后检查输入的长度是否大于零。


在getContinueWithinRange()中,需要将if子句中的条件替换为

!yContinue.equalsIgnoreCase(i) && !nContinue.equalsIgnoreCase(i)

这将“y”和“n”针对输入而不是针对“”。


此外,如果您想在阅读“y”后实际继续,您需要执行以下操作:

if (!yContinue.equalsIgnoreCase(i) && !nContinue.equalsIgnoreCase(i)){
    System.out.println("Error! Entry must be 'y' or 'n'. Try again.");
}        
else {
    isValid = true;
}

第一种情况捕获无效输入,第二种情况如果用户输入“n”则结束循环,第三种情况告诉用户在输入“y”后循环将继续。


最后,为了让你的程序做它应该做的事情,改变

String getContinue = getContinueWithinRange(sc, "Continue? (y/n): ", "y", "n");

choice = getContinueWithinRange(sc, "Continue? (y/n): ", "y", "n");

在你的主要方法中。

于 2013-02-03T23:22:29.583 回答
1

我根据您第一次提交的代码为您尝试一些东西

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

public class Tester4 {

    public static String getContinueWithinRange(Scanner sc, String prompt, String yContinue, String nContinue) {
        String result = "";
        boolean isValid = false;
        boolean isStarted = false;
        while(!isValid) {
            result = getContinue(sc, prompt, isStarted);
            isStarted = true;
            if(yContinue.equalsIgnoreCase(result) || nContinue.equalsIgnoreCase(result)) {
                isValid = true;
            } else if(!yContinue.equalsIgnoreCase(result) || !nContinue.equalsIgnoreCase(result)) {
                System.out.println("Error! Entry must be 'y' or 'n'. Try again.");
            } else {
                System.out.println("Error! Entry must be 'y' or 'n'. Try again.");
            }
        }
        return result;
    }

    public static String getContinue(Scanner sc, String prompt, boolean isStarted) {
        String result = "";
        boolean isValid = false;
        while(!isValid) {
            if(result.isEmpty() && !isStarted) {
                System.out.print(prompt);
                System.out.println("Error! Entry is required. Try again.");
            }
            result = sc.nextLine();
            if(result.length() > 0) {
                isValid = true;
            }
        }
        return result;
    }

    public static void main(String args[]) {

        Scanner sc = new Scanner(System.in);
        String getContinue = getContinueWithinRange(sc, "Continue? (y/n): ", "y", "n");
        // to call the method
        System.out.print(getContinue);
        System.out.println();
    }

    // InputStream stream = this.getClass().getClassLoader().getResourceAsStream("/images/image.jpg");
    // BufferedImage bufferedImage=ImageIO.read(stream);
    // ImageIcon icon= new ImageIcon(bufferedImage);

}
于 2013-02-03T23:50:24.930 回答
0
import java.util.*;
import java.text.*;

public class LoanPaymentApp {

public static void main(String[] args) 
{

    System.out.println("Welcome to the Loan Calculator");
    System.out.println();

    Scanner sc = new Scanner(System.in);
    String choice = "y";
    while (!choice.equalsIgnoreCase("n"))
    {
   System.out.println("DATA ENTRY");
   double loanAmount = getDoubleWithinRange(sc, "Enter loan amount: ", 0, 1000000);
   double interestRate = getDoubleWithinRange(sc, "Enter yearly interest       rate: ", 0, 20);
   int years = getIntWithinRange(sc, "Enter number of years: ", 0, 100);

   double monthlyInterestRate = interestRate/12/100;
   int months = years * 12; 
   double monthlyPayment = calculateMonthlyPayment(loanAmount, monthlyInterestRate, months);


   NumberFormat currency = NumberFormat.getCurrencyInstance(Locale.US);
   NumberFormat percent = NumberFormat.getPercentInstance();
   percent.setMinimumFractionDigits(1);

   String results = "Loan amount: \t\t" + currency.format(loanAmount) + "\n"
           + "Yearly interest rate: \t" + percent.format(interestRate/100) + "\n"
           + "Number of years: \t" + years + "\n"
           + "Monthly payment: \t" + currency.format(monthlyPayment) + "\n";

   System.out.println();
   System.out.println("FORMATTED RESULTS");
   System.out.println(results);


   System.out.print("Continue? (y/n): ");
        choice = sc.nextLine();
        while (!choice.equalsIgnoreCase("y") && !choice.equalsIgnoreCase("n"))
        {
             if (choice.equals(""))
             {
                System.out.println("Error! This entry is required. Try again.");
                System.out.print("Continue? (y/n): ");
             }
             else
             {
                  System.out.println("Error! Entry must be 'y' or 'n'. Try again.");
                  System.out.print("Continue? (y/n): ");
             }
            choice = sc.nextLine();
        }

        }

        }
        public static double getDoubleWithinRange(Scanner sc, String prompt, double min, double max)
{
double d = 0.0;
boolean isValid = false; 
while (isValid == false)
{
    d = getDouble(sc, prompt);
    if (d <=min) {
        System.out.println("Error! Number must be greater than " + min + ".");
    }
    else if (d >= max) {
        System.out.println("Error! Number must be less than " + max + ".");
    }
    else {
        isValid = true;
    }
}
return d; 
}
public static double getDouble(Scanner sc, String prompt)
{
double d = 0.0;
boolean isValid = false;
while (isValid == false)
{
    System.out.print(prompt);
    if (sc.hasNextDouble())
    {
        d = sc.nextDouble();
                isValid = true;
    }
    else
    {
        System.out.println("Error! Invalid decimal value. Try Again.");
    }
    sc.nextLine();
}
 return d; 
}
public static int getIntWithinRange(Scanner sc, String prompt, int min, int max)
{
int i = 0;
boolean isValid = false;
while (isValid == false)
{
    i = getInt(sc, prompt);
    if (i <= min) {
        System.out.println("Error! Number must be greater than " + min + ".");
    }
    else if (i >= max) {
        System.out.println("Error! Number must be less than " + max + ".");
    }
    else {
        isValid = true;
    }
}
return i; 
}
public static int getInt(Scanner sc, String prompt)
{
int i = 0;
boolean isValid = false;
while (isValid == false)
{
    System.out.print(prompt);
    if(sc.hasNextInt())
    {
        i = sc.nextInt();
        isValid = true;
    }
    else 
    {
        System.out.println("Error! Invalid integer value. Try again.");
    }
    sc.nextLine();
}
return i;

}
 public static double calculateMonthlyPayment(double loanAmount, double monthlyInterestRate, double months)
 {
double monthlyPayment = 0;
for (int i = 1; i <= months; i++)
{
    monthlyPayment = loanAmount * monthlyInterestRate/(1 - 1/Math.pow(1 + monthlyInterestRate, months));
}
return monthlyPayment;
}

}
于 2015-03-05T20:56:24.707 回答