-1

Just started doing java programming. I searched stackoverflow and saw various solutions for this error but none of them solved the issue in my program. The program stops at "ENDDATA". I'm sure it is a simple fix that I can't seem to figure out:

Contents of student.dat file :

MARY 50 60 70 80
SHELLY 34 56 90 100
JOHN 32 54 66 88
ALFRED 21 100 88 75
ENDDATA

Program output:

 The name of the student is MARY
 His/her average score is 65
 The name of the student is SHELLY
 His/her average score is 70
 The name of the student is JOHN
 His/her average score is 60
 The name of the student is ALFRED
 His/her average score is 71
 The name of the student is ENDDATA
Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:862)
    at java.util.Scanner.next(Scanner.java:1371)
    at Statistics.main(Statistics.java:32)

My code:

     import java.util.*;
        import java.io.*;
        public class Statistics {


        public static void main(String[] args)throws IOException {
        Scanner in = new Scanner (new FileReader("c:\\students.dat"));

        String name;
        int nameCount = 0;
        int avg = 0;
        int spanish = 0;
        int math = 0;
        int french = 0;
        int english = 0;
        int highSpanish = 0;
        int highMath = 0;
        int highFrench = 0;
        int highEnglish = 0;
        int highAvg = 0;
        name = in.next();
        while (name!= "ENDDATA") {
            nameCount++;
            System.out.printf (" The name of the student is " + name + "\n");
            name = in.next();
            spanish = Integer.parseInt(name);
            if (spanish > highSpanish) {
            highSpanish = spanish;
            }
            name = in.next();
            math = Integer.parseInt(name);
            if (math > highMath) {
            highMath = math;
            }
            name = in.next();
            french = Integer.parseInt(name);
            if (french > highFrench) {
            highFrench = french;
            }
            name = in.next();
            english = Integer.parseInt(name);
            if (english > highEnglish) {
            highEnglish = english;
            }
            avg = (spanish + math + french + english) /4;
            if (avg > highAvg) {
            highAvg = avg;
            }
            System.out.printf (" His/her average score is " + avg + "\n");
            name = in.next();
            }
            System.out.printf (" The number of students in the class are " +         nameCount);
            System.out.printf (" The highest student average is " + highAvg);
            System.out.printf (" The highest score for spanish is " + highSpanish);
            System.out.printf (" The highest score for math is " + highMath);
            System.out.printf (" The highest score for french is " + highFrench);
            System.out.printf (" The highest score for english is " + highEnglish);
        }
    }
lambdas
  • 3,990
  • 2
  • 29
  • 54
  • what is the content in c:\\students.dat file? i hope you are getting the exception because of this contents – Shriram Apr 01 '15 at 06:43
  • This again? how about showing us the contents of your students.dat? – jmcg Apr 01 '15 at 06:45
  • Do not use == and != when comparing strings. Use `equals()` – GhostCat Apr 01 '15 at 06:45
  • @EddyG those are not Strings man – jmcg Apr 01 '15 at 06:46
  • 1
    @jmcg So while (name!= "ENDDATA") is not comparing strings. Open your eyes, "man". – GhostCat Apr 01 '15 at 06:47
  • Check your `in.next()` use. There might be no next. That's what causes the `NoSuchElementException`. Consider using `in.hasNext()` in your loop condition. – Ria Apr 01 '15 at 06:50
  • In order to help with your question, you should provide the full stack trace. – GhostCat Apr 01 '15 at 06:51
  • 1
    @EddyG I stand corrected. That is irrelevant, though. – jmcg Apr 01 '15 at 06:59
  • @ChrisLamonte Never put information that is relevant to the question into the comments Update your question instead. It is much easier to format content there. – GhostCat Apr 01 '15 at 07:07
  • possible duplicate of [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Philipp Wendler Apr 01 '15 at 07:35
  • @jmcg that's not irrelevant. It definitely affects the correctness of the program — that's actually why the loop isn't terminating soon enough. – Sean Reilly Apr 01 '15 at 07:37

3 Answers3

1

It's a shame you didnt include the contents of your file. but i hope this helps.

Have a look at this. This is how I normally read from a text file, or any file for that matter:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class TestMain {

public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new FileReader("file.txt"));
    try {
        String oneLineOfYourData = br.readLine();
        while (oneLineOfYourData != null) {
                 // Now depending on how your data is structured, you may consider PARSING the line

                // Then you can insert the rest of your logic here
              oneLineOfYourData = br.readLine();
        }
    } finally {
        br.close();
    }

}

}

I hope this points you to the right direction.

jmcg
  • 1,547
  • 17
  • 22
1

The main problem in your program is that you are comparing Strings using != operator which is incorrect for type String, we use .equals() to compare Strings you have to change :

 while (name!= "ENDDATA") 

To the following:

 while (!name.equals("ENDDATA")) 

And better approach is to use in.hasNext() to chec you reached the end of file instead of checking it manually.

And the noSuchElementException is thrown because of the following statement in.next() you are referring to the next line of the Scanner while it doesn't have any next lines.

Note: Use in.nextInt() to read integer values from your scanner for (spannish, math, ...).

And for a better approach you have to change your while loop like this :

 while (in.hasNext()) {
  name = in.next();
  spanish = in.nextInt(); 
  // and so on
 }
cнŝdk
  • 31,391
  • 7
  • 56
  • 78
  • I made the change to while (name.equals("ENDDATA")). The program now outputs: The number of students in the class are 0 The highest student average is 0 The highest score for spanish is 0 The highest score for math is 0 The highest score for french is 0 The highest score for english is 0 Process completed. – Chris Lamonte Apr 01 '15 at 07:35
  • sorry it's `while (!name.equals("ENDDATA"))` and I think you better use the `while (in.hasNext())`, because if you use ` while (name.equals("ENDDATA"))` you will never enter in the while loop that's why all values are zeros. – cнŝdk Apr 01 '15 at 07:39
  • It worked without using while (in.hasNext()). But I tested it with your suggestion and it gives the following: error: incompatible types: boolean cannot be converted to String name = in.hasNext(); – Chris Lamonte Apr 01 '15 at 07:48
  • No it's not `name = in.hasNext();` !!! you only need to use `hasNext()` in the while loop to check if the scanner doesn't reach the end of the file, but inside it and to get values you have to use `.next()` for Strings and `.nextInt()` for integers. – cнŝdk Apr 01 '15 at 07:50
0

This works if the file content is as you posted it in your comment. Keep in mind that the code relies on the correctness of the data (might fail if some scores are not present etc).

Scanner in = new Scanner(new FileReader("someFile.txt"));
    in.useDelimiter(System.getProperty("line.separator"));

    String line;
    String token;
    int nameCount = 0;
    int avg = 0;
    int spanish = 0;
    int math = 0;
    int french = 0;
    int english = 0;
    int highSpanish = 0;
    int highMath = 0;
    int highFrench = 0;
    int highEnglish = 0;
    int highAvg = 0;

    while (in.hasNext()) {
        line = in.next();

        String[] splittedLine = StringUtils.split(line);
        token = splittedLine[0];
        if ("ENDDATA".equals(token)) {
            break;
        }
        nameCount++;
        System.out.printf(" The name of the student is " + token + "\n");
        token = splittedLine[1];
        spanish = Integer.parseInt(token);
        if (spanish > highSpanish) {
            highSpanish = spanish;
        }
        token = splittedLine[2];
        math = Integer.parseInt(token);
        if (math > highMath) {
            highMath = math;
        }
        token = splittedLine[3];
        french = Integer.parseInt(token);
        if (french > highFrench) {
            highFrench = french;
        }
        token = splittedLine[4];
        english = Integer.parseInt(token);
        if (english > highEnglish) {
            highEnglish = english;
        }
        avg = (spanish + math + french + english) / 4;
        if (avg > highAvg) {
            highAvg = avg;
        }
        System.out.printf(" His/her average score is " + avg + "\n");

    }
    System.out.printf(" The number of students in the class are " + nameCount);
    System.out.printf(" The highest student average is " + highAvg);
    System.out.printf(" The highest score for spanish is " + highSpanish);
    System.out.printf(" The highest score for math is " + highMath);
    System.out.printf(" The highest score for french is " + highFrench);
    System.out.printf(" The highest score for english is " + highEnglish);
}

It produces the output:

The name of the student is MARY
His/her average score is 65
The name of the student is SHELLY 
His/her average score is 70
The name of the student is JOHN
His/her average score is 60
The name of the student is ALFRED
His/her average score is 71
The number of students in the class are 4 The highest student average is 71 
The highest score for spanish is 50 The highest score for math is 100 The  
highest score for french is 90 The highest score for english is 100
Ria
  • 1,900
  • 4
  • 14
  • 21
  • Your program gives this error: The name of the student is MARY Exception in thread "main" java.lang.NumberFormatException: For input string: "80 SHELLY" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:580) at java.lang.Integer.parseInt(Integer.java:615) at Statistics2.main(Statistics2.java:55) Process completed. – Chris Lamonte Apr 01 '15 at 07:11
  • Then my input files is different from yours. Can you please update your question with the data from your file. – Ria Apr 01 '15 at 07:12
  • I already edited it..it is at the beginning of my question & says "contents of student.dat file is:" followed by the data. Further clarification: The format of my file is 5 separate lines of data: MARY 50 60 70 80 then followed by another line of data as presented in my data above, with the final line being ENDDATA – Chris Lamonte Apr 01 '15 at 07:19
  • I edited my answer, it should work now. You could also use the `Scanner` with multiple delimiters instead of using the `StringUtils.split` (from commons-lang) method (to split each line by whitespace). – Ria Apr 01 '15 at 08:24