0

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?

2
  • What does x.next() return? What are you assigning it to? Commented Aug 2, 2014 at 2:10
  • Why do this int total = c+d+e; and then change it in the next line anyway with this total = x.nextInt();? Commented Aug 2, 2014 at 2:46

2 Answers 2

1

Try:

a = Integer.parseInt(x.next());

Instead of

a = x.next();

And you may try using

a = x.nextInt();
Sign up to request clarification or add additional context in comments.

5 Comments

Why not just use x.nextInt()?
Because then you don't have to use the extra code of Integer.parseInt() for no reason.
Why am i still getting an error at the line: int total = x.nextInt(); ??
O God! Try total = Integer.parseInt(x.next()); too
You should do basic at first :-)
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.