[英]How to get java scanner class to read a file as a argument from cmd
我來自Java代碼,我想使用掃描器類從作為命令行參數的文件中的令牌逐個令牌輸出文件令牌的內容,但對於某些人來說似乎不起作用原因。
import java.io.*;
import java.util.*;
public class HashTable {
public static void main(String args[]) {
File inputfile = new File(args[0]);
try {
Scanner sr = new Scanner(inputfile);
while (sr.hasNextLine()) {
int i = sr.nextInt();
System.out.println(i);
}
sr.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
您需要更改:
int i = sr.nextInt();
通過
字符串i = sr.next();
MisMatchException是由令牌超出范圍引起的(將其轉換為整數)
public static void main( final String[] args )
{
final String input = "1 two 3 four five 6 7";
final Scanner scanner = new Scanner(input);
while ( scanner.hasNext() )
{
if ( scanner.hasNextInt() )
{
System.out.println( "int: " + scanner.nextInt() );
}
else
{
System.out.println ( "String: " + scanner.next() );
}
}
}
代替
int i = sr.nextInt(); System.out.println(i);
采用
System.out.println(sr.nextLine());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.