0

该程序的目标是在给定用户输入的情况下计算体积、表面积、面积或周长。我仍在试图弄清楚我将如何循环某些事情,但这是我真正的问题:

我尝试运行程序,但我得到了上面显示的错误,还有返回语句,我将在哪里放置一个结束消息,告诉用户他希望知道的最终信息(程序计算的东西)。

非常感谢我的主要问题“......必须返回 double 类型的结果”的答案,对我在这里提到的其他事情的任何帮助也会有很长的路要走。

此外,正确格式化的代码非常烦人,我不确定告诉我将其间隔 4 个空格是什么意思,每当我这样做并且它有效时,总会有人对其进行编辑,这非常违反直觉。

import java.io.*;
public class circlemethods
{
    public static void main (String [] args) throws IOException
    {
      BufferedReader myInput = new BufferedReader (new InputStreamReader (System.in));
      String numInput;  
      String reqInput;
      int num;
      int numInt = 0;
      System.out.println("This program will ask for a given user radius, then proceed to calculate the req");
      System.out.println("The program will use several methods to achieve this, all calling back to the main method");
      System.out.println("Press any key to continue");
      numInput = myInput.readLine();
      System.out.println("First, what would you like to calculate?");
      System.out.println("Enter '1' for Circumference, '2' for area, '3' for volume, or '4' for surface area");
      reqInput = myInput.readLine();
      numInt = Integer.parseInt (reqInput);
      System.out.println("Now enter the radius of the required shape");
      numInput = myInput.readLine();
      num = Integer.parseInt (numInput); 
    }
    public static  double circumference(double volume, double surfacearea, double area,  double radius) throws IOException {
      int numInt = 0;
      int num = 0;
      double circumference;
      for (int i = 0; i < volume ; i++) {
        if (numInt == 1)
        {
          System.out.println("You chose to calculate circumference, given the radius :"+ num );
          circumference = (3.14) * (2) * (num);
          return  circumference;
        }
        if (numInt == 2)
        {
          System.out.println("You chose to calculate area, given the radius:" + num);
          area = (3.14)*(num)*(num);
          return area;
        }
        if (numInt == 3)
        {
          System.out.println("You chose to calculate volume, given the radius:" + num);
          volume = 4/3 * (3.14)*(num)*(3)*(3)*(3);
          return volume;
        }      
        if (numInt == 4)
        {
          System.out.println("You chose to calculate surface area, given the radius:" + num);
          surfacearea = 4*(3.14)*(num)*(2)*(2);
          return surfacearea;
        }
        else
        {
          System.out.println("Invalid entry, please restart the program");  
        }
      }
    }
  }
4

1 回答 1

0

你的方法应该总是返回一个双精度值。尝试这样的事情:

...

 if (numInt == 4)
 {
   System.out.println("You chose to calculate surface area, given the radius:" + num);
   surfacearea = 4*(3.14)*(num)*(2)*(2);
   return surfacearea;
 }

 else
 {
   return -1;
 }

方法的调用者检查结果,如果它小于 0,它知道它失败并打印:

 System.out.println("Invalid entry, please restart the program");

编辑:

如果根本没有进入循环,那么该方法也应该返回 -1

于 2013-03-16T20:04:35.973 回答