使用while循环进行Java数据验证
此应用程序验证用户输入的数据是否正确。我已经完成了大约95%的工作,但我不知道该如何继续?(是/否)部分。如果您点击了除y或n以外的任何内容(或者如果您将该行留空),则应该打印一个错误:因此,应用程序在控制台中应该是这样的: 继续?(是/否): 错误!此条目是必需的。再试一次 继续?(是/否):x 错误!条目必须为“y”或“n”。再试一次 继续?(是/否):否 这是我的密码:使用while循环进行Java数据验证,java,validation,Java,Validation,此应用程序验证用户输入的数据是否正确。我已经完成了大约95%的工作,但我不知道该如何继续?(是/否)部分。如果您点击了除y或n以外的任何内容(或者如果您将该行留空),则应该打印一个错误:因此,应用程序在控制台中应该是这样的: 继续?(是/否): 错误!此条目是必需的。再试一次 继续?(是/否):x 错误!条目必须为“y”或“n”。再试一次 继续?(是/否):否 这是我的密码: public static void main(String[] args) { System.out.print
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;
}
}
publicstaticvoidmain(字符串[]args){
System.out.println(“欢迎使用贷款计算器”);
System.out.println();
扫描仪sc=新的扫描仪(System.in);
字符串选择=“y”;
while(choice.equalsIgnoreCase(“y”))
{
System.out.println(“数据输入”);
double loanAmount=getDoubleWithinRange(sc,“输入贷款金额:”,0,1000000);
double interestRate=getDoubleWithinRange(sc,“输入年利率:”,0,20);
整数年=getIntWithinRange(sc,“输入年数:”,0,100);
双月利率=利率/12/100;
整数个月=年*12;
双月付款=计算月付款(贷款金额、月利息、月);
NumberFormat currency=NumberFormat.getCurrencyInstance();
NumberFormat percent=NumberFormat.getPercentInstance();
百分比。setMinimumFractionDigits(1);
String results=“贷款金额:\t\t”+currency.format(loanAmount)+“\n”
+“年利率:\t”+百分比。格式(利率/100)+”\n”
+年数:\t“+年数+”\n
+“每月付款:\t”+货币。格式(每月付款)+“\n”;
System.out.println();
System.out.println(“格式化结果”);
系统输出打印项次(结果);
字符串getContinue=getContinueWithinRange(sc,“Continue?(y/n):”,“y”,“n”);
系统输出打印(getContinue);
System.out.println();
}
}
公共静态双getDoubleWithinRange(扫描仪sc、字符串提示、双最小值、双最大值)
{
双d=0.0;
布尔值isValid=false;
while(isValid==false)
{
d=getDouble(sc,提示符);
如果(d=最大值){
System.out.println(“错误!数字必须小于“+max+”);
}
否则{
isValid=true;
}
}
返回d;
}
公共静态双getDouble(扫描程序sc,字符串提示)
{
双d=0.0;
布尔值isValid=false;
while(isValid==false)
{
系统输出打印(提示);
if(sc.hasNextDouble())
{
d=sc.nextDouble();
isValid=true;
}
其他的
{
System.out.println(“错误!十进制值无效。请重试”);
}
sc.nextLine();
}
返回d;
}
公共静态整型整型getIntWithinRange(扫描程序sc、字符串提示、整型最小值、整型最大值)
{
int i=0;
布尔值isValid=false;
while(isValid==false)
{
i=getInt(sc,提示符);
如果(i=最大值){
System.out.println(“错误!数字必须小于“+max+”);
}
否则{
isValid=true;
}
}
返回i;
}
公共静态int getInt(扫描程序sc,字符串提示)
{
int i=0;
布尔值isValid=false;
while(isValid==false)
{
系统输出打印(提示);
if(sc.hasnetint())
{
i=sc.nextInt();
isValid=true;
}
其他的
{
System.out.println(“错误!无效整数值。请重试”);
}
sc.nextLine();
}
返回i;
}
公共静态双倍计算月付款(双倍贷款金额、双倍月利率、双倍月)
{
双月付款=0;
对于(int i=1;i 0)
{
i=sc.nextLine();
isValid=true;
}
其他的
{
System.out.println(“错误!需要输入。请重试”);
}
sc.nextLine();
}
返回i;
}
}
将getContinue()中while循环的内容更改为:
首先打印提示符,然后将输入读入将返回的变量,然后检查输入的长度是否大于零
在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");
到
在您的主方法中。根据您第一次提交的代码,我为您尝试了一些东西
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);
}
import java.util.*;
导入java.text.*;
公共类贷款支付应用{
公共静态void main(字符串[]args)
{
System.out.println(“欢迎使用贷款计算器”);
System.out.println();
扫描仪sc=新的扫描仪(System.in);
字符串选择=“y”;
而(!choice.equalsIgnoreCase(“n”))
{
System.out.println(“数据输入”);
double loanAmount=getDoubleWithinRange(sc,“输入贷款金额:”,0,1000000);
double interestRate=getDoubleWithinRange(sc,“输入年利率:”,0,20);
整数年=getIntWithinRange(sc,“输入年数:”,0,100);
双月利率=利率/12/100;
整数个月=年*12;
双月付款=计算月付款(贷款金额、月利息、月);
NumberFormat currency=NumberFormat.getCurrencyInstance(Locale.US);
NumberFormat percent=NumberFormat.getPercentInstance();
百分比。setMinimumFractionDigits(1);
String results=“贷款金额:\t\t”+currency.format(贷款金额)
choice = getContinueWithinRange(sc, "Continue? (y/n): ", "y", "n");
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);
}
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;
}
}