JAVA 點check input係唔係integer?

2007-09-22 10:04 am
JAVA 點check input係唔係integer?
要用咩funciton??
更新1:

仲有點將string 轉做integer?? public class inttt { public static void main(String[] args) { System.out.println(args[0]); }//mian }//public run prohram時我要打 java inttt -x x要係一個integer, 會store 係 args. 我要check args係唔係integer 同埋要args 由string 轉做integer 先可繼續做落去.

回答 (2)

2007-09-22 11:18 am
✔ 最佳答案
Method 1: use regular expression

import java.util.regex.*;
Pattern integerPattern = Pattern.compile("^\d*$");
Matcher matchesInteger = integerPattern.matcher(myString);
boolean isInteger = matchesInteger.matches();

or
boolean isInteger = Pattern.matches("^\d*$", myString);

Methid 2: Integer.parseInt() method
praseInt() will convert string to integer

int i;
bool isNumeric = false;
try
{
i = Integer.parseInt(myString);
isNumeric = true;
// did not throw error, myString is numeric
}
catch(NumberFormatException eX)
{
// threw an error, myString is not a number
isNumeric = false;
}
2007-09-22 10:53 am
try {

int i = Integer.parseInt(args[0].trim()); //成功convert 左o既話就會直接store左i 度

}
catch(NumberFormatException e) {
e.printStackTrace();
}


收錄日期: 2021-04-23 00:17:12
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20070922000051KK00383

檢視 Wayback Machine 備份