自定义方法出错“...必须返回double类型的结果”

时间:2013-03-16 19:59:07

标签: java methods

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

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

回答我的主要问题" ...必须返回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");  
        }
      }
    }
  }

1 个答案:

答案 0 :(得分: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