java - 返回和接收方法

标签 java methods

我是一名初学者编码器,我试图通过在主方法中调用不同的方法来实现底部的输出,但我不断收到错误。有人可以指出我正确的方向吗?不确定我是否需要在主 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 方法中声明了变量,但没有初始化它们。由于您创建了具有返回类型的方法并打算返回城市名称等值,因此您必须使用已声明的变量捕获每个方法返回的值。

例如,在ma​​in中:

city = cityName();

此外,您的程序似乎打算对有关城市的数据/信息进行建模。您的类缺少一个构造函数。您了解创建类/对象了吗?如果没有,我建议这样做。如果使用构造函数、setter 和 getter(访问器和修改器方法)进行编程,这个程序将会更加干净、更有组织。

关于java - 返回和接收方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31257732/

相关文章:

java - Python 等价于 Java StringBuffer?

java - 类类型作为Java中的参数

javascript - 何时使用 which - 多个方法、多个参数或一个选项参数

java - 错误: “Method getText() must be called from the UI thread, currently inferred thread is worker.”

光栅之外的 Java getSubimage()

java - 如何从 void 方法返回 Completable

java gui 帮助 Action 监听器

java - 如何在 Java 中传递和调用方法引用

php - symfony 中不同方法的空路由路径

python - 将对象的方法映射到对象列表的更 pythonic 方式