gpt4 book ai didi

java - Java 中的 Try-Catch 语句

转载 作者:搜寻专家 更新时间:2023-10-31 19:29:13 25 4
gpt4 key购买 nike

更新:感谢您提供有关保留代码 SSCCE 的建议。就像我说的,这是我第一次在这里发帖。下次我一定会花时间确保代码在我下次发布之前被充分精简。


所以我正在为我的计算机科学类(class)编写一个程序,并且遇到了一个我无法弄清楚的奇怪问题。我试图通过使用 try/catch 语句来阻止无效的数据类型输入,以免它弄乱并结束整个程序,从而使我的程序健壮,但它似乎不起作用。当输入无效的数据类型时,程序结束时不会在窗口中显示任何 Java 的标准错误消息。我不知道这是为什么,但我假设我错误地使用了 try/catch 语句。这是我的程序的两个类:

/* The core class for the finance calculations to be done in the FinanceApp class. */

public class FinanceCore{
// Instance variables
int numYears;
double principal;
double interestRate;
double balance;

public FinanceCore(){
numYears = 0;
principal = 0;
interestRate = 0;
balance = 0;
}

// Mutator methods that return boolean values depending on whether the input was valid or not
public boolean setYears(int y){
if(y >= 0){
numYears = y;
return true;
}
else return false;
}

public boolean setPrincipal(double p){
if(p >= 0){
principal = p;
balance = principal;
return true;
}
else return false;
}

public boolean setInterestRate(double ir){
if(ir >= 0 && ir <= 1){
interestRate = ir;
return true;
}
else return false;
}

// Two accessors
public int getYears(){
return numYears;
}

public double getPrincipal(){
return principal;
}

// This method calculates and returns the balance at the end of each year
public double plusYear(){
balance = balance*(1+interestRate);
return balance;
}
}

/* This program recieves three pieces of data (interest rate, principal amount, number of years) and generates an output
* table that shows how much money will be in a fund with the given parameters at the end of every year. */

import java.util.Scanner;

public class FinanceApp{

public static void main(String[]args){
// First, we will declare our global variables, and set them to default values
Scanner reader = new Scanner(System.in);
FinanceCore account = new FinanceCore();
int menuItem = 0;

// Now, we'll greet the user (because we're friendly like that)
System.out.println("Welcome! Please select a menu option below.");

while(true){
/* Now, our first user interface: a menu system that displays four options to the user arranged in
* columns for aesthetic effect. This is accomplished using the printf method.
*/

System.out.printf("%n%-20s%-20s%n%-20s%-20s%n%-20s%n",
"Set Principal[1]","Set Interest Rate[2]","Set Timespan[3]","Calculate[4]","Quit[5]");

System.out.print(": ");

// Now we get the user input until it is valid, and catch and errors in input type
try {
menuItem = reader.nextInt();
}
catch(Exception e){
reader.nextLine(); // Clear the input stream to avoid an infinite loop
System.out.println("Please a valid number 1-5.");
}

// The code for setting the principal amount
if(menuItem == 1){
while(true){
System.out.print("Please enter the principal investment amount: ");

try{
if(account.setPrincipal(reader.nextDouble()));
break;
}
catch(Exception e){
reader.nextLine(); // Clear the input stream to avoid an infinite loop
System.out.println("Please enter a valid dollar amount.");
}
}
}
// The code for setting the interest rate
else if(menuItem == 2){
while(true){
System.out.print("Please enter the quarterly interest rate: ");
try{
if(account.setInterestRate(reader.nextDouble()));
break;
}
catch(Exception e){
reader.nextLine(); // Clear the input stream to avoid an infinite loop
System.out.println("Please enter a valid decimal number between 0 and 1 (inclusive).");
}
}
}

// The code for setting the number of years
else if(menuItem == 3){
while(true){
System.out.print("Please enter the number of years the account will exist: ");
try{
if(account.setYears(reader.nextInt()));
break;
}
catch(Exception e){
reader.nextLine(); // Clear the input stream to avoid an infinite loop
System.out.println("Please enter a valid integer value.");
}
}
}

// This part actually executes the calculation
else if(menuItem == 4){
System.out.printf("%-10s%-10s%n%-10d%-10.2f%n","YEAR","BALANCE",0,account.getPrincipal());
int count = 1;
for(int c = account.getYears(); c > 0; c--){
System.out.printf("%-10d%-10.2f%n",count,account.plusYear());
count++;
}
}

// If the user enters any other number, the program quits
else
break;
}
}
}

请注意,此程序存在一个我似乎无法修复的顽固问题。由于某种原因,每次用户在菜单选择提示下输入无效数据类型,程序结束(尽管没有任何错误被抛出)。

最佳答案

当您使用 try-catch block 时,实际上是在告诉编译器将负责显示错误消息——不会显示任何内置消息。相反,将显示您在 catch 语句中包含的任何错误提示。

当我运行你的程序时,我看到了你的错误信息,但没有内置的 Java 错误信息;这是应该的。实际上,错误正在被抛出——但您正在捕获它们,因此 Java 不会在控制台上显示默认消息。

关于您在节目结束时的评论:

如果用户在菜单提示下输入了错误的数据类型,看看会发生什么; menuItem 仍为零。因此,所有 if 语句的计算结果都是假的。因此,运行 else 语句,终止程序。

关于java - Java 中的 Try-Catch 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13655993/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com