我使用以下逻辑从字符串中提取 double 值。它在第一个字符串上工作正常,但在第二个字符串上引发异常。引发的异常是java.util.NoSuchElementException
。
public class StringHandling {
public String processString(String string)
{
Scanner st = new Scanner(string);
while (!st.hasNextDouble())
{
st.next();
}
double value = st.nextDouble();
return String.valueOf(value);
}
public static void main(String[] args)
{
String first = "Hey, he is 70.3 miles away.";
String second = "{\"Hey\", \"he\" \"is\": 1.0, \"miles\" away}";
StringHandling sh = new StringHandling();
System.out.println("First Value is "+sh.processString(first));
System.out.println("Second Value is "+sh.processString(second));
}
}
我只是想知道为什么它会引发异常。
最佳答案
这就是问题:
"{\"Hey\", \"he\" \"is\": 1.0, \"miles\" away}"
默认情况下,Scanner
类的 next
方法会为您提供下一个输入,直到到达空格为止。
next
方法会像这样获取它:
{"Hey",
"he"
"is":
1.0,
"miles"
away}
在这种情况下,您有 1.0,
,它不是 double
(注意逗号)。
这就是为什么你会得到一个 NoSuchElementException
:你继续执行 st.next()
,但是永远找不到 double
,所以结束已到达字符串的 ,并且扫描程序未找到其他元素。
关于java - 从字符串中提取 double 值获取 java.util.NoSuchElementException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25501993/