Re: [問題] 輸入分辨字串與數字

作者: qwerty0981 (帳號活動中止日20150131)   2014-11-09 17:55:49
※ 引述《j94223 (笨肌)》之銘言:
: 大家好 我第一次在這邊發文 若排版不好看請多多包涵
: 我剛學java不到兩個月
: 我現在遇到了一個問題
: 我想讓程式判斷我輸入的是字串(字元)或是數字
: 若是字串(字元)則執行A運算
: 若是數字則執行B運算
: 請問這樣要怎麼寫出來?
: 謝謝各位!
你必須定義結果域為何。
否則以numeric來說,此時又沒別的lib情況下,
我寧可try catch + BigDecimal,
多一點額外開銷,但結果會對。
_____________________________________________________________
import static java.lang.System.out;
import java.math.BigDecimal;
import java.util.Scanner;
/**
* @author qwerty@qwerty.tw
* @version 14.11
*
*/
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
String input = new Scanner(System.in).next();
BigDecimal bd = null;
try {
bd = new BigDecimal(input);
} catch(Exception e) {
// I dont care
}
if(bd == null) {
out.println(input + " is not numeric.");
} else {
out.println(input + " is numeric.");
}
}
}
StackOverflow上有很多討論,可以先google之。
作者: j94223 (笨肌)   2014-11-09 19:10:00
謝謝

Links booklink

Contact Us: admin [ a t ] ucptt.com