2011-10-26 19 views
0

我不確定如何正確使用帶有隻返回字符的if/else語句的公共靜態方法。該程序應該帶上x,y並返回座標所在的象限。 (A小白到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"); 
     } 
    } 
} 
+0

剛一說明:我覺得一個象限功能,可以返回五個* *值之一有效座標是有點...不必要的複雜和任意數學。除非你被告知要這麼做,否則我會建議使用> = 0和<0,那麼軸和原點也算在象限中。 – Boann

回答

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; 
    } 
} 
2

你告訴,將在其簽名行返回一個雙重的方法:

public static double quadrant(double x, double y) 

編譯器會不喜歡這樣,因爲該方法不實際上返回一個雙倍(也不應該)。我建議你改變這條線,以便它知道它會返回一個字符串。你可能知道如何做到這一點,對吧?

而且,在你的類,你宣佈答案是雙變量不使邏輯意義:

double x, 
     y, 
    answer; 

應該answer聲明爲哪些變量類型?

編輯
你也想發佈您的作業指令,因此我們可以看到你應該做什麼。你可能會回答一個int,並讓該方法返回一個int - 如果這是老師想要的。讓我們看看他們告訴你做什麼。

+1

+1指導;對於干預的重新格式感到抱歉。 – trashgod