2011-02-10 32 views
13

例如,我想創建一個可以返回任意數字(負數,零或正數)的函數。如何編寫返回多個數據類型值的Java函數?

然而,根據某些例外情況,我想函數返回BooleanFALSE

有沒有編寫能夠返回int一個Boolean功能的方法嗎?


好的,所以收到了很多回應。我明白我只是不正確地接近這個問題,我應該在該方法中的某種例外情況下應用throw。爲了得到更好的答案,我將提供一些示例代碼。請不要取笑:)

public class Quad { 

    public static void main (String[] args) { 

    double a, b, c; 

    a=1; b=-7; c=12; 
    System.out.println("x = " + quadratic(a, b, c, 1)); // x = 4.0 
    System.out.println("x = " + quadratic(a, b, c, -1)); // x = 3.0 


    // "invalid" coefficients. Let's throw an exception here. How do we handle the exception? 
    a=4; b=4; c=16; 
    System.out.println("x = " + quadratic(a, b, c, 1)); // x = NaN 
    System.out.println("x = " + quadratic(a, b, c, -1)); // x = NaN 

    } 

    public static double quadratic(double a, double b, double c, int polarity) { 

    double x = b*b - 4*a*c; 

    // When x < 0, Math.sqrt(x) retruns NaN 
    if (x < 0) { 
     /* 
     throw exception! 
     I understand this code can be adjusted to accommodate 
     imaginary numbers, but for the sake of this example, 
     let's just have this function throw an exception and 
     say the coefficients are invalid 
     */ 
    } 

    return (-b + Math.sqrt(x) * polarity)/(2*a); 

    } 

} 
+2

你已經有了很多答案,所以你可以看到它是可能的,但不是很好。我建議你解釋一下你需要什麼。那麼你很可能會得到一個更好的解決方案。順便說一句,異常也可以通過拋出異常來表示。返回Boolean.FALSE並從不返回Boolean.TRUE是一種代碼異味,請考慮返回Integer,返回空值而不是FALSE。 – maaartinus 2011-02-10 03:04:19

+2

使用返回值是C風格的編程。並不是說這有什麼不妥,而是考慮例外。這是他們的目標。 – duffymo 2011-02-10 03:05:20

回答

12

不,你不能在Java中這樣做。

雖然您可以返回Object。通過返回一個對象,你可以在技術上返回派生類,如java.lang.Integerjava.lang.Boolean。但是,我不認爲這是最好的主意。

5

沒有。你可以做的最好的事情是返回一個類的實例,該類處理所有你可能想要返回的東西。

public class ReturnObj { 
    public bool yesno; // yes or no 
    public int val; // for int values 
    public String mode; // mode describing what you returned, which the caller will need to understand. 
} 

顯然,你需要的名字玩....

而且,這似乎是一個代碼味道。您可以通過限定您想要的功能之外的路徑,然後調用特定的函數來獲取布爾型或特定函數來獲取int,這取決於限定條件,您可能不需要執行此類操作。

+0

你可能應該使用`Enum`,而不是`String` – 2016-12-22 00:46:49

1

不,一個返回給客戶的參考。

您可以編寫一個響應對象,它將一個布爾值和一個int值封裝在一起,並根據您的喜好設置值。

但是,如果我是一個用戶,我會認爲你的設計很混亂。

3

編寫一個返回Object的函數。讓它返回BooleanInteger包裝對象。然後使用instanceof來確定要使用哪個。

0

這可能不是最好的解決方案,取決於你想要做什麼,但一個簡單的方法來解決問題可能是該函數返回一個int或一個常量超出可能的範圍(如RETURNED_FALSE/TRUE)並檢查這一點。

10

你可以在技術上做到這一點:

public <T> T doWork() 
{ 
    if(codition) 
    { 
     return (T) new Integer(1); 
    } 
    else 
    { 
     return (T) Boolean.FALSE; 
    } 
} 

那麼這段代碼編譯:

int x = doWork(); // the condition evaluates to true 
boolean test = doWork(); 

但你肯定可能會遇到運行時異常,如果該方法返回錯誤的類型。您還必須返回對象而不是基元,因爲T將被擦除爲java.lang。對象,這意味着返回的類型必須擴展Object(即成爲一個對象)。上面的示例使用自動裝箱來實現原始返回類型。

我當然不會推薦這種方法,因爲IMO需要評估你對異常處理的使用。如果您可以對該異常執行某些操作(例如恢復,保留,重試等),則可以在特殊情況下捕獲異常。例外情況是例外與預期的工作流程不同,而不是其中的一部分。

1

我的老師有一個很酷的想法對的TryParse C#與Java方法,希望它有助於

import java.util.Scanner; 

public class Program { 
    static Scanner scanner = new Scanner(System.in); 
    public static void main(String[] args) { 
     System.out.println("Enter number"); 
     String input = scanner.next(); 
     int[] num ={0}; 
     if(tryParse(input,num)) 
      System.out.println(num[0] * num[0]); 
    } 
    static boolean tryParse(String inputString,int[] outputInt){ 
     try{ 
      outputInt[0] = Integer.parseInt(inputString); 
      return true; 
     }catch(Exception e){ 
      return false; 
     } 
    } 
} 
-2

inout參數僅適用於可以被突變的對象。對於String inout參數,傳遞StringBuilders而不是Strings,然後替換()它們的值。

2

IEEE浮點

大多數語言將處理您的具體的例子沒有異常或聯合類型,因爲IEEE浮點包括楠表示。在Java中,使用Double.NaN:

public static double quadratic(double a, double b, double c, int polarity) { 
    double x = b*b - 4*a*c; 

    // When x < 0, Math.sqrt(x) retruns NaN 
    if (x < 0) { 
     return Double.NaN; 
    } 
    return (-b + Math.sqrt(x) * polarity)/(2*a); 
} 

產生你想要的精確輸出:

x = 4.0 
x = 3.0 
x = NaN 
x = NaN 

例外

例外是解決類似問題的舊式Java方式:

public static double quadratic(double a, double b, double c, int polarity) { 
    double x = b*b - 4*a*c; 
    // When x < 0, Math.sqrt(x) returns NaN 
    if (x < 0) { 
     throw new Exception("NaN") 
    } 
    return (-b + Math.sqrt(x) * polarity)/(2*a); 
} 

這是您的異常客戶端代碼。

a=1; b=-7; c=12; 

// x = 4.0 
try { 
    System.out.println("x = " + quadratic(a, b, c, 1)); 
} catch (Exception iae) { 
    System.out.println("Oopsie: " + iae.getMessage()); 
} 

// x = 3.0 
try { 
    System.out.println("x = " + quadratic(a, b, c, -1)); 
} catch (Exception iae) { 
    System.out.println("Oopsie: " + iae.getMessage()); 
} 

// "invalid" coefficients. 
a=4; b=4; c=16; 

// Oopsie: NaN 
try { 
    System.out.println("x = " + quadratic(a, b, c, 1)); 
} catch (Exception iae) { 
    System.out.println("Oopsie: " + iae.getMessage()); 
} 

// Oopsie: NaN 
try { 
    System.out.println("x = " + quadratic(a, b, c, -1)); 
} catch (Exception iae) { 
    System.out.println("Oopsie: " + iae.getMessage()); 
} 

聯合類型

要真正傳遞或返回不相關的類型或從一個方法,你想要的Java真的不支持聯合類型。但Paguro提供Union Types,你可以在Java中使用這樣的(使用OR):

public static Or<Double,String> quadratic(double a, double b, 
              double c, int polarity) { 
    double x = b*b - 4*a*c; 

    // When x < 0, Math.sqrt(x) retruns NaN 
    if (x < 0) { 
     return Or.bad("NaN"); 
    } 
    return Or.good((-b + Math.sqrt(x) * polarity)/(2*a)); 
} 

@Test public void testQuadradic() { 
    double a, b, c; 
    a=1; b=-7; c=12; 

    // x = Good(4.0) 
    System.out.println("x = " + quadratic(a, b, c, 1)); 

    // x = 3.0 
    System.out.println(
      (String) quadratic(a, b, c, -1) 
        .match(good -> "x = " + good, 
          bad -> "Oopsie: " + bad)); 

    // "invalid" coefficients. 
    a=4; b=4; c=16; 

    // x = Bad("NaN") 
    System.out.println("x = " + quadratic(a, b, c, 1)); 

    // Oopsie: NaN 
    System.out.println(
      (String) quadratic(a, b, c, -1) 
        .match(good -> "x = " + good, 
          bad -> "Oopsie: " + bad)); 
} 

結論

爲了您的具體的例子,只是使用浮點。對於更一般的解決方案,我發現聯合類型比Exceptions更有用。您可以使用聯合類型作爲可能採用兩個不具有通用接口或祖先的不同輸入的方法的參數。他們對函數式編程也更友好。

-1

我會說這是可能的。但不直接。

我還沒有經過問題中給出的程序。我知道這是一箇舊帖子,我正在回答這個問題。可能幫助某人。

將您的值添加到下面的地圖。並用它的鑰匙獲得它!

public static HashMap returnAnyType(){ 
    String x = "This"; 
    int a = 9; 

    HashMap myMap = new HashMap(); 
    myMap.put("stringVal", x); 
    myMap.put("intVal", a); 
    return myMap; 
} 

String theStringFromTheMap = (String) returnAnyType().get("stringVal"); 
int theIntFromTheMap = (Integer) returnAnyType().get("intVal"); 

System.out.println("String : " + theStringFromTheMap + " is great !"); 
System.out.println("Integer: " + theIntFromTheMap + 10); 

輸出(兩者都來自相同的方法返回):

 
String : This is great! 
Integer: 19 

注:
這是不是一個好的做法。但它有時會在需要時幫助!

相關問題