Reading Data from a txt File in Java - java

I am trying to read data from a text file in Java. I want to read student names from the text file and put them into a String array which is called as "student". Also i want to read student grades. When i execute the program the output be like this:
click to see the output
Please help me. How can i read student names and grades from the text file without using Buffer or Stream or etc.?
File file = new File("StudentScores.txt");
Scanner input = new Scanner(file);
int i = 0;
while(input.hasNext()){
input.nextLine();
i++;
}
String[] student = new String[i];
while(input.hasNext()){
String name = input.next();
double grade = input.nextDouble();
System.out.println(name + " " + grade );
}
for(String a : student){
System.out.println(a);
}
StudentScores.txt Content:
John 60 70 80 90 65 75 70 89.5 75.4
Can 60 70 80 90 80 75 70 89.5 75.4
Cannot 60 -70 80 90 80 75 -70 89.5 75.4

Scanner moves only forward. First scanner part read whole file and second while(input.hasNext()) subpart will be not called. Take a look below script.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("StudentScores.txt");
List<Student> students = new ArrayList<>();
Scanner input = new Scanner(file);
while (input.hasNext()) {
String line = input.nextLine();
if (line.isEmpty()) {
break;
}
// split with spaces
String[] str = line.split(" ");
// first item is name
Student student = new Student(str[0]);
// visit rest items are grade values
for (int i = 1; i < str.length; i++) {
student.addGrade(Double.parseDouble(str[i]));
}
// add into the list
students.add(student);
}
for (Student student : students) {
System.out.println(student);
}
}
private static class Student {
private String name;
private List<Double> grades = new ArrayList<>();
public Student(String name) {
this.name = name;
}
public void addGrade(double grade) {
grades.add(grade);
}
public List<Double> getGrades() {
return grades;
}
#Override
public String toString() {
return name + ", grades=" + grades;
}
}
}
Output:
John, grades=[60.0, 70.0, 80.0, 90.0, 65.0, 75.0, 70.0, 89.5, 75.4]
Can, grades=[60.0, 70.0, 80.0, 90.0, 80.0, 75.0, 70.0, 89.5, 75.4]
Cannot, grades=[60.0, -70.0, 80.0, 90.0, 80.0, 75.0, -70.0, 89.5, 75.4]

Related

problem with removing student from array creates error

This program is created to store all student details and course details. The problem happens when trying to remove a student from this array it creates a error but only happens if you add a student to the array in option 2 in the program. You are able to remove a student when you haven't added a student it's only when you add a student that the error happens.
Main:
package javacoursework;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
*
* #author zhunt
*/
public class JavaCoursework {
static student[] students;
static courses[] course;
public static void main( String[] args )
throws FileNotFoundException {
//creating File instance to reference text file in Java
File text = new File("students.txt");
Scanner scanner = new Scanner(text);
while(scanner.hasNextLine()){
String line = scanner.nextLine();
String[] split = line.split(",");
student.FName.add(split[0]);
student.SName.add(split[1]);
student.DOB.add(split[2]);
student.Address.add(split[3]);
student.Gender.add(split[4]);
}
File course = new File("course.txt");
Scanner scan = new Scanner(course);
while(scan.hasNextLine()){
String info = scan.nextLine();
String[] split2 = info.split(",");
courses.CName.add(split2[0]);
courses.Lecturer.add(split2[1]);
courses.Enrolled.add(split2[2]);
}
Scanner kb = new Scanner( System.in );
int x;
//students = new Student[0];
students = new student[2];
do
{
System.out.println();
System.out.println( "Do you want to:" );
System.out.println( "\t0) View Students" );
System.out.println( "\t1) View Students' Details" );
System.out.println( "\t2) Add a Student" );
System.out.println( "\t3) Remove a Student" );
System.out.println( "\t4) View Courses Details" );
System.out.println( "\t5) Exit Progarm" );
x = Integer.parseInt(kb.nextLine());
switch (x)
{
case 0:
student.ViewStudents();
break;
case 1:
student.ViewDetails();
break;
case 2:
student.addStudent();
break;
case 3:
student.removeStudent();
break;
case 4:
courses.Report();
break;
default:
}
}
while( x != 5);
}
}
Student:
package javacoursework;
import java.util.Scanner;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author zhunt
*/
public class student {
// Make 'static' so as to maintain the same
// collection throughout all instances of Student.
public static java.util.List<String> FName = new java.util.ArrayList<>();
public static java.util.List<String> SName = new java.util.ArrayList<>();
public static java.util.List<String> DOB = new java.util.ArrayList<>();
public static java.util.List<String> Address = new java.util.ArrayList<>();
public static java.util.List<String> Gender = new java.util.ArrayList<>();
public static void addStudent(){
if(FName.size()>19){
System.out.print("The maximum amount of 20 students are currently being stored in the system. If you wish to add a new student you need to remove an existing student from the program");
}
else{
Scanner kb = new Scanner( System.in );
String Fname;
String Sname;
String Dob;
String address;
String gender;
System.out.println( "\tInput Information" );
System.out.println( "\tFirst Name: ");
Fname = kb.nextLine();
System.out.println( "\tSurname: ");
Sname = kb.nextLine();
System.out.println( "\tDate of Birth(dd-mm-yyyy): ");
Dob = kb.nextLine();
System.out.println( "\tAddress: ");
address = kb.nextLine();
System.out.println( "\tGender(Male/Female): ");
gender = kb.nextLine();
if(Fname!=""&&Sname!=""&&Dob!=""&&address!=""&&gender!="")
{
if(gender.equalsIgnoreCase("Female")||gender.equalsIgnoreCase("Male")){
FName.add(Fname);
SName.add(Sname);
DOB.add(Dob);
Address.add(address);
Gender.add(gender);
System.out.print(Fname+" "+Sname+" has been added to the system");
}
else{
System.out.print("Gender must be entered as male/female. Please try again");
}
}
else{
System.out.print("You may not leave out any of the required information. Please try again");
}
}
}
public static void ViewDetails()
{
Scanner kb = new Scanner( System.in );
String i;
System.out.println( "Enter the full name of the student you wish to view: ");
i = kb.nextLine();
String[] name = i.split(" ");
boolean found=false;
for(int x=0; x <FName.size();x++){
if(FName.get(x).equalsIgnoreCase(name[0]))
{
if(SName.get(x).equalsIgnoreCase(name[1]))
{
found=true;
System.out.print("Student found here are the students full details: ");
System.out.print(FName.get(x)+", "+SName.get(x)+", "+DOB.get(x)+", "+Address.get(x)+", "+Gender.get(x));
}
}
}
if(found==false)
{
System.out.print("Student entered cannot be found.");
}
}
public static void removeStudent(){
Scanner kb = new Scanner( System.in );
String i;
System.out.println( "Enter the full name of the student you wish to remove: ");
i = kb.nextLine();
String[] name = i.split(" ");
boolean found=false;
for(int x=0; x <FName.size();x++){
if(FName.get(x).equalsIgnoreCase(name[0]))
{
if(SName.get(x).equalsIgnoreCase(name[1]))
{
found=true;
FName.remove(x);
SName.remove(x);
DOB.remove(x);
Address.remove(x);
Gender.remove(x);
System.out.print(FName.get(x)+" "+SName.get(x)+" has been removed from the course");
}
}
}
if(found==false)
{
System.out.print("Student entered cannot be found. Please try again");
}
}
public static void ViewStudents(){
for( int i = 0; i < FName.size(); i++)
{
System.out.println(SName.get(i)+", "+FName.get(i));
}
}
}
Course:
package javacoursework;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author zhunt
*/
import java.util.Collections;
public class courses {
// Make 'static' so as to maintain the same
// collection throughout all instances of Courses.
public static java.util.List<String> CName = new java.util.ArrayList<>();
public static java.util.List<String> Lecturer = new java.util.ArrayList<>();
public static java.util.List<String> Enrolled = new java.util.ArrayList<>();
public static void Report(){
int enrolled=student.FName.size();
double male=Collections.frequency(student.Gender, "Male");
male=male+Collections.frequency(student.Gender, "male");
male=(male / enrolled)*100;
double female=100-male;
System.out.print("Course: "+CName.get(0)+"\nLecturer: "+Lecturer.get(0)+"\nStudents Enrolled: "+enrolled+"\nPercentage Male: "+String.format("%.2f", male)+"%"+"\nPercentage Female: "+String.format("%.2f", female)+"%");
}
}
Error:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 19, Size: 19
at java.util.ArrayList.rangeCheck(ArrayList.java:659)
at java.util.ArrayList.get(ArrayList.java:435)
at javacoursework.student.removeStudent(student.java:124)
at javacoursework.JavaCoursework.main(JavaCoursework.java:84)
C:\Users\xxray\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
In code of Student#removeStudent, when the student was found, you're deleting it and then trying to access deleted student by its index.
Consider next case:
Students list has 20 elements (last student Bob has an index of x = 19)
We're deleting Bob from the list by calling FName.remove(x)
Students list now contains only 19 elements
We're trying to access the 20th element of the list by calling System.out.print(FName.get(x)+" "+SName.get(x)+" has been removed from the course"). And because the list has only 19 elements, we're getting IndexOutOfBoundsException. To fix this issue, save removed items into local variables and print them afterwards.
After this two improvement the code will be look like some think like that:
fname = FName.remove(x);
sname = SName.remove(x);
DOB.remove(x);
Address.remove(x);
Gender.remove(x);
System.out.print(fname + " " + sname + " has been removed from the course");

why java method return same result?

i have problem with my program << this program take information for 3 student name and id and marks in 5 course then return information with marks avrage my program is work good but it return same avrage for all student its same number please can u help me
this is the class
StudentsMarks.java
package programmersx;
import java.io.BufferedWriter;
import java.io.*;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
public class StudentsMarks {
private String studentName;
private int studentId;
private double marks[];
public static int NoInstntitd;
public StudentsMarks() {
NoInstntitd += 1;
}
double avgCalculator(double[] marks) { //avg method
double sum =0;
double avg=0;
for (int i = 0; i < marks.length; i++) {
sum = sum + marks[i];
avg=sum/5;
}
return avg;
}
#Override
public String toString() {
return studentName +" " + studentId +" " + Arrays.toString(marks) +" " ;
}
void toFile(String fileName) throws IOException {
FileOutputStream file= new FileOutputStream(fileName);
PrintWriter writer= new PrintWriter(file);
writer.print("reem ");
String information = "student information :" + getStudentName() + "" + getStudentId() + " average " + avgCalculator(marks);
LocalDate localDate = LocalDate.now();
BufferedWriter writer1 = new BufferedWriter(new FileWriter("average.txt"));
BufferedWriter writer2 = new BufferedWriter(new FileWriter("localDate.txt"));
try {
writer.write(information);
writer1.write(" average " + avgCalculator(marks));
writer2.write(DateTimeFormatter.ofPattern("yyy/MM/dd").format(localDate));
writer2.close();
} catch (IOException ex) {
Logger.getLogger(Programmersx.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("student information :" + getStudentName() + "" + getStudentId() + " average " + avgCalculator(marks));
System.out.println(" student average. : " + avgCalculator(marks));
System.out.println(DateTimeFormatter.ofPattern("yyy/MM/dd").format(localDate));
}
{
NoInstntitd += 1;
}
void display( ) {
System.out.println("display the count of the instantiated objects from StudentMarks" + getNoInstntitd());
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public double[] getMarks() {
return marks;
}
public void setMarks(double[] marks) {
this.marks = marks;
}
public int getNoInstntitd() {
return NoInstntitd;
}
public void setNoInstntitd(int NoInstntitd) {
this.NoInstntitd = this.NoInstntitd + 1;
}
}
this is main
Programmersx.java
package programmersx;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Programmersx {
public static void main(String[] args) throws IOException {
StudentsMarks myObject = new StudentsMarks();
StudentsMarks myObject1 = new StudentsMarks();
StudentsMarks myObject2 = new StudentsMarks();
System.out.print("Please enter your student Name : ");
Scanner myObj = new Scanner(System.in); // Create a Scanner object
myObject.setStudentName(myObj.next()) ;
System.out.print("Please enter your student Id : ");
myObject.setStudentId(myObj.nextInt()) ;
System.out.println("Please enter your marks of 5 courses : ");
double marks[] = new double [5];
for (int i = 0; i < 5; i++) {
marks[i]= myObj.nextInt();
}
myObject.setMarks(marks) ;
System.out.print("Please enter your student Name : ");
Scanner myObj1 = new Scanner(System.in); // Create a Scanner object
myObject1.setStudentName(myObj1.next()) ;
System.out.print("Please enter your student Id : ");
myObject1.setStudentId(myObj1.nextInt()) ;
System.out.println("Please enter your marks of 5 courses : ");
double marks1[] = new double [5];
for (int i = 0; i < 5; i++) {
marks1[i]= myObj1.nextInt();
}
myObject1.setMarks(marks) ;
myObject1.toString();
System.out.print("Please enter your student Name : ");
Scanner myObj2 = new Scanner(System.in); // Create a Scanner object
myObject2.setStudentName(myObj2.next()) ;
System.out.print("Please enter your student Id : ");
myObject2.setStudentId(myObj2.nextInt()) ;
System.out.println("Please enter your marks of 5 courses : ");
double marks2[] = new double [5];
for (int i = 0; i < 5; i++) {
marks2[i]= myObj2.nextInt();
}
myObject2.setMarks(marks) ;
myObject2.toString();
myObject.toString();
myObject.toFile("Reem.txt");
myObject1.toFile("MAria.txt");
myObject2.toFile("Abrar.txt");
System.out.println("display the count of the instantiated objects from StudentMarks: " + StudentsMarks.NoInstntitd );
}
}
the output is
run:
Please enter your student Name : jack
Please enter your student Id : 1123
Please enter your marks of 5 courses :
6
4
5
7
6
Please enter your student Name : mick
Please enter your student Id : 87534
Please enter your marks of 5 courses :
6
4
3
22
5
Please enter your student Name : meno
Please enter your student Id : 43433
Please enter your marks of 5 courses :
6
55
33
22
7
student information :jack1123 average 5.6
student average. : 5.6
2019/12/06
student information :mick87534 average 5.6
student average. : 5.6
2019/12/06
student information :meno43433 average 5.6
student average. : 5.6
2019/12/06
display the count of the instantiated objects from StudentMarks: 6
All of the StudentMarks objects have their marks set by a similar call:
myObject2.setMarks(marks)
They all use the same marks array, so they all have the same marks.
Even if you change the content of the marks array between
myObject.setMarks(marks)
and
myObject1.setMarks(marks)
there's still only one marks array, shared by all StudentMarks objects: the StudentMarks setter does not copy the array.
All student are setted the same marks
myObject.setMarks(marks)
myObject1.setMarks(marks)
myObject2.setMarks(marks)
You should change your code like this
myObject.setMarks(marks)
myObject1.setMarks(marks1)
myObject2.setMarks(marks2)

Basic Java programming with Multiple ArrayLists

In the following code, I have taken in a list of 5 student names, and loading them in an ArrayList of type String.
import java.util.Scanner;
import java.util.ArrayList;
public class QuizAverage
{
public static void main( String[] args ) {
final int NAMELIMIT = 5 ;
final int QUIZLIMIT = 5 ;
ArrayList<String> sNames = new ArrayList<String>();
ArrayList<String> sFamily = new ArrayList<String>();
Scanner in = new Scanner(System.in);
//Load the 5 names of the students in the arraylist
for(int i = 1; i<=NAMELIMIT; i++)
{
String[] input = in.nextLine().split("\\s+");
sNames.add(input[0]);
sFamily.add(input[1]);
}
System.out.println("Name: ");
System.out.println();
for(int i=0; i<NAMELIMIT; i++)
{
System.out.println("Name: " +sNames.get(i) + " " + sFamily.get(i));
}
System.out.println();
}
}
However, now I am trying to add to the code a part that reads in marks for 5 quizes for each student and loads the quiz marks in An ArrayList of type Integer
So I know I need to use
ArrayList<Integer> quizMarks = readArrayList(readQuiz.nextLine());
and then pass it on to this code which takes the quiz marks and weights them out of 15 instead of 100
public static ArrayList<Integer> readArrayList(String input)
{
ArrayList<Integer> quiz = new ArrayList<Integer>();
int i = 1;
while (i <= QUIZLIMIT)
{
if (readQuiz.hasNextInt()) {
quiz.add(readQuiz.nextInt());
i++;
} else {
readQuiz.next(); // toss the next read token
}
}
return quiz;
}
//Computer the average of quiz marks
public static void computerAverage(ArrayList<Integer>quiz)
{
double total = 0 ;
for(Integer value : quiz)
{
total = total + value;
}
total *= MAX_SCORE/100;
System.out.println("Quiz Avg: "+ total / QUIZLIMIT );
}
}
So my current code with the input:
Sally Mae 90 80 45 60 75
Charlotte Tea 60 75 80 90 70
Oliver Cats 55 65 76 90 80
Milo Peet 90 95 85 75 80
Gavin Brown 45 65 75 55 80
Gives the output
Name: Sally Mae
Name: Charlotte Tea
Name: Oliver Cats
Name: Milo Peet
Name: Gavin Brown
when the desired output is
Name: Sally Mae Quiz Avg: 10.5
Name: Charlotte Tea Quiz Avg: 11.25
Name: Oliver Cats Quiz Avg: 10.95
Name: Milo Peet Quiz Avg: 12.75
Name: Gavin Brown Quiz Avg: 9.6
As Jim said, you should store the marks and the name of the student in the same class. The reason for doing that is say going forward you want to find the marks of a particular student named Raj.
In your implementation you would have to go through the first array for find the index of the person named Raj and then go to the same index in the marks array. If there was no problem in initializing the first array but there was some problem in creating the marks array you might end up with the wrong marks.
Also if you have to add a new attribute to a student you would have to create a new array and then add one more logic to read that data.
Having a class gives you an easy way to group all the data belonging to a student.
For your problem of averaging, I'd have a class as follows
class Student {
private String name;
private Double marks;
public Student(String name, String marks) {
this.name = name;
this.marks = marks;
}
//getters setters
}
Have a list of Student
List<Student> students = new ArrayList<Student>();
After reading you will append the object to this list
students.add(new Student(name, marks));
Computing average is as follows
Double average = 0;
for(Student student: students) {
average += student.getMarks();
}
average = average / student.size();
Checkout https://docs.oracle.com/javase/tutorial/collections/streams/reduction.html for other ways to get the average.
Don't use parallel arrays. Use a Student class instead:
public class Student {
private String name;
private String family;
private List<Integer> marks = new ArrayList<>();
public Student(String name, String family)
{
this.name = name;
this.family = family;
}
// getters, setters
...
public void addMark(int mark)
{
this.marks.add(mark);
}
public void getAverage()
{
... // etc
}
}
Then store instances of this class in a single list in your main program
List<Student> students = new ArrayList<>();
You haven't called computerAverage() yet from what I see.

Java - ArrayIndexOutOfBounds Error on parallel arrays

I'm having a bit of trouble with this project:
We're given a text file of 5 students, with 4 number grades following each name in a separate line. We have to use our main method to read the file, then perform calculations in the gradebook class. However, from what others in class have been saying the method we're using is archaic at best, involving Parallel arrays. We don't really seem to have any other option though, so I'm making due with what I can. But near what I'm hoping is the end of this code, I've encountered a problem, where it says the index that contains the grades for students is out of bounds.
I've rewritten the readFile method in my main in quite a few different ways, but no matter what I still get these errors. Could anyone help me understand what's going on? I'll post everything I can.
I also apologize if I'm a bit slow/incapable with this, this is my first time coding java in months unfortunately.
Also, in the error I post, line 64 of the main class is: grades[test] = inputFile.nextDouble();
run:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at Package1.GradeBookDemo.readFile(GradeBookDemo.java:64)
at Package1.GradeBookDemo.main(GradeBookDemo.java:29)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
The following is my Main method:
import java.util.Scanner;
import java.io.*;
public class GradeBookDemo {
public static void main(String[] args) throws IOException {
// Create a new gradebook object
Gradebook gradeBook = new Gradebook();
//Read StudentInfo file for names and test scores using readFile method
readFile(gradeBook);
//Output Student data
for (int index = 1; index <= 5; index++)
{
System.out.println("Name: " + gradeBook.getName(index) +
"\tAverage Score: " + gradeBook.getAverage(index) +
"\tGrade: " + gradeBook.getLetterGrade(index));
}
}
// This method reads from the StudentInfo file
public static void readFile(Gradebook gradeBook) throws IOException
{
int nI = 0; // Name index
int gI = 4; // Grade index
// Create a string array to hold student names and another for grades
double[] grades = new double[gI];
// Access the StudentInfo text file
File sFile = new File("StudentInfo.txt");
// Create a scanner object to read the file
Scanner inputFile = new Scanner(sFile);
// Read StudentInfo
for(int student = 1; student <= 5; student++)
{
String name = inputFile.nextLine();
gradeBook.setName(student, name);
for (int test = 0; test < 4; test++)
{
grades[test] = inputFile.nextDouble();
}
}
// Close the file
inputFile.close();
}
}
And then the Gradebook class
public class Gradebook {
// Declare fields
private final int NUM_STUDENTS = 5;
private final int NUM_TESTS = 4;
// ArrayList for names of students - 5 in total
private String[] names = new String[NUM_STUDENTS];
// Array to store letter grades
private char[] grades;
// array to store each student's scores
private double[] scores1 = new double[NUM_TESTS];
private double[] scores2 = new double[NUM_TESTS];
private double[] scores3 = new double[NUM_TESTS];
private double[] scores4 = new double[NUM_TESTS];
private double[] scores5 = new double[NUM_TESTS];
// Method to set student's name
public void setName(int studentNumber, String name)
{
names[studentNumber-1] = name;
}
// Method sets student scores
public void setScores(int studentNumber, double[] scores)
{
switch(studentNumber)
{
case 1:copyArray(scores1,scores); break;
case 2:copyArray(scores2,scores); break;
case 3:copyArray(scores3,scores); break;
case 4:copyArray(scores4,scores); break;
case 5:copyArray(scores5,scores); break;
default:break;
}
}
// Returns the student's name
public String getName(int studentNumber)
{
return names[studentNumber-1];
}
// Returns student's average score
public double getAverage(int studentNumber)
{
double avg=0.0;
switch(studentNumber)
{
case 1:avg = calcAverage(scores1); break;
case 2:avg = calcAverage(scores2); break;
case 3:avg = calcAverage(scores3); break;
case 4:avg = calcAverage(scores4); break;
case 5:avg = calcAverage(scores5); break;
default:break;
}
return avg;
}
// Returns the student's letter grade
public char getLetterGrade(int studentNumber)
{
char lettergrade;
if(getAverage(studentNumber)>=90 && getAverage(studentNumber)<=100)
lettergrade = 'A';
else if(getAverage(studentNumber)>=80 && getAverage(studentNumber)<=89)
lettergrade = 'B';
else if(getAverage(studentNumber)>=70 && getAverage(studentNumber)<=79)
lettergrade = 'C';
else if(getAverage(studentNumber)>=60 && getAverage(studentNumber)<=69)
lettergrade = 'D';
else
lettergrade = 'F';
return lettergrade;
}
// Calculates the student's average
private double calcAverage(double[] scores)
{
double sum=0;
for(int i=0; i<scores.length; i++)
sum+=scores[i];
return sum/scores.length;
}
// Determines student's letter grade based on average score
public char LetterGrade(double average)
{
char lettergrade;
if(average>=90 && average<=100)
lettergrade = 'A';
else if(average>=80 && average<=89)
lettergrade = 'B';
else if(average>=70 && average<=79)
lettergrade = 'C';
else if(average>=60 && average<=69)
lettergrade = 'D';
else
lettergrade = 'F';
return lettergrade;
}
// Array copy method
private void copyArray(double[] to, double[] from)
{
System.arraycopy(from, 0, to, 0, from.length);
}
}
Here is the file the program is reading - StudentInfo.txt:
Joanne Smith
98
89
100
76
Will Jones
67
89
91
88
Kerry McDonald
78
79
88
91
Sam Young
88
98
76
56
Jill Barnes
94
93
91
98
You will get InputMismatchException
Reason
String name = inputFile.nextLine(); //Reads the current line, Scanner moves to next line
grades[test] = inputFile.nextDouble(); //Reads the next double value
You should be able to read first student name and grades without any issues. After reading 76, the scanner position is at the end of line 5. It didn't skip line 5.
So, when you try to read next student name by calling nextLine(). you will see "". and scanner moves to line 6.
So the next call to nextDouble() fails.
Quick fix
use Double.parseDouble(inputFile.nextLine()); for reading the double values here
This is a rather interesting "This can not happen" scenario.
From the comments I would guess that the code actually compiled has an error in the inner for-loop. You need to find which file you are actually compiling.
Try adding random
System.out.println("Got HERE!");
to your code and see if any of them are actually printed.
Because the code you show should not be able to give that exception.

End of File Error in File Handling Program

I am creating a database project in java using file handling. The program is working without compiling error. Following points are not working
File is storing only first record. (if program is running again it is overwriting file)
I want to display all records but the only first record is displaying with Exeception
Please offer suggestions..
import java.io.*;
public class Student implements Serializable
{
private int roll;
private String name; //To store name of Student
private int[] marks = new int[5]; //To store marks in 5 Subjects
private double percentage; //To store percentage
private char grade; //To store grade
public Student()
{
roll = 0;
name = "";
for(int i = 0 ; i < 5 ; i++)
marks[i] = 0;
percentage = 0;
grade = ' ';
}
public Student(int roll , String name ,int[] marks)
{
setData(roll,name,marks);
}
public void setData(int roll , String name ,int[] marks)
{
this.roll = roll;
this.name = name;
for(int i = 0 ; i < 5 ; i++)
this.marks[i] = marks[i];
cal();
}
//Function to calculate Percentage and Grade
private void cal()
{
int sum = 0;
for(int i = 0 ; i < 5 ;i++)
sum = sum + marks[i];
percentage = sum/5;
if(percentage>85)
grade = 'A';
else if(percentage > 70)
grade = 'B';
else if (percentage >55)
grade = 'C';
else if (percentage > 33)
grade = 'E';
else
grade = 'F';
}
public char getGrade() { return grade; }
public double getPercentage() { return percentage; }
#Override
public String toString()
{
string format = "Roll Number : %4d, Name : -%15s "
+ "Percentage : %4.1f Grade : %3s";
return String.format(format, roll, name, percentage, grade);
}
}
second file
import java.io.*;
public class FileOperation
{
public static void writeRecord(ObjectOutputStream outFile, Student temp)
throws IOException, ClassNotFoundException
{
outFile.writeObject(temp);
outFile.flush();
}
public static void showAllRecords(ObjectInputStream inFile)
throws IOException, ClassNotFoundException
{
Student temp = new Student();
while(inFile.readObject() != null)
{
temp = (Student)inFile.readObject();
System.out.println(temp);
}
}
}
main file
(only two options are working)
import java.util.*;
import java.io.*;
public class Project
{
static public void main(String[] args)
throws IOException,ClassNotFoundException
{
ObjectInputStream inFile;
ObjectOutputStream outFile;
outFile = new ObjectOutputStream(new FileOutputStream("info.dat"));
inFile = new ObjectInputStream(new FileInputStream("info.dat"));
Scanner var = new Scanner(System.in) ;
int roll;
String name;
int[] marks = new int[5];
int chc = 0;
Student s = new Student();
while(chc != 6)
{
System.out.print("\t\tMENU\n\n");
System.out.print("1.Add New Record\n");
System.out.print("2.View All Records\n");
System.out.print("3.Search a Record (via Roll Number) \n");
System.out.print("4.Delete a Record (via Roll Number) \n");
System.out.print("5.Search a Record (via Record Number)\n");
System.out.print("6.Exit\n");
System.out.print("Enter your choice : ");
chc = var.nextInt();
switch(chc)
{
case 1:
System.out.print("\nEnter Roll number of Student : ");
roll = var.nextInt();
System.out.print("\nEnter Name of Student : ");
name = var.next();
System.out.println("\nEnter marks in 5 subjects \n");
for(int i = 0 ; i < 5 ; i++)
{
System.out.print("Enter marks in subject " + (i+1) + " ");
marks[i] = var.nextInt();
}
s.setData(roll , name , marks );
System.out.println("\n Adding Record to file \n");
System.out.printf("Record \n " + s);
System.out.println("\n\n");
FileOperation.writeRecord(outFile,s);
System.out.println("Record Added to File\n ");
break;
case 2:
System.out.println("All records in File \n");
FileOperation.showAllRecords(inFile);
break;
default: System.out.println("Wrong choice ");
}
}
outFile.close();
inFile.close();
}
}
Your program found a ClassNotFoundException and your method only throws an IOException.
I would check your import statements to make sure you are bringing in the class for ObjectInputStream
import java.io.ObjectInputStream;
If you want to get rid of unreported exception try:
Try
public static void showAllRecords(ObjectInputStream inFile) throws IOException, ClassNotFoundException

Categories

Resources