I've got from code for java which I want to use the scanner class to output the contents of the file token by token from a file that was as an argument from the command line but it doesn't seem to work for me for some reason.
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();
}
}
}
You need to change:
int i = sr.nextInt();
by
String i = sr.next();
MisMatchException is caused by token out of range (to be converted into integer)
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() );
}
}
}
instead of
int i = sr.nextInt(); System.out.println(i);
use
System.out.println(sr.nextLine());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.