我是一名初学者编码器,我试图通过在主方法中调用不同的方法来实现底部的输出,但我不断收到错误。有人可以指出我正确的方向吗?不确定我是否需要在主 header 中列出调用方法内的参数。
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
最佳答案
您在 main 方法中声明了变量,但没有初始化它们。由于您创建了具有返回类型的方法并打算返回城市名称等值,因此您必须使用已声明的变量捕获每个方法返回的值。
例如,在main中:
city = cityName();
此外,您的程序似乎打算对有关城市的数据/信息进行建模。您的类缺少一个构造函数。您了解创建类/对象了吗?如果没有,我建议这样做。如果使用构造函数、setter 和 getter(访问器和修改器方法)进行编程,这个程序将会更加干净、更有组织。
关于java - 返回和接收方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31257732/