本文介紹了為什么 DecimalFormat 允許字符作為后綴?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
限時送ChatGPT賬號..
我正在使用 DecimalFormat
來解析/驗證用戶輸入.不幸的是,它允許在解析時將字符作為后綴.
I'm using DecimalFormat
to parse / validate user input. Unfortunately it allows characters as a suffix while parsing.
示例代碼:
try {
final NumberFormat numberFormat = new DecimalFormat();
System.out.println(numberFormat.parse("12abc"));
System.out.println(numberFormat.parse("abc12"));
} catch (final ParseException e) {
System.out.println("parse exception");
}
結果:
12
parse exception
我實際上希望它們都出現解析異常.如何告訴 DecimalFormat
不允許像 "12abc"
這樣的輸入?
I would actually expect a parse exception for both of them. How can I tell DecimalFormat
to not allow input like "12abc"
?
推薦答案
來自NumberFormat.parse
:
從給定字符串的開頭解析文本以生成一個數字.該方法可能不會使用給定字符串的整個文本.
Parses text from the beginning of the given string to produce a number. The method may not use the entire text of the given string.
這是一個示例,可以讓您了解如何確保考慮整個字符串.
Here is an example that should give you an idea how to make sure the entire string is considered.
import java.text.*;
public class Test {
public static void main(String[] args) {
System.out.println(parseCompleteString("12"));
System.out.println(parseCompleteString("12abc"));
System.out.println(parseCompleteString("abc12"));
}
public static Number parseCompleteString(String input) {
ParsePosition pp = new ParsePosition(0);
NumberFormat numberFormat = new DecimalFormat();
Number result = numberFormat.parse(input, pp);
return pp.getIndex() == input.length() ? result : null;
}
}
輸出:
12
null
null
這篇關于為什么 DecimalFormat 允許字符作為后綴?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!