[英]Java: How to check with a scanner to see if a file contains integers or words?
我需要將文本文件存儲到鏈表中。 我得到一個文本文件,如:1 2 3 4 5當我試圖說scan.next它說沒有元素異常。 但我還需要考慮這樣一個文件:Michael Hannah Josephus Ruth Matthew所以我不能只說nextInt,因為它可能是一個字符串。 如何檢查其整數或字符串? 謝謝! 我的代碼:
Scanner sc = new Scanner(f);
int k = 1;
String line = new String(sc.next());
ListNode nodes = new ListNode(n, null);
while(k < n - 1)
{
line = sc.nextLine();
nodes.setNext(new ListNode(n, null));
}
line = sc.nextLine();
ListNode last = new ListNode(n, null);
nodes.setNext(last);
return nodes;
您可以對所有令牌使用Scanner.next()
,然后只對整數令牌執行Integer.parseInt()
。
這是一個例子:
File f = new File("myfile.txt");
Scanner scn = new Scanner(f);
String s = "";
while(scn.hasNext()) {
s=scn.next();
try {
Integer.parseInt(s);
//if the code made it to this line, s is an int, handle at as such
} catch(NumberFormatException e) {
//s is a string, handle it as such
}
}
只需一條建議,即使下一個標記是整數, hasNext()
也會成立。 因此,您不能使用hasNext()
來確定文件是由Ints還是字符串組成。 但是,如果您事先知道該文件屬於一種類型(沒有混合情況),則以下內容也可以:
if(scn.hasNextInt()) { //if true, you know that this file is ints
while(scn.hasNextInt()) {
int i = scn.nextInt(); //handle all as ints
}
} else { //otherwise the file is strings
while(scn.hasNext()) {
String s = scn.next();
//handle all as strings
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.