parseObject()方法是java.text.NumberFormat的内置方法,该方法从字符串中解析文本以产生Number。该函数尝试解析从给定索引开始的文本。发生解析时,给定索引设置为使用的最后一个字符,如果解析失败,则给定索引不变,错误索引设置为发生错误的索引。
用法:
public final Object parseObject(String source, ParsePosition pos)
参数:该函数接受以下两个参数:
source:指定要解析的字符串
pos:按照说明,使用索引和错误索引信息指定ParsePosition对象
返回值:该函数返回一个布尔值,如果数字可以解析为整数,则返回true,否则返回false。
异常注意:如果source或pos初始化为null,则该函数将引发NullPointerException。
下面是上述功能的实现:
程序1:
// Java program to implement
// the above function
import java.text.NumberFormat;
import java.util.Locale;
import java.text.ParsePosition;
public class Main {
public static void main(String[] args)
throws Exception
{
// Get the instance
NumberFormat nF
= NumberFormat.getNumberInstance();
// Prints the parsed number or NULL
System.out.println(nF
.parseObject("456",
new ParsePosition(0)));
}
}
输出:
456
示例2:
// Java program to implement
// the above function
import java.text.NumberFormat;
import java.util.Locale;
import java.text.ParsePosition;
public class Main {
public static void main(String[] args)
throws Exception
{
try {
// Get the instance
NumberFormat nF
= NumberFormat.getNumberInstance();
// Prints the parsed number or NULL
System.out.println(
nF
.parseObject(null,
new ParsePosition(0)));
}
catch (Exception e) {
System.out.println("Exception: "
+ e);
}
}
}
输出:
Exception: java.lang.NullPointerException