1

このアプリケーションは、ユーザーが正しいデータを入力していることを検証します。私はこれの約95%を完了しましたが、続行がわかりませんか?(y / n)部分。yまたはn以外をヒットした場合(または行を空白のままにした場合)、エラーが出力されるはずです。したがって、これは、アプリケーションがコンソールでどのように表示されるかを示しています。

継続する?(y / n):

エラー!このエントリは必須です。再試行。

継続する?(y / n):x

エラー!エントリは「y」または「n」である必要があります。再試行。

継続する?(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;
}

最初のケースは無効な入力をキャッチし、2番目のケースはユーザーが「n」を入力した場合にループを終了し、3番目のケースはユーザーが「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 に答える