我是编程新手,我很感激这个问题的帮助:一个计算经济援助金额的计划。如果家庭年收入在3万至4万美元之间且家庭至少有3个孩子,则每名儿童的收入为1000美元。如果家庭年收入在2万至3万美元之间且家庭至少有3个孩子,则每名儿童的收入为1500美元。如果家庭年收入低于20000美元,则每名儿童的收入为2000美元。我必须实现一个方法并使用-1作为sentinel值。这是我目前的计划
public static void main(String[] args) {
// **METHOD** //
Scanner in = new Scanner(System.in);
System.out.println("What is the annual household income?");
double income = in.nextDouble();
System.out.println("How many children are in the household?");
int children = in.nextInt();
System.out.println("The financial assistance for this household is: "
+ assistance(income, children));
}
//**TEST PROGRAM**//
public static double assistance(double income, int children)
{
if(income >= 30000 && income < 40000 && children >= 3)
{
assistance = children * 1000; //says that it cannot find the symbol
}
else if(income >= 20000 && income < 30000 && children >= 2)
{
assistance = children * 1500;
}
else if(income < 20000)
{
assistance = children * 2000;
}
else
{
assistance = 0.0;
}
return assistance;
}
}
答案 0 :(得分:1)
您可能正在考虑另一种语言,例如Basic,您声明一个函数并使用函数的名称返回函数的值。
Java只是让你返回值。
其他人已经宣布assistance
。请考虑使用其他名称ans
的变量。最后,您将返回ans
。
public static double assistance(double income, int children)
{
double ans = 0.0;
if(income >= 30000 && income < 40000 && children >= 3)
{
ans = children * 1000; //says that it cannot find the symbol
}
else if(income >= 20000 && income < 30000 && children >= 2)
{
ans = children * 1500;
}
else if(income < 20000)
{
ans = children * 2000;
}
return ans;
}
}
答案 1 :(得分:0)
您需要在assistance
function public static double assistance
public static double assistance(double income, int children)
{
double assistance = 0.0;
"Rest of your code here"
}
答案 2 :(得分:0)
首先,我假设您拥有在类中列出的代码,因为在Java中,所有内容都是类。截至目前,您尚未定义可变辅助。因此,我建议您验证输入,以便处理用户未输入数值的实例。另一个想法是将援助作为一个对象,因为它不必是静态的。然后,您可以使用该对象来调用辅助方法。像这样:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// **METHOD** //
Scanner in = new Scanner(System.in);
System.out.println("What is the annual household income?");
double income = in.nextDouble();
System.out.println("How many children are in the household?");
int children = in.nextInt();
System.out.println("The financial assistance for this household is: "
+ new Assistance.getAssistance(income,children));
}
}
public class Assistance {
public double getAssistance(double income, int children) {
/* Declare assistance here */
double assistance;
if (income >= 30000 && income < 40000 && children >= 3) {
assistance = children * 1000; // says that it cannot find the symbol
}
else if (income >= 20000 && income < 30000 && children >= 2) {
assistance = children * 1500;
} else if (income < 20000) {
assistance = children * 2000;
} else {
assistance = 0.0;
}
return assistance;
}
}