[Java] 判斷字串是否是整數

有時候必須知道輸入的字串是否是整數,如果不是的話,就要重新輸入,這有兩種作法 第一種是使用 try … catch … finally 的方法,如下

public class test
{ 
	public static void main(String args[])
  {
    BufferedReader buf = new BufferedReader(new InputStreamReader(System.in)); 
    try{
      System.out.print("請輸入你要的數字:");
      int test = Integer.parseInt(buf.readLine()); 
    }
    catch(ArrayIndexOutOfBoundsException e)
    {
      System.out.println(e.toString() + "陣列程式發生錯誤");  
    }
    catch(ArithmeticException e)
    {
      System.out.println(e.toString() + "數學發生錯誤");  
    }
    catch(Exception e)
    {
      System.out.println(e.toString() + "程式發生錯誤");
    }
    finally
    {
      System.out.println("執行成功");  
    }
	
  }
}
另外一種方法,是利用 while 然後利用 Character.isDigit 的方法 e> 然後在 javaworld 版,看到有人介紹 String與基本資料型態(int byte...等)之間的轉換 如下

轉錄自java連線版 發信人: TAHO, 看板: java 精華區 標 題: String與基本資料型態(int byte…等)之間的轉換 發信站: 140.126.22.6 竹師風之坊 Origin: Local 1. 由 基本資料型態轉換成 String String 類別中已經提供了將基本資料型態轉換成 String 的 static 方法 也就是 String.valueOf() 這個參數多載的方法 有下列幾種 String.valueOf(boolean b) : 將 boolean 變數 b 轉換成字串 String.valueOf(char c) : 將 char 變數 c 轉換成字串 String.valueOf(char[] data) : 將 char 陣列 data 轉換成字串 String.valueOf(char[] data, int offset, int count) : 將 char 陣列 data 中 由 data[offset] 開始取 count 個元素 轉換成字串 String.valueOf(double d) : 將 double 變數 d 轉換成字串 String.valueOf(float f) : 將 float 變數 f 轉換成字串 String.valueOf(int i) : 將 int 變數 i 轉換成字串 String.valueOf(long l) : 將 long 變數 l 轉換成字串 String.valueOf(Object obj) : 將 obj 物件轉換成 字串, 等於 obj.toString() 用法如: int i = 10; String str = String.valueOf(i); 這時候 str 就會是 “10” 2. 由 String 轉換成 數字的基本資料型態 要將 String 轉換成基本資料型態轉 大多需要使用基本資料型態的包裝類別 比如說 String 轉換成 byte 可以使用 Byte.parseByte(String s) 這一類的方法如果無法將 s 分析 則會丟出 NumberFormatException byte : Byte.parseByte(String s) : 將 s 轉換成 byte Byte.parseByte(String s, int radix) : 以 radix 為基底 將 s 轉換為 byte 比如說 Byte.parseByte(“11”, 16) 會得到 17 double : Double.parseDouble(String s) : 將 s 轉換成 double float : Double.parseFloat(String s) : 將 s 轉換成 float int : Integer.parseInt(String s) : 將 s 轉換成 int long : Long.parseLong(String s) : 將 s 轉換成 long 用法如:

try
{
  String str = "1234";
  int a = Integer.parseInt(str);
}
catch (NumberFormatException e)
{
  System.out.println(" parse int error!!  " + e);
}
http://www.javaworld.com.tw/jute/post/view?bid=29&id=9557

See also