Question

Java programming help My program wont run. could someone tell me why. everything seems correct to...

Java programming help

My program wont run. could someone tell me why. everything seems correct to me...

giving me the error:

Exception in thread "main" java.lang.NumberFormatException: For input string: "Stud"

at java.base/java.lang.NumberFormatException.forInputString(Unknown Source)

at java.base/java.lang.Integer.parseInt(Unknown Source)

at java.base/java.lang.Integer.parseInt(Unknown Source)

at Util.readFile(Util.java:35)

at Driver.main(Driver.java:8)

_________________________________________________________________________________________________________________________

Program Prompt:

Write a program to perform statistical analysis of scores for a class of students.The class may have up to 40 students.There are five quizzes during the term. Each student is identified by a four-digit student ID number.

The program is to print the student scores and calculate and print the statistics for each quiz. The output is in the same order as the input; no sorting is needed. The input is to be read from a text file. The output from the program should be similar to the following:

Here is some sample data (not to be used) for calculations:

Stud Q1 Q2 Q3 Q4 Q5

1234 78 83 87 91 86

2134 67 77 84 82 79

1852 77 89 93 87 71

High Score 78 89 93 91 86

Low Score 67 77 84 82 71

Average     73.4    83.0    88.2     86.6    78.6

The program should print the lowest and highest scores for each quiz.

_________________________________________________________________________________________________________

PROGRAM and txt file below

public class Driver

{

public static void main(String[] args)

{

Student arrStudent[] = new Student[40];

int studentCount=0;

arrStudent = Util.readFile("C:\\Users\\JamesJr\\eclipse-workspace\\test\\src\\Data.txt", arrStudent);

// find number of lines from file. which will show number of students in array.

studentCount= Util.studentCount;

Statistics s = new Statistics();

// print student data fetched from file

for(int i = 0; i<studentCount; i++)

{

arrStudent[i].printData();

}

// print statistics of students

s.printStatistics(arrStudent,studentCount);

}

}

____________________________________________________________________________________________

import java.io.*;

import java.util.StringTokenizer;

public class Util

{

static int studentCount;

static Student [] readFile(String filename, Student [] stu)

{

//Reads the file and builds student array.

int i=0;

try

{

//Open the file using FileReader Object.

FileReader file = new FileReader(filename);

BufferedReader buff = new BufferedReader(file);

boolean eof = false;

while (!eof)

{

//In a loop read a line using readLine method.

String line = buff.readLine();

if (line == null)

eof = true;

else

{

// System.out.println(line);

stu[i]= new Student();

//Tokenize each line using StringTokenizer Object

StringTokenizer st = new StringTokenizer(line);

while(st.hasMoreTokens())

{

//Value is then saved in the right property of Student Object.

stu[i].setSID(Integer.parseInt(st.nextToken()));

int[] arr= new int[5];

for(int j=0;j<5;j++)

{

//Each token is converted from String to Integer using parseInt method

arr[j]= Integer.parseInt(st.nextToken());

}

//Value is then saved in the right property of Student Object.

stu[i].setScores(arr);

  

}

}

i++;

}

buff.close();

} catch (IOException e)

{

System.out.println("Error -- " + e.toString());

}

studentCount = i-1;

return stu;

}

  

}

___________________________________________________________________________________________________

public class Statistics

{

private int[] lowscores= new int[5];

private int[] highscores= new int[5];

private float[] avgscores= new float[5];

  

void findlow(Student[] a, int c)

{

// finds low score.

int i=0;

for(i=0;i<5; i++)

{

int[] temp= a[0].getScores();

int min = temp[i];

for(int j=0; j< c; j++)

{

int[] s= a[j].getScores();

if(min > s[i])

{

min = s[i];

}

}

lowscores[i]= min;

}

}

//find high score

void findhigh(Student[] a, int c)

{

int i=0;

for(i=0;i<5; i++)

{

int[] temp= a[0].getScores();

int max = temp[i];

for(int j=0; j< c; j++)

{

int[] s= a[j].getScores();

if(max < s[i])

{

max = s[i];

}

}

highscores[i]= max;

}

}

//find average score.

void findavg(Student[] a, int c)

{

int i=0;

for(i=0;i<5; i++)

{

int sum =0;

for(int j=0; j<c; j++)

{

int[] s= a[j].getScores();

sum= sum + s[i];

}

avgscores[i]= sum/c;

}

}

  

//print statistics for all students and all quizes

public void printStatistics(Student[] a, int c)

{

findlow(a,c);

findhigh(a,c);

findavg(a,c);

System.out.println("Lowest score :\t\t"+ lowscores[0] +"\t"+ lowscores[1] +"\t"+ lowscores[2] +"\t"+ lowscores[3] +"\t"+ lowscores[4] );

System.out.println("High score :\t\t"+ highscores[0] +"\t"+ highscores[1] +"\t"+ highscores[2] +"\t"+ highscores[3] +"\t"+ highscores[4] );

System.out.println("Average score :\t\t"+ avgscores[0] +"\t"+ avgscores[1] +"\t"+ avgscores[2] +"\t"+ avgscores[3] +"\t"+ avgscores[4] );

}

}

___________________________________________________________________________________________________________

public class Student

{

private int SID;

private int scores[] = new int[5];

  

//get and set functions for scores and ID

public int getSID()

{

return this.SID;

}

public void setSID(int id)

{

this.SID= id;

}

public int[] getScores()

{

return this.scores;

}

public void setScores(int[] s)

{

this.scores= s;

}

  

//print all data of a student

public void printData()

{

System.out.println("\t\t\t\t"+ SID +"\t"+ scores[0] +"\t"+ scores[1] +"\t"+ scores[2] + "\t"+ scores[3] +"\t"+ scores[4] +"\n");

}

}

________________________________________________________________________________________________________

Data.txt

Stud Qu1 Qu2 Qu3 Qu4 Qu5

1234 052 007 100 078 034

2134 090 036 090 077 030

3124 100 045 020 090 070

4532 011 017 081 032 077

5678 020 012 045 078 034

6134 034 080 055 078 045

7874 060 100 056 078 078

8026 070 010 066 078 056

9893 034 009 077 078 020

1947 045 040 088 078 055

2877 055 050 099 078 080

3189 022 070 100 078 077

4602 089 050 091 078 060

5405 011 011 000 078 010

6999 000 098 089 078 020

0 0
Add a comment Improve this question Transcribed image text
Answer #1

I've gone through the code you've entered here.

The code is completely correct logic wise, the error you're getting is when the data is read from the file very first time.

You're getting the marks of the student using following lines:

  1. stu[i].setSID(Integer.parseInt(st.nextToken()));
  2. arr[j] = Integer.parseInt(st.nextToken());

Here, st.nextToken() returns String and so that string is parsed in the int. But, to be able to get parsed in the integer, the string should contain only numeric value. For example, string "100" can be parsed but the string "Hello" can not be parsed in 'int'.

So, when this code is running for the first time, it will go to the statement

stu[i].setSID(Integer.parseInt(st.nextToken()));

Here, nextToekn() will return "Stud" which will be passed as parseInt("Stud") which is invalid as "Stud" is not a number.

That is why you're given the error saying NumberFormatException while parsing is done.

To solve this error, I added few lines of the code in Util class where this input is taken from the file.

The modified code is as follows..

Modified code for Util.java

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

public class Util {

static int studentCount;

static Student[] readFile(String filename, Student[] stu) {

int i = 0;

try {

FileReader file = new FileReader(filename);
BufferedReader buff = new BufferedReader(file);
boolean eof = false;
boolean firstLineSkipped = false;

while (!eof) {

String line = buff.readLine();
if (line == null) {
eof = true;
} else {
if (!firstLineSkipped) {
firstLineSkipped = true;
continue;
}

stu[i] = new Student();
StringTokenizer st = new StringTokenizer(line);
  
while (st.hasMoreTokens()) {
stu[i].setSID(Integer.parseInt(st.nextToken()));
int[] arr = new int[5];

for (int j = 0; j < 5; j++) {
arr[j] = Integer.parseInt(st.nextToken());
}

stu[i].setScores(arr);
}
}
  
i++;
}

buff.close();
} catch (IOException e) {
System.out.println("Error -- " + e.toString());
}

studentCount = i-1;

return stu;
}
}

So, to skip the first line, I added a boolean variable that will allow that if() condition to run only once.

The boolean variable 'firstLineSkipped' is initialized as 'false'.

Now, inside the while() loop, first it is checked whether the line is null or not, if not then it comes to the 'else' part in which the data is saved in array.

So, before this saving is performed, I am checking whether this is the first line i.e. whether I've set 'firstLineSkipped' true or not using the line: if(!firstLineSkipped)

If this is first run of the code, obviously I've not changed value of that variable yet so I'm setting its value = true to indicate I've skipped first line. And to skip further execution of loop body for this run, I've used 'continue'.

This means on the first run of the loop, 'firstLineSkipped' is set as true so on every subsequent loop iterations, this will become false so no any iteration will try to execute that if() and so no further execution will be skipped.

Here, while skipping the line, I've not incremented 'i' as 'i' represent number of students and as you're creating an array based on 'i', if it was incremented here, this means 'i' will be having value 1 when it will be storing first row, in particular

1234 52 7 100 78 34

data from the text file. So its first element would remain null and it will give nullPointerException if I'm incrementing 'i' here. So, I've not done that.

Initially 'i' is 0 so first score values will be stored in arr[0] and then i++ will be done which is perfect.

At the end, as values are inserted first and then 'i' is incremented, here there's 15 lines so i=14 will store the last line values. But after that again i++ would be done but while loop won't get executed as it will be eof. So, students data should be till 14 only not 15 that's why i-1 written after while loop is still valid if we're skipping the first line.

So I've not changed there (otherwise it would also be giving the same error of nullPointerException.)

The modification done on the code is written in BOLD font style to identify them easily.

When I modified this and executed the code, I got the output as follows..

run: 34 30 70 100 78 1234 52 2134 90 3124 100 4532 11 5678 20 6134 34 7874 60 8026 70 9893 34 1947 45 2877 55 3189 22 460289

I've modified three existing lines in the method printStatistics() to get the output formatted as above. Those modified lines are..

System.out.println("\t\t\tLowest score :\t" + lowscores[0] + "\t" + lowscores[1] + "\t" + lowscores[2] + "\t" + lowscores[3] + "\t" + lowscores[4]);

System.out.println("\t\t\tHigh score :\t" + highscores[0] + "\t" + highscores[1] + "\t" + highscores[2] + "\t" + highscores[3] + "\t" + highscores[4]);

System.out.println("\t\t\tAverage score :\t" + avgscores[0] + "\t" + avgscores[1] + "\t" + avgscores[2] + "\t" + avgscores[3] + "\t" + avgscores[4]);

So, I've changed few '\t' in order to get the result displayed as above.

Now as you can see the output, it is giving the proper result.

So this is how you can solve this error and achieve this thing.

Go through the modifications, its output and description for the same.

Do comment if there is any query. I will address it for sure.

Thank you. :)

Add a comment
Know the answer?
Add Answer to:
Java programming help My program wont run. could someone tell me why. everything seems correct to...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • This is a java homework for my java class. Write a program to perform statistical analysis...

    This is a java homework for my java class. Write a program to perform statistical analysis of scores for a class of students.The class may have up to 40 students.There are five quizzes during the term. Each student is identified by a four-digit student ID number. The program is to print the student scores and calculate and print the statistics for each quiz. The output is in the same order as the input; no sorting is needed. The input is...

  • please edit my java code perferably on jgrasp version 50.0 , wont complie correctly :( the...

    please edit my java code perferably on jgrasp version 50.0 , wont complie correctly :( the program is supposed to read from my input file and do the following        1) print out the original data in the file without doing anything to it.        2) an ordered list of all students names (last names) alphabetically and the average GPA of all student togther . 3) freshman list in alphabeticalorder by last name with the average GPA of the freshmen...

  • Complete the following Java class. In this class, inside the main() method, user first enters the...

    Complete the following Java class. In this class, inside the main() method, user first enters the name of the students in a while loop. Then, in an enhanced for loop, and by using the method getScores(), user enters the grades of each student. Finally, the list of the students and their final scores will be printed out using a for loop. Using the comments provided, complete the code in methods finalScore(), minimum(), and sum(). import java.util.Scanner; import java.util.ArrayList; public class...

  • Hi All, Can someone please help me correct the selection sort method in my program. the...

    Hi All, Can someone please help me correct the selection sort method in my program. the output for the first and last sorted integers are wrong compared with the bubble and merge sort. and for the radix i have no idea. See program below import java.io.*; import java.util.ArrayList; import java.util.Scanner; public class Sort { static ArrayList<Integer> Data1 = new ArrayList<Integer>(); static ArrayList<Integer> Data2 = new ArrayList<Integer>(); static ArrayList<Integer> Data3 = new ArrayList<Integer>(); static ArrayList<Integer> Data4 = new ArrayList<Integer>(); static int...

  • JAVA TIC TAC TOE - please help me correct my code Write a program that will...

    JAVA TIC TAC TOE - please help me correct my code Write a program that will allow two players to play a game of TIC TAC TOE. When the program starts, it will display a tic tac toe board as below |    1       |   2        |   3 |    4       |   5        |   6                 |    7      |   8        |   9 The program will assign X to Player 1, and O to Player    The program will ask Player 1, to...

  • Can someone help me with my Java code error! Domain package challenge5race; import java.util.Random; public class...

    Can someone help me with my Java code error! Domain package challenge5race; import java.util.Random; public class Car {    private int year; private String model; private String make; int speed; public Car(int year, String model, String make, int speed) { this.year = year; this.model = model; this.make = make; this.speed = speed; } public Car() { } public int getYear() { return year; } public void setYear(int year) { this.year = year; } public String getModel() { return model; }...

  • I need help fixing my java code for some reason it will not let me run...

    I need help fixing my java code for some reason it will not let me run it can someone pls help me fix it. class LinearProbingHashTable1 { private int keyname; private int valuename; LinearProbingHashTable1(int keyname, int valuename) { this.keyname = keyname; this.valuename = valuename; } public int getKey() { return keyname; } public int getValue() { return valuename; } } class LinearProbingHashTable2 { private final static int SIZE = 128; LinearProbingHashTable2[] table; LinearProbingHashTable2() { table = new LinearProbingHashTable2[SIZE]; for (int...

  • Here is everything I have on my codes, the compiler does not allow me to input...

    Here is everything I have on my codes, the compiler does not allow me to input my name, it will print out "Please enter your name: " but totally ignores it and does not allow me to input my name and just proceeds to my result of ID and Sale. Please help. I've bolded the part where it I should be able to input my name package salesperson; public class Salesperson { String Names; int ID; double Sales; // craeting...

  • Hello this is my java sorting algorithm program i need all of my errors corrected so...

    Hello this is my java sorting algorithm program i need all of my errors corrected so I can run it. thank you!! import java.util.Scanner;    public class SortingAlogs { public static void main(String[]args){ int array [] = {9,11,15,34,1}; Scanner KB = new Scanner(System.in); int ch; while (true) { System.out.println("1 Bubble sort\n2 Insertion sort\n3 Selection sort\n"); ch = KB.nextInt(); if (ch==1)    bubbleSort(array); if (ch==2)    insertion(array); if (ch==3)    Selection(array); if (ch==4) break;    print(array);    System.out.println(); }    }...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT