我试图尝试我发现的这个代码。如果输入两个连续的数字(以空格分隔),则第一个数字标识为long,但第二个数字不标识。
import java.util.*;
public class ScannerDemo {
public static void main(String[] args) {
String s = "Hello World! 35 62 + 3.0 = 6.0 true ";
Long l = 13964599874l;
s = s + l;
// create a new scanner with the specified String Object
Scanner scanner = new Scanner(s);
// find the next long token and print it
// loop for the whole scanner
while (scanner.hasNext()) {
// if no long is found, print "Not Found:" and the token
System.out.println("Not Found: " + scanner.next());
// if the next is a long, print found and the long
if (scanner.hasNextLong()) {
System.out.println("Found: " + scanner.nextLong());
}
}
// close the scanner
scanner.close();
}
}
结果:
Not Found :Hello
Not Found :World!
Found :35
Not Found :62
Not Found :+
Not Found :3.0
Not Found :=
Not Found :6.0
Not Found :true
Found :13964599874
为什么62找不到?
答案 0 :(得分:0)
在您的代码中,“未找到”行需要一个条件,例如
if (!scanner.hasNextLong())
目前,该行代码在每次迭代时获取下一个元素,无论该元素是否为long。这就是为什么62没有被检测到但35是。在带有条件的第二个语句找到35之后,第一个语句正在处理62。
答案 1 :(得分:0)
您可以尝试查看字符串中的每个单词,并仅过滤掉可以制作为Longs的标记
String s = "Hello World! 35 62 + 3.0 = 6.0 true ";
Long l = 13964599874l;
s = s + l;
Long temp;
for (String word : s.split("\\s+"))
{
if (word.length()>10 && word.length() < 20) {
try{
Long.parseLong(word);
System.out.println(word+ " is a Long");
}catch(IllegalArgumentException ex){
}
}
}
输出:
13964599874 is a Long
这样你也可以消除有符号整数。只拉长型
答案 2 :(得分:0)
您可以在其他地方移动未找到的代码,例如:
// if the next is a long, print found and the long
if (scanner.hasNextLong()) {
System.out.println("Found :" + scanner.nextLong());
}else{
System.out.println("Not Found :" + scanner.next());
}