无法为象限检查程序创建正确的方法

时间:2011-10-26 21:40:53

标签: java

我不确定如何使用只返回字符的if / else语句来使用public static方法。该程序应该采用x,y并返回坐标所在的象限。 (java的菜鸟!)

import javax.swing.JOptionPane;

public class Assignment13 {

    public static void main(String[] args) {
        String userInputx,
            userInputy;
        double x, y, answer;

        userInputx = JOptionPane.showInputDialog("Please enter your x coordinate.");
        x = Double.parseDouble(userInputx);

        userInputy = JOptionPane.showInputDialog("Please enter your y coordinate.");
        y = Double.parseDouble(userInputy);

        answer = MethodQuad.quadrant(x, y);

        System.out.println("The coordinates " + x + y + "are located Quadrant " + answer);
    }
}

class MethodQuad {

    public static double quadrant(double x, double y) {

        if (x > 0 && y > 0) {
            return System.out.println("1");
        } else if (x < 0 && y > 0) {
            return System.out.println("2");
        } else if (x < 0 && y < 0) {
            return System.out.println("3");
        } else if (x < 0 && y > 0) {
            return System.out.println("4");
        } else {
            return System.out.println("0");
        }
    }
}

2 个答案:

答案 0 :(得分:2)

您告诉方法它将在其签名行中返回一个double:

public static double quadrant(double x, double y)

编译器不会喜欢这个,因为该方法实际上并不返回double(也不应该)。我建议您更改该行,以便它知道它将返回字符串。你可能知道怎么做,对吗?

另外,在你的课堂上,你宣称答案是一个双重变量,这在理论上是不合理的:

double x, 
       y,
  answer; 

应将answer声明为哪种变量类型?

修改
您还需要发布作业说明,以便我们确切了解您应该做什么。你可能会回答一个int并让方法返回一个int - 如果那是教师想要的。所以,让我们看看他们告诉你的事情。

答案 1 :(得分:2)

它的工作方式与其他编程语言类似。如果你写了返回值,你必须返回一些值)

 class MethodQuad {
 public static int quadrant(double x, double y)
 {

   if(x > 0 && y > 0)
     return 1;
   else if(x < 0 && y > 0)
     return 2;
   else if(x < 0 && y < 0)
     return 3;
   else if (x<0 && y >0) 
     return 4; 
   else 
     return 0;
  }
}