这是我正在使用的两个 java 文件。我遇到的问题是让 getPosNum 方法(下面突出显示)获取用户输入的数字并查看该数字是否为正数,而不是执行现在正在执行的操作,即:
jGRASP exec: java Prog12
OUTPUT: First Investment
INPUT: Please enter a positive number: -5000.00
INPUT: ERROR: -5000.0 is not positive; try again: -3000.00
而不是让它说这样的话:
jGRASP exec: java Prog12
OUTPUT: First Investment
INPUT: Enter the first principal amount: -5000.00
INPUT: ERROR: -5000.0 is not positive; try again: -3000.00
如何解决此问题并使其正确读取?我说得有道理吗?
public class Finance
{
public static double getPosNum (String prompt)
{
double num;
num = Input.readDouble("Please enter a positive number: ");
while (num <= 0.0)
num = Input.readDouble("ERROR: " + num +
" is not positive; try again: ");
Output.showValue("You entered ", num);
return num;
} // method getPosNum
public static void outFinances (double prin, double rate, double years, double fv)
{
Output.showMessage("The original amount invested was $" + prin + ",\nand the annual interest rate was set at " + rate + "%.\nIt has been " + years + " years since the investment was made,\nand the future value of the investment after that many years is $" + fv + ".");
} // method outFinances
public static double futureValue (double prin, double rate, double years)
{
double FV, P, r, n;
P = prin;
r = rate;
n = years;
FV = P * Math.pow((1 + (r / 100)),(n));
return FV;
} // method outFinances
} // class Finance
// File: Prog12.java
// CS200 Lab 12 Main
// Author: Ryan Pech
// Created: February 19, 2011
public class Prog12
{
public static void main (String [] args)
{
double p, r, y, fv;
Output.showMessage("First Investment");
p = Finance.getPosNum("Enter the first principal amount: ");
r = Finance.getPosNum("Enter the first interest rate: ");
y = Finance.getPosNum("Enter the first number of years: ");
fv = Finance.futureValue(p, r, y);
Finance.outFinances(p, r, y, fv);
Output.showMessage("Second Investment");
p = Finance.getPosNum("Enter the second principal amount: ");
r = Finance.getPosNum("Enter the second interest rate: ");
y = Finance.getPosNum("Enter the second number of years: ");
fv = Finance.futureValue(p, r, y);
Finance.outFinances(p, r, y, fv);
} // method main
} // class Prog12
// File: Finance.java
// CS200 Lab 12
// Author: Ryan Pech
// Created: February 19, 2011
最佳答案
您的 getPostNum()
接受名为 prompt
的参数,但您根本不会在该方法中使用该变量。不要硬编码请输入正数:
,而是用该提示
变量替换该字符串,如下所示:-
改变...
num = Input.readDouble("Please enter a positive number: ");
...到...
num = Input.readDouble(prompt);
关于java - 在图书馆类(class)中获取用户输入并确保其是积极的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5060075/