2012-11-08 31 views
0

我想確定一個字符串是否包含正整數。我的代碼是:java中的比較問題[.equals()]

public void isInt(String str) throws NotIntException{ 
    String integer=str.replaceAll("\\d",""); 
    System.out.println(integer); 
    if (!integer.equals("")){ 
     throw new NotIntException("Wrong data type-check fields where an integer"+ 
     " should be."); 
    }//end if 
    if (integer.equals("-")){ 
     System.out.println(integer); 
     throw new NotIntException("Error-Can't have a negative count."); 
    }//end if 
}//end method 

我正在用一個字符串「-1」測試它,它應該在replaceAll()之後變成「 - 」。這應該輸入兩個if語句。但它只進入第一個。我也嘗試過==的比較,以防萬一,但它也不起作用。對我來說奇怪的是,無論我期望完成第二個if語句的條件還是實現它的否定[即!integer.equals(「 - 」)],程序仍然不會進入if ...

謝謝,通常我的比較問題,只是我缺少一些基本的東西,但我真的看不到任何東西在這裏...

+1

你就不能'的Integer.parseInt()',看看它是否拋出或是否定的? – Esailija

+0

如果它進入第一個並拋出異常......它應該如何進入第二個?困惑 – Affe

+0

@Esailija sry,我讀過你的評論,有同樣的方法,看到我的答案。 – jlordo

回答

3

既然你如果拋出一個異常,你的第一個如果,那麼,你的第二個將不甚至被測試。

if (!integer.equals("")){ 
    throw new NotIntException("Wrong data type-check fields where an integer"+ 
    " should be."); 
} 

if (integer.equals("-")){ 
    System.out.println(integer); 
    throw new NotIntException("Error-Can't have a negative count."); 
} 

如果你的代碼進入第一if,也不會進一步執行。


但是,爲什麼你使用這種方法來解決你的問題。您可以使用Integer.parseInt來檢查有效的integer。然後如果它是有效的,那麼測試它是否是less than 0。這將是更容易和可讀性。

+0

哦,對......謝謝! –

0

如果你想簡單地從一個字符串中讀取一個int,使用Integer.parseInt(),儘管如果你想查看一個字符串「是」是一個int還是不包含一個int。

您可以使用Integer.parseInt()和循環策略的組合來查看它是否相當容易地包含一個int,然後檢查它是否爲正值。

0

你的方法太複雜了。我會保持它的簡單:

if (integer.startsWith("-")) { 
    // it's a negative number 
} 

if (!integer.matches("^\\d+$")) { 
    // it's not all-numbers 
} 

,忘記調用replaceAll()

1

我的解決辦法:

public static boolean isPositiveInt(String str) { 
    try { 
     int number = Integer.parseInt(str.trim()); 
     return number >= 0; 
    } catch (NumberFormatException e) { 
     return false; 
    } 
}