java - 如何将 Scanner.in 值从方法返回到另一个方法
问题描述
我想做一些简单的程序来计算产品的月费率。有两个输入:产品成本 - 100-10000 和费率数量 - 6-48。我想像下面的代码那样做:
import java.util.Scanner;
public class Calculator {
Scanner sc = new Scanner (System.in);
double productCost;
int numberOfRates;
double loanInterestRate;
double monthlyRate;
Double print () {
Calculator c = new Calculator();
System.out.println ("Enter the value of your product from 100 to 10 000 : ");
productCost=sc.nextDouble();
if (productCost < 100){
System.out.println ("You have to choose price between 100 to 10000. Try again: ");
c.print();
} else if (productCost >10000){
System.out.println ("You have to choose price between 100 to 10000. Try again: ");
c.print();
} else if (productCost >= 100 || productCost <=10000){
c.print1();
return = productCost;
// how to return productCost to be used in next method print1()?
}
else return null;
}
void print1(){
Calculator c = new Calculator();
System.out.println ("Now enter how many rates do you want to pay from 6 to 48: ");
numberOfRates=sc.nextInt();
if (numberOfRates<6){
System.out.println ("You can't choose this number of rates. Choose between 6-48: ");
c.print1();
} else if (numberOfRates>48){
System.out.println ("You can't choose this number of rates. Choose between 6-48: ");
c.print1();
} else if (numberOfRates>=6 || numberOfRates<=12) {
loanInterestRate=1.025;
monthlyRate = (productCost*loanInterestRate)/numberOfRates;
System.out.printf("Your monthly rate is: "+ "%.2f%n",monthlyRate);
} else if (numberOfRates>=13 || numberOfRates <=24 ) {
loanInterestRate=1.05;
monthlyRate = (productCost*loanInterestRate)/numberOfRates;
System.out.printf("Your monthly rate is: "+ "%.2f%n",monthlyRate);
} else if (numberOfRates >=25|| numberOfRates<=48){
loanInterestRate=1.1;
monthlyRate = (productCost*loanInterestRate)/numberOfRates;
System.out.printf("Your monthly rate is: "+ "%.2f%n",monthlyRate);
}
}
}
而主方法只调用其他类的方法。
public class MonthlyRate {
public static void main(String[] args) {
Calculator calc = new Calculator();
calc.print();
// TODO code application logic here
}
}
有什么问题,我不知道如何从方法“print()”返回“double productCost”。productCost 是从输入中获取的,这是双倍的,但 NetBeans 向我显示它不是正确的类型。谁能帮我理解问题出在哪里?
解决方案
简单地做
return productCost;
return
是关键字,而不是变量。它“返回”给定值并退出函数,以便调用函数的实体可以执行以下操作:
public static void main(String[] args) {
...
double cost = calc.print(); // note calc.print() PRODUCES a value, which we assign to `cost`
...
}
然后你可以做任何你想做的事情cost
(或者你选择命名变量的任何东西),包括将它传递给另一个函数。
推荐阅读
- javascript - Redux 错误状态或错误显示在另一个页面中,即使它已被清除
- javascript - 如何将反应渲染方法内容转换为 pug,而不是标准组件方式
- react-native - React Native - console.log 和网络命令不起作用
- google-sheets - 如何留下一个空白单元格而不使用 Importxml 跳过它?
- c# - 带有命名空间和前缀的 Json 到 XML
- javascript - 如何从特定字符串中消除子字符串
- php - 蜜罐 Codeigniter 4
- node.js - touch 命令或其等效系统调用对性能有何影响?
- c# - Load filtered hierarchy from self-referencing table in EF Core
- python - How to style the first index in a multi-index DataFrame