End of File Error in File Handling Program - java

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

Related

Cannot get program to print to command line or report file

I have a program here that compiles but I cannot get it to print to the command line or a report file. Any assistance is appreciated. Here is the error that I get:
Error: Main method not found in class Township, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
Press any key to continue . .
import java.util.*;
import java.io.*;
//Township class
class Township
{
//instance variables
String name;
int households;
int bicycles;
double average;
String tier;
double funding;
//constructor
public Township(String name, int households, int bicycles)
{
this.name = name;
this.households = households;
this.bicycles = bicycles;
}
//calculate average bikes per household
public void AverageBikes()
{
average = (double)bicycles/households;
}
//calculate the funding
public void Funding()
{
if(average>=3.0) funding = 50000.00;
else if(average>=2.0) funding = 40000.00;
else if(average>=1.0) funding = 30000.00;
else if(average>=0.5) funding = 20000.00;
else funding = 0.00;
}
//calculate the tier
public void Tier()
{
if(average>=3.0) tier = "One";
else if(average>=2.0) tier = "Two";
else if(average>=1.0) tier = "Three";
else if(average>=0.5) tier = "Four";
else tier = "Five";
}
//sort the townships in alphabetical order by township name
public static void sort(Township t[], int n)
{
for(int i=0; i<n-1; i++){
for(int j=i+1; j<n; j++){
if(t[i].name.compareTo(t[j].name) > 0){
Township tmp = t[i];
t[i] = t[j];
t[j] = tmp;
}
}
}
}
}
//Driver class
class Driver
{
//method to print the report
public static void printReport(Township t[], int n)
{
//sort the list
Township.sort(t, n);
System.out.println ("Township Number Bicycles Average Bikes Proposed Tier");
System.out.println ("Name Households reported Per household Funding Designation");
//print the report
for(int i=0; i<n; i++)
{
System.out.printf ("%-20s%-12d%-12d%-16.2f%-16.2f%s\n", t[i].name, t[i].households,
t[i].bicycles, t[i].average, t[i].funding, t[i].tier);
}
}
//method to get input from user
public static Township getInput(Scanner sc)
{
System.out.print ("Enter the name of Township: ");
String name = sc.nextLine();
System.out.print ("Enter the number households: ");
int household = sc.nextInt();
System.out.print ("Enter the bicycles reported: ");
int bicycles = sc.nextInt();
Township town = new Township(name, household, bicycles);
town.AverageBikes();
town.Funding();
town.Tier();
return town;
}
//method to get input from file
public static int readFile(Township town[]) throws IOException
{
//open the file
Scanner sc = new Scanner(new File("town.txt"));
int i=0;
while(sc.hasNext())
{
String name = sc.nextLine();
int household = sc.nextInt();
sc.nextLine();
int bicycles = sc.nextInt();
sc.nextLine();
town[i] = new Township(name, household, bicycles);
town[i].AverageBikes();
town[i].Funding();
town[i].Tier();
i++;
}
return i;
}
//method to write the report to the file
public static void writeFile(Township t[], int n) throws IOException
{
//sort the list
Township.sort(t, n);
FileWriter writer = new FileWriter("report.txt");
PrintWriter pout = new PrintWriter(writer);
pout.printf ("Township Number Bicycles Average Bikes Proposed Tier\n");
pout.printf ("Name Households reported Per household Funding Designation\n");
for(int i=0; i<n; i++)
{
pout.printf ("%-20s%-12d%-12d%-16.2f%-16.2f%s\n", t[i].name, t[i].households,
t[i].bicycles, t[i].average, t[i].funding, t[i].tier);
}
pout.close();
}
//main method
public static void main (String[] args) throws IOException
{
//create an instance of Scanner class
Scanner sc = new Scanner(System.in);
//create an array of Townships
Township town[] = new Township[10];
int i= readFile(town);
//processing
while(true)
{
//menu
System.out.println ("1. Input\n2. Report\n3. Exit");
//prompt to enter a choice
System.out.print("Enter choice: ");
int n = sc.nextInt();
switch(n)
{
case 1:
//get input from user
town[i] = getInput(sc);
i++;
break;
case 2:
//print the report
printReport(town, i);
break;
case 3:
//write to file
writeFile(town, i);
System.out.println ("Goodbye!");
return;
}
}
}
}
EDIT
I updated the error and some code thanks to the responses.
Here is the new error that I get:
Error: Exception in thread "main" java.util.InputMismatchException at
java.base/java.util.Scanner.throwFor(Scanner.java:939) at
java.base/java.util.Scanner.next(Scanner.java:1594) at
java.base/java.util.Scanner.nextInt(Scanner.java:2258) at
java.base/java.util.Scanner.nextInt(Scanner.java:2212) at
Township.readFile(Township.java:143) at
Township.main(Township.java:20)
Code:
import java.util.*;
import java.io.*;
//Township class
public class Township{
//instance variables
String name;
int households;
int bicycles;
double average;
String tier;
double funding;
public static void main (String[] args) throws IOException{
//create an instance of Scanner class
Scanner sc = new Scanner(System.in);
//create an array of Townships
Township town[] = new Township[10];
int i= readFile(town);
//processing
while(true)
{
//menu
System.out.println ("1. Input\n2. Report\n3. Exit");
//prompt to enter a choice
System.out.print("Enter choice: ");
int n = sc.nextInt();
switch(n)
{
case 1:
//get input from user
town[i] = getInput(sc);
i++;
break;
case 2:
//print the report
printReport(town, i);
break;
case 3:
//write to file
writeFile(town, i);
System.out.println ("Goodbye!");
return;
}
}
}
//==================================================================
//constructor
public Township(String name, int households, int bicycles)
{
this.name = name;
this.households = households;
this.bicycles = bicycles;
}
//calculate average bikes per household
public void AverageBikes()
{
average = (double)bicycles/households;
}
//calculate the funding
public void Funding()
{
if(average>=3.0) funding = 50000.00;
else if(average>=2.0) funding = 40000.00;
else if(average>=1.0) funding = 30000.00;
else if(average>=0.5) funding = 20000.00;
else funding = 0.00;
}
//calculate the tier
//==================================================================
public void Tier()
{
if(average>=3.0) tier = "One";
else if(average>=2.0) tier = "Two";
else if(average>=1.0) tier = "Three";
else if(average>=0.5) tier = "Four";
else tier = "Five";
}
//sort the townships in alphabetical order by township name
public static void sort(Township t[], int n)
{
for(int i=0; i<n-1; i++){
for(int j=i+1; j<n; j++){
if(t[i].name.compareTo(t[j].name) > 0){
Township tmp = t[i];
t[i] = t[j];
t[j] = tmp;
}
}
}
}
//==================================================================
//method to print the report
public static void printReport(Township t[], int n)
{
//sort the list
Township.sort(t, n);
System.out.println ("Township Number Bicycles Average Bikes Proposed Tier");
System.out.println ("Name Households reported Per household Funding Designation");
//print the report
for(int i=0; i<n; i++)
{
System.out.printf ("%-20s%-12d%-12d%-16.2f%-16.2f%s\n", t[i].name, t[i].households,
t[i].bicycles, t[i].average, t[i].funding, t[i].tier);
}
}
//==================================================================
//method to get input from user
public static Township getInput(Scanner sc)
{
System.out.print ("Enter the name of Township: ");
String name = sc.nextLine();
System.out.print ("Enter the number households: ");
int household = sc.nextInt();
System.out.print ("Enter the bicycles reported: ");
int bicycles = sc.nextInt();
Township town = new Township(name, household, bicycles);
town.AverageBikes();
town.Funding();
town.Tier();
return town;
}
//==================================================================
//method to get input from file
public static int readFile(Township town[]) throws IOException
{
//open the file
Scanner sc = new Scanner(new File("bicycledata.txt"));
int i=0;
while(sc.hasNext())
{
String name = sc.nextLine();
int households = sc.nextInt();
sc.nextLine();
int bicycles = sc.nextInt();
sc.nextLine();
town[i] = new Township(name, households, bicycles);
town[i].AverageBikes();
town[i].Funding();
town[i].Tier();
i++;
}
return i;
}
//==================================================================
//method to write the report to the file
public static void writeFile(Township t[], int n) throws IOException{
//sort the list
Township.sort(t, n);
FileWriter writer = new FileWriter("report.txt");
PrintWriter pout = new PrintWriter(writer);
pout.printf ("Township Number Bicycles Average Bikes Proposed Tier\n");
pout.printf ("Name Households reported Per household Funding Designation\n");
for(int i=0; i<n; i++)
{
pout.printf ("%-20s%-12d%-12d%-16.2f%-16.2f%s\n", t[i].name, t[i].households,
t[i].bicycles, t[i].average, t[i].funding, t[i].tier);
}
pout.close();
}//end method
}//end class
Try this:
class Township {
//instance variables
String name;
int households;
int bicycles;
double average;
String tier;
double funding;
//constructor
public Township(String name, int households, int bicycles) {
this.name = name;
this.households = households;
this.bicycles = bicycles;
}
// Rest of Township class code...
public static void main(String[] args) {
// Do things...
}
}
Take a look to this: Essentials
Every application needs one class with a main method. This class is
the entry point for the program, and is the class name passed to the
java interpreter command to run the application.
IOException is thrown to you for another reason. The answer to your question has been given.
I think you are compiling class Township which do not have main() method. You should compile Driver class because class Driver has main() method and creating the object of class Township.

Opening File Using BufferedWriter

I am a beginner to Java; I am trying to append text to a text file that was previously created using the File class and writing to the file using PrintWriter. When I call the first method in my main class the file is created and works. However, when I call the second method "try" is called, but no new text is added to the .txt file. I put the second method into a separate public class but I ran into the same issue. Do I need to initialize the fileName variable again?
Many thanks.
package project;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class WriteOut {
private int NumberOfMember;
private String ProjectName;
private String[] TeamMember;
public static String fileName;
private int[][] Vote;
public int FirstExport(int NumberOfMember, String ProjectName, String[] TeamMember) {
Scanner scan = new Scanner(System.in);
String fileName="ok"; //initializing the file name
System.out.println("Enter a file name to hold the Project:");
fileName = scan.nextLine( );
File fileObject = new File(fileName+".txt");
while (fileObject.exists( ))
{
System.out.println("There already is a file named "
+ fileName);
System.out.println("Enter a different file name:");
fileName = scan.nextLine( );
fileObject = new File(fileName+".txt");
}
PrintWriter outputStream = null;
try
{
outputStream =
new PrintWriter(new FileOutputStream(fileName+".txt"));
}
catch(FileNotFoundException e)
{
System.out.println("Error opening the file " + fileName +".txt");
System.exit(0);
}
for (int MemberCount = 1; MemberCount <= NumberOfMember; MemberCount ++) //For as long as the member count is less than the total number of members, the program will ask for the user input
{
//Statement of variable allocation to corresponding member position
outputStream.println("Team Member"+(MemberCount)+ ":"+TeamMember[MemberCount - 1]);
}
outputStream.println("Number of Members:"+ NumberOfMember+ "\nProject Name:"+ProjectName);
outputStream.close();
return NumberOfMember;
}
public int[][] SecondExport(int[][] Vote) {
System.out.println("hello"); //test to see if this is being called correctly
try
{
String content = "This is the content to write into file"; //Test content
BufferedWriter bw = new BufferedWriter(new FileWriter(fileName+".txt", true));
bw.append(content);
System.out.println("Done"); //Test to see if this is being called
bw.flush();
bw.close();
} catch (IOException e)
{
e.printStackTrace();
}
return Vote;
}
}
My main class calls the WriteOut class under the EnterVotes() method:
package project:
import java.util.Scanner; //Importing the scanner tool
import java.util.stream.IntStream; //for summing arrays
import java.io.FileNotFoundException;
import java.text.DecimalFormat; //Importing the decimal tool
public class Project
{
public static void main(String[] args)
{
Project run = new Project();
run.StartMenu();
}
public static String option; //Declaring the strings representing the menu option buttons
private static int NumberOfMember; //Entering the number of members
public static int index=NumberOfMember; //used for later, declaring a square matrix
public static String[] TeamMember; //Declaring the strings representing the names of the members
public static int[][] Vote;
public static String ProjectName; // Declaring the project name variable as a string
private static boolean CorrectInput, ShowMenu; //Booleans CorrectInput, which determines whether the user has entered a valid input and ShowMenu, which determines whether the main menu is displayed again
public String fileName;
static Scanner scan = new Scanner(System.in); // Importing the scanner tool
DecimalFormat twoDecPlcFormatter = new DecimalFormat("0.00"); //Although not used currently, having a decimal formatter could come in handy later
//----------------------------------------------
//Declaration of StartMenu(): listing Menu Options and equalsIgnoreCase to accept either upper or lower case
//----------------------------------------------
Project(){
}
public void StartMenu()
{
Scanner scan = new Scanner(System.in);
System.out.println();
System.out.print("\nWelcome to Splitit ");
do
{
printMenu();
char input = scan.next().charAt(0); //Asking user to input a character
option = Character.toString(input); //Converting from characters to string
checkInput(option);
}
while (CorrectInput == false || ShowMenu == true); //Run StartMenu() while either the CorrectInput is false or ShowMenu is true
}
//----------------------------------------------
//Declaration of checkInput(String OneInput) method
//----------------------------------------------
private void checkInput(String OneInput)
{
if (OneInput.equalsIgnoreCase("A") == true)
{
About();
}
else if (OneInput.equalsIgnoreCase("C") == true)
{
CreateProjectTitle();
}
else if (OneInput.equalsIgnoreCase("V") == true)
{
EnterVotes();
}
else if (OneInput.equalsIgnoreCase("S") == true)
{
ShowProject();
}
else if (OneInput.equalsIgnoreCase("Q") == true)
{
Quit();
}
else
{
System.out.print("\tIncorrect input. "); //If the user has entered an incorrect input, force them to enter in correct input
CorrectInput = false;
}
}
private void printMenu()
{
System.out.println("\n\n\tAbout\t\t(A)");
System.out.println("\tCreate Project\t(C)");
System.out.println("\tEnter Votes\t(V)");
System.out.println("\tShow Project\t(S)");
System.out.println("\tQuit\t\t(Q)");
System.out.print("\n\tPlease choose an option: ");
}
//----------------------------------------------
//Declaration of About() method
//----------------------------------------------
public void About()
{
System.out.println("\tThis is a program designed to assign grades for a project based on each member's \n \tparticipation. ");
}
//----------------------------------------------
//Declaration of ShowProject()
//----------------------------------------------
public void ShowProject()
{
CorrectInput = true;
ShowMenu = true;
StoreVariables getThings = new StoreVariables();
System.out.println("Number of members: " + getThings.getNumberofMember(NumberOfMember));
System.out.println("Project name: " + getThings.getProjectName(ProjectName));
String[] abc = getThings.getTeamMember();
for (int Counter = 1; Counter <= NumberOfMember; Counter ++) //Returning each team member's name and corresponding member number
{
System.out.println("Name of member " + Counter + " : " + getTeamMemberName(Counter));
}
for (int Counter = 1; Counter <= NumberOfMember; Counter ++) //Returning each team member's name and corresponding member number
{
System.out.println("Votes for Member " + TeamMember[Counter-1] + " : ");
System.out.print(getThings.getVotes(Vote));
}
}
//----------------------------------------------
//Declaration of EnterVotes()
//----------------------------------------------
public int[][] EnterVotes()
{
CorrectInput=true;
Vote = new int [NumberOfMember][index];
index=NumberOfMember;
if (NumberOfMember==0) {
System.out.println("Please Create a Project Before Entering Votes!"); //Error Message
ShowMenu=true;
}
for (int row=0; row < Vote.length; row++)
{
System.out.println("Enter "+ TeamMember[row]+"'s votes, points must add up to 100:");
System.out.println();
for (int col=0; col < Vote[row].length; col++)
{
System.out.println("Enter "+TeamMember[row]+ "'s points for"+ TeamMember[col]+":");
Vote[row][col] = scan.nextInt();
}
}
//if (sum!=100){
//System.out.println("Error. Please make sure all votes add up to 100.");
//EnterVotes();
//}
sumRow(Vote, NumberOfMember);
return Vote;
}
public int[] sumRow(int[][] Vote, int NumberOfMember)
{
int sum[] = new int[NumberOfMember];
for (int i = 0; i < Vote.length; i++){
int total = 0;
for (int j = 0; j < Vote[0].length; j++)
total +=Vote[i][j];
sum[i] = total;}
for(int i = 1; i < sum.length; i++)
{
if (sum[i] != 100) {
System.out.println("Please Make Sure the points add to 100!");
EnterVotes();
}
}
WriteOut getsecond = new WriteOut();
getsecond.SecondExport(Vote);
return sum;
}
//----------------------------------------------
//Declaration of CreateProject()
//----------------------------------------------
public String CreateProjectTitle()
{
CorrectInput = true;
ShowMenu = true; //Still show Menu
System.out.print("\n\tEnter the project name: "); //Asking user for a project name
ProjectName = scan.next();
CreateProjectNumberofMembers(); //calling methods within the resulting methods
CreateProjectNamesofMembers();
return ProjectName;
}
public int CreateProjectNumberofMembers(){ //ENTER NUMBER OF TEAM MEMBERS
System.out.print("\tEnter the number of team members: "); //Asking user to input a number for all members count
NumberOfMember = scan.nextInt();
System.out.print("\n");
return NumberOfMember;
}
public String[] CreateProjectNamesofMembers(){
TeamMember = new String[NumberOfMember];
for (int MemberCount = 1; MemberCount <= NumberOfMember; MemberCount ++) //For as long as the member count is less than the total number of members, the program will ask for the user input
{
//Statement of variable allocation to corresponding member position
System.out.print("\tEnter the name of team member " + MemberCount + ": ");
TeamMember[MemberCount - 1] = scan.next();
}
WriteOut getThings2= new WriteOut();
getThings2.FirstExport(NumberOfMember, ProjectName, TeamMember);
System.out.print("Press any key to return to the main menu: ");
String DummyInput = scan.next(); //This is a dummy variable where the input is never used again
ShowMenu = true; //Irrespective of the input, the menu will be shown again by assigning this boolean to tr
return TeamMember;
}
//----------------------------------------------
//Declaration of Quit() method
//----------------------------------------------
public void Quit()
{
CorrectInput = true;
ShowMenu = false; //if ShowMenu is false, the program's menu will terminate
//WriteOut();
System.out.println("\tGoodbye. ");
scan.close();
}
//--------------------------------------------------------------------------------
//Declaration of toString() method to check for all variable values when necessary
//--------------------------------------------------------------------------------
private String getNumberOfMember()
{
return Integer.toString(NumberOfMember);
}
private String getProjectName(int NumberOfProjects)
{
return ProjectName;
}
private String getTeamMemberName(int index)
{
return TeamMember[index - 1];
}
}
You have a field in class WriteOut:
public static String fileName;
and then a local variable in FirstExport with the same name:
String fileName="ok"; //initializing the file name
the local variable takes precedence inside FirstExport and the field is null when you get in SecondExport. You'll get what I understand is the expected behaviour if you just delete the local variable declaration.
Delete the local variable in your method FirstExport:
String fileName="ok";
You only want to use your public field
public static String fileName;
so you can access it from both methods.

Constructor ClassRoll(String f) assignment help, I need to identify why I cannot display the roll

So, basically I have an assignment that requires for me to Write a java program to help maintain a class roll. The program must contain four classes: Student, Exams, ClassRoll and Assignment4(Main).
I have developed all the classes but the ClassRoll constructor it s not performing correctly. When I run the program I am prompted with the file name option, once i enter the file name I see null then the options to modify and / or display the list, but when I enter a command, it does not work, it gives me an error.
The Output should be
Expected input/output:
Assuming that the file data.txt contains:
COP2210
John Doe 50 60 70
Marco Boyle 50 60 73
Eric Munzon 45 100 90
Marry Able 95 100 100
Jack Smith 100 100 100
Elizabeth Gomez 100 100 100
The following is a sample input output run:
What is the name of input file: data.txt
Enter one of the following commands
a or add to add a student in the class roll
sa or average to sort the students based on their average
sn or names to sort the students based on their last names
r or remove to remove a student from the class roll
s or save to save the list of students back to the datafile
Here are my classes;
public class Student {
private String fName = "";
private String lName = "";
private Exam scores;
public Student(String f, String l){
fName=f;
lName=l;
scores = new Exam();
}
public void setScore1(int score) {
scores.setScore1(score);
}
public void setScore2(int score) {
scores.setScore2(score);
}
public void setScore3(int score) {
scores.setScore3(score);
}
public String toString() {
return lName + "\t" + fName + "\t" +
scores.toString();
}
public double getAverage() {
return (scores.getScore1() + scores.getScore2() +
scores.getScore3())/3.0;
}
public boolean equals(String f, String l) {
return f.equals(fName) && l.equals(lName);
}
public int compareTo(Student s){
if (lName.compareTo(s.lName) > 0)
return 1;
else if (lName.compareTo(s.lName) < 0)
return -1;
else if (fName.compareTo(s.fName) > 0)
return 1;
else if (fName.compareTo(s.fName) < 0)
return -1;
else return 0;
}}
public class Exam {
private int score1;
private int score2;
private int score3;
public Exam(){
score1=0;
score2=0;
score3=0;
}
public void setScore1(int score) {
score1=score;
}
public int getScore1() {
return score1;
}
public void setScore2(int score) {
score2=score;
}
public int getScore2() {
return score2;
}
public void setScore3(int score) {
score3=score;
}
public int getScore3() {
return score3;
}
public String toString() {
return Integer.toString(score1) + "\t"
+Integer.toString(score2)
+ "\t" + Integer.toString(score3) + "\t";
}}
public class ClassRoll {
ArrayList students = new ArrayList();
String title;
String fileName;
public ClassRoll(String f) throws IOException {
Scanner fileScan, lineScan;
String line;
fileName = f;
fileScan = new Scanner(new File(f));
title = fileScan.nextLine();
System.out.println("Title =" + title);
while (fileScan.hasNext()) {
line = fileScan.nextLine();
lineScan = new Scanner(line);
lineScan.useDelimiter("\t");
String lastName = lineScan.next();
String firstName = lineScan.next();
Student s = new Student(firstName, lastName);
s.setScore1(lineScan.nextInt());
s.setScore2(lineScan.nextInt());
s.setScore3(lineScan.nextInt());
students.add(s);
//display(students);
ClassRoll c = new ClassRoll();
c.display();
}
}
void display() {
DecimalFormat fmt = new DecimalFormat("0.00");
System.out.println("\t\t\t" + title);
double classAverage = 0.0;
for (int i = 0; i < students.size(); i++) {
Student s = (Student) students.get(i);
System.out.print(s.toString());
System.out.println("\t" + fmt.format(s.getAverage()));
classAverage = classAverage + s.getAverage();
}
System.out.println("\t\t\t" + fmt.format(classAverage /
students.size()));
}
public void insert() {
Scanner input = new Scanner(System.in);
System.out.print("First Name -> ");
String firstName = input.next();
System.out.print("Last Name -> ");
String lastName = input.next();
System.out.print("Score 1 -> ");
int score1 = input.nextInt();
System.out.print("Score 2 -> ");
int score2 = input.nextInt();
System.out.print("Score 3 -> ");
int score3 = input.nextInt();
Student s = new Student(firstName, lastName);
s.setScore1(score1);
s.setScore2(score2);
s.setScore3(score3);
students.add(s);
}
private int search(String f, String l) {
int i = 0;
while (i < students.size()) {
Student s = (Student) students.get(i);
if (s.equals(f, l)) {
return i;
} else {
i++;
}
}
return -1;
}
public Student find() {
Scanner input = new Scanner(System.in);
System.out.print("First Name -> ");
String firstName = input.next();
System.out.print("Last Name -> ");
String lastName = input.next();
int i = search(firstName, lastName);
if (i >= 0) {
return (Student) students.get(i);
} else {
return null;
}}
public void delete() {
Scanner input = new Scanner(System.in);
System.out.print("First Name -> ");
String firstName = input.next();
System.out.print("Last Name -> ");
String lastName = input.next();
int i = search(firstName, lastName);
if (i >= 0) {
students.remove(i);
} else {
System.out.println("Student not found");
}
}
public void sortLastNames() {
for (int i = 0; i < students.size() - 1; i++) {
for (int j = i + 1; j < students.size(); j++) {
Student s1 = (Student) students.get(i);
Student s2 = (Student) students.get(j);
if (s1.compareTo(s2) > 0) {
students.set(i, s2);
students.set(j, s1);
}
}
}}
public void sortAverage() {
for (int i = 0; i < students.size() - 1; i++) {
for (int j = i + 1; j < students.size(); j++) {
Student s1 = (Student) students.get(i);
Student s2 = (Student) students.get(j);
if (s1.getAverage() < s2.getAverage()) {
students.set(i, s2);
students.set(j, s1);
}
}}}
public void save() throws IOException {
PrintWriter out = new PrintWriter(fileName);
out.println(title);
for (int i = 0; i < students.size(); i++) {
Student s = (Student) students.get(i);
out.println(s.toString());
}
out.close();
}}
public class Assignment4bis {
public static void main(String[] args) throws IOException {
Scanner input=new Scanner(System.in);
System.out.print("Enter the name of the input file ->");
String fileName=input.next();
ClassRoll c = new ClassRoll();
c.display();
prompt();
System.out.print("Enter a command --> ");
String ans=input.next();
while (!(ans.equalsIgnoreCase("q") || ans.equalsIgnoreCase("quit")))
{
if(!(ans.equalsIgnoreCase("i") ||ans.equalsIgnoreCase("insert") ||
ans.equalsIgnoreCase("a") || ans.equalsIgnoreCase("average") ||
ans.equalsIgnoreCase("n") || ans.equalsIgnoreCase("names") ||
ans.equalsIgnoreCase("r") || ans.equalsIgnoreCase("remove") ||
ans.equalsIgnoreCase("f") || ans.equalsIgnoreCase("find") ||
ans.equalsIgnoreCase("d") || ans.equalsIgnoreCase("display")))
System.out.println("Bad Command");
else
switch (ans.charAt(0))
{
case 'i': c.insert();
break;
case 'a': c.sortAverage();
c.display();
break;
case 'n': c.sortLastNames();
c.display();
break;
case 'r': c.delete();
c.display();
break;
case 'f': Student s=c.find();
if (s == null)
System.out.println("Student not found");
else System.out.println(s.toString());
break;
case 'd': c.display();
break;
}
prompt();
System.out.print("Enter a command --> ");
ans=input.next();
}
c.save();
System.out.println("Thank you for using this program");
}
public static void prompt(){
System.out.println("Enter one of the following commands");
System.out.println("i or insert to insert a student in the class
roll");
System.out.println("a or average to sort the students based on
their average");
System.out.println("n or names to sort the students based on their
last names");
System.out.println("r or remove to remove a student from the class
roll");
System.out.println("f or find to find a student in the class
roll");
System.out.println("d or display to display the class roll");
System.out.println("q or quit to exit the program");
}}
Errors that I m still getting...
run:
Enter the name of the input file ->data.txt
Title =COP2210
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at assignment4bis.ClassRoll.<init>(ClassRoll.java:40)
at assignment4bis.Assignment4bis.main(Assignment4bis.java:28)
Java Result: 1
Your ClassRoll "constructor" is a "pseudo-constructor":
public class ClassRoll {
ArrayList students = new ArrayList();
String title;
String fileName;
public void ClassRoll(String f) throws IOException {
Constructors have no return type, so get rid of the void:
public class ClassRoll {
ArrayList students = new ArrayList();
String title;
String fileName;
public ClassRoll(String f) throws IOException {
As a bit of side recommendations:
You look to be mixing user interface with one of your "model" or logical classes, ClassRoll, something you probably shouldn't do. I'd keep all user interface code, including use of a Scanner and File I/O separate from ClassRoll, which likely should just have code to create the collection, to allow other classes to add or remove from the collection, and to allow other classes to query the collection.
Take care to learn and follow Java code formatting rules. You've got some deviations from the standard, including have your class declaration lines indented the same as the method body and variable declaration lines, bunching up of end braces,... This makes your code hard for other Java coders to read and understand.

How to fix my Array class

I am trying to figure out how to get my array to run correctly, I know I have to change the array value to an input but I cannot get the program to compile if any one can help that be great.
I am trying to have the program take input for grades and names of students and in the end output their name and grade.
Edit sorry this is my first it posting i have an error
Student.java:60: error: class, interface, or enum expected I am in java 101 so this is why it is such low level java, we only know the basics
import java.util.Scanner;
public class students
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("How many students?: ");
int numofstudents = keyboard.nextInt();
Student s = new Student();
s.setMultipleStudents();
s.toString();
System.out.println("Enter the Grade for the student: ");
int gradeofstudnets = keyboard.nextInt();
}
}
and my second class is
import java.util.Scanner;
public class Student
{
Scanner scan = new Scanner(System.in);
private String name;
private int grade;
private int[] multiplegradeinputs = new int[10];
private String[] multipleStudent = new String[10];
public Student()
{
}
public Student(String n, int g)
{
name = n;
grade = g;
}
public String setMultipleStudents()
{
String n = "";
for(int i = 1; i < multipleStudent.length; i++)
{
System.out.println("Enter student #" + i +" name: " );
n = scan.nextLine();
multipleStudent[i] = n;
}
return null;
}
public String multiplegradeinputs()
{
for(int i = 1; i <multiplegradeinputs.length; i++)
{
System.out.println("Enter the Grade of the student#" + i +" : ");
grade = scan.nextInt();
multiplegradeinputs[i] = grade;
}
} <--- error here
public String toString()
{
String temp = "";
for(int i = 1; i < multipleStudent.length; i++)
{
temp += multipleStudent[i] + " ";
}
return temp;
}
}
Add return statement in your multiplegradeinputs() method:
public String multiplegradeinputs()
{
for(int i = 1; i <multiplegradeinputs.length; i++)
{
System.out.println("Enter the Grade of the student#" + i +" : ");
grade = scan.nextInt();
multiplegradeinputs[i] = grade;
}
return null; //Add this line
}
Or change your methods to void return type if they dont return anything.
Class names have to be capitalized in java, so instead of
public class students
you should write
public class Students
Also instead of writing
keyboard.nextInt();
You should write
Integer.parseInt(keyboard.nextLine());
This is mainly because java is full of bugs and technical specifications that you won't find easily. Let me know if this fixes it for you, since you didn't post the exact error message you got.
As for the error that you pointed out, it's because your function expects a String as a return value no matter what, so either change that to void if you can or return a null string. To do that just add the following line at the very end of the method.
return null;
You should create a Student object which holds the properties of the student, e.g. Name and Grades. You should then store all the student objects in some kind of data structure such as an array list in the students class.
Adding to the answer provided by #hitz
You have a bug in the for loops:
for(int i = 1; i <multiplegradeinputs.length; i++)
for(int i = 1; i < multipleStudent.length; i++)
You will never populated multiplegradeinputs[0] and multipleStudent[0] because you start the loop at index == 1 and thus you will have only 9 student names stored instead of 10.
Change to:
for(int i = 0; i <multiplegradeinputs.length; i++)
for(int i = 0; i < multipleStudent.length; i++)
Remember even though the length in 10, the indices always start with 0 in Java and in your case will end with 9.
import java.util.Scanner;
public class Student
{
Scanner scan = new Scanner(System.in);
private String name;
private int grade;
private int[] multiplegradeinputs = new int[10];
private String[] multipleStudent = new String[10];
public Student()
{
}
public Student(String n, int g)
{
name = n;
grade = g;
}
public String setMultipleStudents()
{
String n = "";
for(int i = 1; i < multipleStudent.length; i++)
{
System.out.println("Enter student #" + i +" name: " );
n = scan.nextLine();
multipleStudent[i] = n;
}
return null;
}
public void multiplegradeinputs()
{
for(int i = 1; i <multiplegradeinputs.length; i++)
{
System.out.println("Enter the Grade of the student#" + i +" : ");
grade = scan.nextInt();
multiplegradeinputs[i] = grade;
}
}
public String toString()
{
String temp = "";
for(int i = 1; i < multipleStudent.length; i++)
{
temp += multipleStudent[i] + " ";
}
return temp;
}
}
this is the 2nd class
import java.util.Scanner;
public class students
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("How many students?: ");
int numofstudents = keyboard.nextInt();
Student s = new Student();
s.setMultipleStudents();
s.toString();
System.out.println("Enter the Grade for the student: ");
int gradeofstudnets = keyboard.nextInt();
}
}
You are missing a return value in the multiplegradeinputs() method.

Formatting output method

I have a question with the display array method. I can't figure how to make it to format this:
Credit Card # 4:
8908 9014 8812 1331
What I need to do is for each array element call the display method and pass the index of the array in a string for the label, I just cant figure out how to do this, I tried this but it is wrong:
System.out.println(display("Credit Card # %d", cred1[i]));
Can anyone please suggest a way to do this?
package homework4;
import java.util.Scanner;
public class Prog4 {
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args)
{ CreditCardNumber[] cred1;
CreditCardNumber cred2 = getInput();
Display("The complete number from your input:", cred2);
cred1 = getInputArray();
DisplayArray(cred1);
TryAnother();
}
public static CreditCardNumber getInput() {
String ID;
String accNum;
CreditCardNumber tempCred;
System.out.printf("Please enter issuer ID:");
ID = scanner.next();
System.out.printf("Please enter account number:");
accNum = scanner.next();
tempCred = new CreditCardNumber(ID, accNum);
return tempCred;
}
public static void Display(String ch, CreditCardNumber cred2)
{
System.out.println(ch);
System.out.println(cred2.toString().replaceAll(".{4}", "$0 "));
}
public static CreditCardNumber[] getInputArray()
{
CreditCardNumber[] tempArray;
String tempID;
int size;
System.out.printf("Please enter size of the aray:");
size = scanner.nextInt();
if(size < 1)
{
size = 1;
}
tempArray = new CreditCardNumber[size];
System.out.printf("Please enter issuer ID:");
tempID = scanner.next();
System.out.print(tempArray.length);
for(int i = 0; i < tempArray.length; i++)
{
tempArray[i] = new CreditCardNumber();
tempArray[i].CreateCred(tempID);
}
return tempArray;
}
public static void DisplayArray(CreditCardNumber[] cred1)
{
for(int i = 0; i< cred1.length; i++)
{
System.out.println(display("Credit Card # %d", cred1[i]));
}
}
public static boolean TryAnother()
{
String s;
System.out.printf("Get more credit card numbers? (n for no):");
s = scanner.next();
if(s.charAt(0) != 'N' && s.charAt(0) != 'n')
{
return true;
}
return false;
}
}
sounds like all you need is a new line character. For example.
System.out.println("Credit Card # " + cred1[i] + "\n" + cred2.toString());
The new line character "\n" will drop the output onto it's own line.
Do this:
System.out.format("Credit Card # %d:\n%s", i, cred1[i].toString());

Categories

Resources