I have a file: student.txt
1 Adam 50 50 50
2 Eric 34 28 38
3 Joash 44 48 49
4 Bill 34 30 45
I have 2 classes: 1 is main and another one does all the work.
// Class 1 ******************
public class Main {
public static void main(String[] args) {
readfile a = new readfile();
a.openFile();
a.readFile();
a.closeFile();
}
}
// ********* Class 2
import java.util.*;
import java.io.*;
import java.lang.*;
public class readfile {
private Scanner x;
public void openFile(){
try{
x = new Scanner(new File("student.txt"));
}
catch(Exception e){
System.out.println("Error");
}
}
public void readFile(){
int a=0;
String b;
int c=0;
int d = 0;
int e = 0;
int total;
while(x.hasNext()){
a = x.next();
b = x.next();
c = x.next();
d = x.next();
e = x.next();
int total = c+d+e;
total = x.nextInt();
System.out.printf("%s %s %s %s %s %s/n",a,b,c,d,e,total);
}
}
public void closeFile(){
x.close();
}
}
I have 2 errors:
1) This is at a = x.next();
where it says
Can't convert from String to int.
Can you tell me how to fix that?
2) This is at:
Exception in thread "main"
Error java.lang.NullPointerException
How do I fix this?
Try:
a = Integer.parseInt(x.next());
Instead of
a = x.next();
And you may try using
a = x.nextInt();
Scanner.next() returns the next token as a String. When java tries to set int a to a String, an error occurs. You can fix this by using Scanner.nextInt(), which will return the next token as an integer, or throw an error if the next token is not an int. If
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.