[英]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.