我是初学者编码器,我试图通过在我的main方法中调用不同的方法来实现底部的输出,但我不断收到错误。有人可以指出我正确的方向。不确定我是否需要列出主标题中的调用方法内的参数。
import java.util.Scanner;
public class CityOrozcoB52
{ // begin class
private static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{ // begin main method
String city, state;
float cityPopulation, statePopulation;
cityName();
stateName();
cityPopulation(city);
statePopulation(state);
cityPercState(cityPopulation, statePopulation);
displayCityStateStats(cityName, stateName, cityPopulation, statePopulation, cityPercState);
} // end main method
public static String cityName()
{
String city = "";
System.out.printf("What is the name of your city:");
city = input.nextLine();
return city;
}
public static String stateName()
{
String state = "";
System.out.printf("What is the name of your state:");
state = input.nextLine();
return state;
}
public static float cityPopulation(String city)
{
float cityPopulation = 0;
System.out.printf("what is the population of %s:\n", city);
cityPopulation = input.nextFloat();
return cityPopulation;
}
public static float statePopulation(String state);
{
float statePopulation = 0;
System.out.printf("what is the population of %s:", state);
statePopulation = input.nextFloat();
return statePopulation;
}
public static float cityPercState(float cityPopulation, float statePopulation)
{
float cityStatePercentage = (cityPopulation / statePopulation) * 100;
}
public static void displayCityStateStats(String cityName, String stateName, float cityPopulation, float statePopulation,
float cityPercState)
{
System.out.printf("POPULATION STATISTICS\n\n"
+ "City: %s"
+ "State: %s"
+ "City Population: %f"
+ "State Population: %f"
+ "City to State Population: %.2f%%", cityName, stateName, cityPopulation, statePopulation,
cityPercState);
}
} // ends CityOrozcoLE52
答案 0 :(得分:3)
您在main方法中声明了变量,但是没有初始化它们。由于您创建了具有返回类型的方法并且打算返回诸如城市名称之类的值,因此必须使用已声明的变量捕获每个方法返回的值。
例如,在主要:
中city = cityName();
此外,您的计划似乎打算对有关城市的数据/信息进行建模。您缺少类的构造函数。你学习了创建类/对象吗?如果没有,我建议这样做。如果使用构造函数,设置器和getter(访问器和增变器方法)进行编程,那么这个程序会更清晰,更有条理。
答案 1 :(得分:1)
不知道你得到了什么错误这有点棘手,但我认为你的变量范围有问题。就像来自main()方法的以下调用一样:
cityName();
stateName();
cityPopulation(city);
statePopulation(state);
cityPercState(cityPopulation, statePopulation);
displayCityStateStats(cityName, stateName, cityPopulation, statePopulation, cityPercState);
您没有“捕获”来自cityName()或任何其他函数的返回值。以下内容最有可能奏效:
float cityPercState;
city = cityName();
state = stateName();
cityPopulation = cityPopulation(city);
statePopulation = statePopulation(state);
cityPercState = cityPercState(cityPopulation, statePopulation);
displayCityStateStats(city, state, cityPopulation, statePopulation, cityPercState);
因此,只要有一个返回值的函数,如果要访问返回的值,就需要将它存储在我所显示的变量中。您在其他方法中使用的变量在您的其他方法中不可用,除非您在类中声明它们,例如输入变量。