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