Getter and setter methods and reading a txt file - java

Esentially, I'm reading a text file in my driver class, but I'm calling a methods from another class with instructions to read from the text file from another class, but it just isn't working. This is what I have so far in my driver class:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class CourseGrade {
static int numberOfStudents;
private int numberOfAssignAndLabs;
private int numberOfTestsAndQuiz;
private static int patZyanteAttend = 3;
static int patZyanteAttendScore = 0;
public void setNumberOfAssignAndLabs() {
numberOfAssignAndLabs = 21;
}
public int getNumberOfAssignAndLabs() {
return numberOfAssignAndLabs;
}
public void setNumberOfTestsAndQuiz() {
numberOfTestsAndQuiz = 4;
}
public int getNumberOfTestsAndQuiz() {
return numberOfTestsAndQuiz;
}
public static void main(String[] args) {
Student myStudent = new Student();
Scanner scanner = new Scanner(System.in);
try {
scanner = new Scanner(new File("grades.txt"));
} catch (FileNotFoundException e) {
System.out
.println("Error opening file. Please make sure that you have a grades.txt file in the same folder as GradeCalculator.class");
System.exit(0);
}
System.out.println("Name" + "\t" + "\t" + "Assignment Score" + "\t"
+ "Test Score");
numberOfStudents = scanner.nextInt();
for (int i = 0; i < numberOfStudents; i++) {
myStudent.setFirstName();
System.out.print(myStudent.getFirstName() + " ");
myStudent.setLastName();
System.out.print(myStudent.getLastName());
myStudent.setHomeworkScore();
System.out.print(myStudent.getHomeworkScore() + " ");
myStudent.setTestScore();
System.out.print(myStudent.getTestScore());
myStudent.computeGrade();
System.out.println(myStudent.getGrade());
for (int l = 0; l < patZyanteAttend; l++) {
int temp;
temp = scanner.nextInt();
patZyanteAttendScore += temp;
}
}
}
}
and this is the class I'm calling:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Student {
private String firstName;
private String lastName;
private String letterGrade;
private int homeworkScore;
private int testScore;
CourseGrade myCourseGrade = new CourseGrade();
Scanner scanner = new Scanner(System.in);
public Student() {
homeworkScore = 0;
testScore = 0;
}
public void setFirstName() {
firstName = scanner.next();
}
public String getFirstName() {
return firstName;
}
public void setLastName() {
lastName = scanner.next();
}
public String getLastName() {
return lastName;
}
public void setHomeworkScore() {
int temp;
for (int j = 0; j < myCourseGrade.getNumberOfAssignAndLabs(); j++) {
temp = scanner.nextInt();
homeworkScore += temp;
}
}
public int getHomeworkScore() {
return homeworkScore;
}
public void setTestScore() {
int temp;
for (int k = 0; k < myCourseGrade.getNumberOfTestsAndQuiz(); k++) {
temp = scanner.nextInt();
testScore += temp;
}
}
public int getTestScore() {
return testScore;
}
public void computeGrade() {
if (homeworkScore <= 599 || testScore <= 149 || homeworkScore <= 719
&& testScore <= 179 || homeworkScore <= 779 && testScore <= 164
|| homeworkScore <= 659 && testScore <= 209) {
letterGrade = "P";
}
if (homeworkScore >= 1140 && testScore >= 180 || homeworkScore >= 1080
&& testScore >= 195 || homeworkScore >= 960 && testScore >= 210
|| homeworkScore >= 900 && testScore >= 225
|| homeworkScore >= 840 && testScore >= 240
|| homeworkScore >= 780 && testScore >= 255
|| homeworkScore >= 720 && testScore >= 285) {
letterGrade = "G";
} else {
letterGrade = "A";
}
}
public String getGrade() {
return letterGrade;
}
}
For whatever reason, the program terminates when I get inside the for loop

Your setters should take a parameter, so it knows what value to set
for example, in Student:
public void setFirstName(String fName) {
firstName = fName;
}
sets the field firstname in the Student class, from the value of the fName method parameter.
When you call the method from main, include the forename from the file you are reading:
myStudent.setFirstName(scanner.next());
You don't need a scanner in your Student class.
Change all your setters to take a parameter, and use the Scanner in main to supply the values.

Related

count no. of vowels, consonants, and print their count and product in a string

In the Question we are given 2 strings and we have to count no. of vowels, no. of consonants and display their product individually for each string.
Expected Output
2 6 12
0 7 0
Output getting
0 0 0
2 6 12
Here is the code-
import java.io.*;
import java.util.*;
public class CandidateCode {
public static void main(String args[] ) throws Exception {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
for(int i=0;i<n;i++)
{
String s=sc.nextLine();
alpha(s);
System.out.println();
}
}
private static void alpha(String s)
{
int count=0;
int length=s.length();
for(int i=0;i<length;i++)
{
if(s.charAt(i)=='a' || s.charAt(i)=='e' || s.charAt(i)=='i' || s.charAt(i)=='o' || s.charAt(i)=='u')
count++;
}
int c=length-count;
int product = c * count;
System.out.printf("%d %d %d",count,c,product);
}
}
public class CandidateCode {
public static void main(String args[]) throws Exception {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your number : ");
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
System.out.println("Enter your name : ");
String s = sc.next();
alpha(s);
}
}
private static void alpha(String str) {
int vCount = 0, cCount = 0;
str = str.toLowerCase();
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i' || str.charAt(i) == 'o' || str.charAt(i) == 'u') {
vCount++;
} else if (str.charAt(i) >= 'a' && str.charAt(i) <= 'z') {
cCount++;
}
}
System.out.println("Number of vowels: " + vCount);
System.out.println("Number of consonants: " + cCount);
System.out.println("Product of vowels and consonants :" + vCount * cCount);
}
}

Calling getter from imported class

I am having trouble calling a getter from an imported class.
I have created a working class (Students) and an action class (ProgressReport). The main class reads a text file and writes the data to an array. The data is then manipulated in the working class. Last, ProgressReport.generateReport will create a report giving the students name, their grade average and the letter grade associate with that average.
I am having trouble using the Students getters from the Progress Report class. Eclipse is saying the method is undefined. I am not exactly sure what I have done wrong or how to go about fixing it. Any help would be very much appreciated.NOTE: I added some println to make sure parts of the code were being executed. Thank you all in advance.
Code to follow:
Progress Report
package Lab1A;
import java.util.*;
import Lab1A.Students;
import java.io.*;
public class ProgressReport {
public Students section[][];
public static void main(String[] args) throws IOException
{
Students tmpStudent;
ProgressReport progressReport = new ProgressReport();
progressReport.readInputFile();
progressReport.generateReport();
System.out.println("\nSEARCH TEST");
tmpStudent = null;
tmpStudent = progressReport.sequentialSearch(0, "Cooper");
if (tmpStudent != null)
System.out.println("Found " + tmpStudent.getName() +
"\tAverage = " + tmpStudent.getAverage() +
"\tGrade = " + tmpStudent.getGrade());
else System.out.println("Fail to find the student");
tmpStudent = null;
tmpStudent = progressReport.sequentialSearch(0, "Bronson");
if (tmpStudent != null)
System.out.println("Found " + tmpStudent.getName() +
"\tAverage = " + tmpStudent.getAverage() +
"\tGrade = " + tmpStudent.getGrade());
else System.out.println("Fail to find the student");
tmpStudent = null;
tmpStudent = progressReport.sequentialSearch(1, "Diana");
if (tmpStudent != null)
System.out.println("Found " + tmpStudent.getName() +
"\tAverage = " + tmpStudent.getAverage() +
"\tGrade = " + tmpStudent.getGrade());
else System.out.println("Fail to find the student");
}
public ProgressReport()
{
section = new Students [2][];
}
public void readInputFile() throws FileNotFoundException
{
System.out.println("in readInputFile method");
//Open file
File input = new File("Lab1A.in");
Scanner inputFile = new Scanner(input);
System.out.println("file is open");
//Read file data
int currentStudent = 0;
while (inputFile.hasNext())
{
System.out.println("In while loop");
//Get Student count
int rows = inputFile.nextInt();
//Read student data
section[currentStudent] = new Students[rows];
System.out.println("array initiated");
for(int i = 0; i < rows; i++)
{
System.out.println("In for loop");
//read in a students info
String sName = inputFile.next();
//Read in grades
int grade1 = inputFile.nextInt();
int grade2 = inputFile.nextInt();
int grade3 = inputFile.nextInt();
int grade4 = inputFile.nextInt();
int grade5 = inputFile.nextInt();
//Send to Students Array
section[currentStudent][i] = new Students(sName, grade1, grade2, grade3, grade4, grade5);
}
//Next Student Line
currentStudent++;
}
inputFile.close();
}
public void generateReport()
{
System.out.println("Progress Report");
double average = Students.class.getAverage();
//String section = "Section\n";
}
public Students sequentialSearch(int section, String searchName)
{
return null;
}
}
Students Class
package Lab1A;
import java.lang.reflect.Array;
public class Students {
private String name;
private char grade;
private double average;
private int scores[];
public Students(String sName, int grade1, int grade2, int grade3, int grade4, int grade5)
{
//CONSTRUCTOR load data from ProgressReport
name = sName;
int newScores[] = {grade1, grade2, grade3, grade4, grade5};
scores = newScores;
}
//Getters and Setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public char getGrade() {
if(average >= 90 && average <= 100)
{
grade = 'A';
}
if(average >= 80 && average < 90)
{
grade = 'B';
}
if(average >= 70 && average < 80)
{
grade = 'C';
}
if(average >= 60 && average < 70)
{
grade = 'D';
}
if(average >= 0 && average < 60)
{
grade = 'F';
}
return grade;
}
public void setGrade(char grade) {
this.grade = grade;
}
public double getAverage() {
return average;
}
public void setAverage(double average) {
this.average = average;
}
public int[] getScores() {
return scores;
}
public void setScores(int[] scores) {
this.scores = scores;
}
//Calculate average score
public void calculateAverage()
{
int total = 0;
for (int i = 0; i < scores.length; i++)
{
total += scores[i];
}
average = total*1.0/scores.length;
}
//calculate letter grade based on average score (calulateAverage.average)
public void calculateGrade()
{
if(average >= 90 && average <= 100)
{
grade = 'A';
}
if(average >= 80 && average < 90)
{
grade = 'B';
}
if(average >= 70 && average < 80)
{
grade = 'C';
}
if(average >= 60 && average < 70)
{
grade = 'D';
}
if(average >= 0 && average < 60)
{
grade = 'F';
}
}
}
Your not specifying which Student you want the average of (Not sure why you named your class students with an s). It needs to look something like this:
section[1][1].getAverage()

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at lab3.Lab3.readTestScore(Lab3.java:93) at lab3.Lab3.main(Lab3.java:25)

package lab3;
import java.util.Scanner;
public class Lab3
{
static int n;
static double testScores[] = new double[n];
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int studentID;
System.out.println("Enter student ID: ");
studentID = input.nextInt();
System.out.println("Enter number of test scores");
n = input.nextInt();
readTestScore(n);
//double[] testarray = readTestScore(n);
//System.out.println("Test Scores are:" + testarray);
}
public char getLetterGrade(double score)
{
char letter;
if(score >= 90)
{
printComment('A');
letter = 'A';
}
if(score >= 80)
{
printComment('B');
letter = 'B';
}
if(score >= 70)
{
printComment('D');
letter = 'C';
}
else if(score >= 60)
{
printComment('D');
letter = 'D';
}
else if(score < 60)
printComment('F');
letter = 'F';
return letter;
}
static void printComment(char grade)
{
if(grade == 'A')
System.out.println("COMMMENT\t\t\t:\t" + "Very Good!");
if(grade == 'B')
System.out.println("COMMMENT\t\t\t:\t" + "Good!");
if(grade == 'C')
System.out.println("COMMMENT\t\t\t:\t" + "Satisfactory.");
if(grade == 'D')
System.out.println("COMMMENT\t\t\t:\t" + "Needs Improvement.");
if(grade == 'F')
System.out.println("COMMMENT\t\t\t:\t" + "Poor.");
}
static void printTestResults(double []testList)
{
for(int i = 0; i < testList.length; i++)
{
System.out.println("Test Score\t\t\t" + "Letter Grade\t\t\t" + "Comment\t\t\t");
System.out.println(testScores[i] + "\t\t\t" );//+ getLetterGrade(score) + "\t\t\t" + printComment(grade));
}
}
static double[] readTestScore(int size)
{
Scanner input = new Scanner(System.in);
int i =0;
System.out.println("Enter Test Scores:\t");
for(i = 0; i<n; i++)
{
testScores[i] = input.nextDouble();
}
testScores[i] /=n;
System.out.println("these are test scores: " + testScores);
return (testScores);
}
}
Because of this
static int n;
static double testScores[] = new double[n];
array is set to default size of int ie 0 giving you that error in the method

Reader does not stop in my program (java)

I am still fairly new to java and in my current class project we are trying to set students to classrooms, the students information is read from a text file which we create but my reader program does not stop after 4 lines (which is the end of the information of the student). It reads through all of them and prints them before analyzing what they have to be able to put them in the correct classRoom. Please remember I am still new to java.
Also not sure about an error I keep getting about Exception in thread "main" java.util.NoSuchElementException: No line found
this is my reader program
import java.io.*;
import java.util.Scanner;
public class Student{
private Scanner file;
public String name;
public String id;
public String year;
public String course;
//open the file to read
public void openFile(){
try{
file = new Scanner(new File("StudentFile.txt"));
}
catch(Exception e)
{
System.out.print("Could not Open File");
}
}
//Read the file and Assign the Student information strings
protected void readFileText(){
if(file.hasNext())
{
for(int n=0; n<4; n++)
{
name = file.nextLine();
id = file.nextLine();
year = file.nextLine();
course = file.nextLine();
System.out.print("\n" + name + "\n" + id + "\n" + year + "\n" + course + "\n");
}
}
else
{
name = null;
}
}
//close the file
public void closeFile(){
file.close();
}
//set information
public Student(){
this.name = name;
this.id = id;
this.year = year;
this.course = course;
}
//Get the informaton to main method
public String getName(){
return name;
}
public String getId(){
return id;
}
public String getYear(){
return year;
}
public String getCourse(){
return course;
}
}
This is my main method
public class Registrar {
public static void main(String[] args) {
Student student = new Student();
student.openFile();
String namenull = " ";
String classRoom[] = {"Washington W1000", "Washington W1100", "Washington W1200", "Washington W1300", "Washington W1400", "Washington W1500", "Kennedy K1000", "Kennedy K1100", "Kennedy K1200", "Kennedy K1300"};
int maxCapacity = 25;
int studentNum = 0;
int num = 0;
int n = 0;
String currentClass = classRoom[0];
while(namenull != null){ // to read the file and set students to a classroom.
student.readFileText();
String course = student.getCourse();
while (n < 10){
if(currentClass == "Washington W1400"){
maxCapacity = 30;
}
else if(currentClass == "Kennedy 1000"){
maxCapacity = 25;
}
else if(currentClass == "Kennedy 1200"){
maxCapacity = 35;
}
int num1 = 1;
int num2 = 2;
int num3 = 3;
if(studentNum < maxCapacity && course == "Comp 182" && num < 10){
System.out.print("\nRegistered in Comp 182, in classroom " + currentClass);
studentNum++;
}
else{
while(num == num1 || num == num2 || num == num3 || num == num){
num = num++;
}
}
if(studentNum < maxCapacity && course == "Comp 182 Lab" && num1 < 10){
currentClass = classRoom[num1];
System.out.print("\nRegistered in Comp 182 Lab, in classroom " + currentClass);
studentNum++;
}
else{
while(num1 == num || num1 == num2 || num1 == num3 || num1 == num1){
num1 = num1++;
}
}
if(studentNum < maxCapacity && course == "Comp 101" && num2 < 10){
currentClass = classRoom[num2];
System.out.print("\nRegistered in Comp 101, in classroom " + currentClass);
studentNum++;
}
else{
while(num2 == num || num2 == num1 || num2 == num3 || num2 == num2){
num2 = num2++;
}
}
if(studentNum < maxCapacity && course == "Comp 101 Lab" && num3 <10){
currentClass = classRoom[num3];
System.out.print("\nRegistered in Comp 101 Lab, in classroom " + currentClass);
studentNum++;
}
else{
while(num3 == num || num3 == num1 || num3 == num2 || num3 == num3){
num3 = num3++;
}
}
currentClass = classRoom[num];
}
namenull = student.getName();
}
student.closeFile();
}
}
As Requested, my StudentFile.txt
Alfredo Dominguez
1205586453
Freshman
Comp 182
Stacy Flores
6584527256
Sophmore
Comp 182 Lab
Scanner throws NoSuchElementException if no line was found. so wrap each file.nextLine(); with
if(file.hasNextLine()){
file.nextLine();
}

Scanning from file with seperate classes, scanner starts over when going between classes

my code:
Student class...
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Student {
private Scanner scanner;
//initialize data members
private String firstName;
private String lastName;
private int assignmentScore;
private int labScore;
private int quizScore;
private int attendanceScore;
private int homeworkScore;
private int midterm1Score;
private int midterm2Score;
private int finalExamScore;
private int zyanteScore;
private int patScore;
private int testScore;
private String letterGrade;
public void setScanner() {
try { //start try statement
scanner = new Scanner(new File("gradesA5.txt")); //initialize scanner to scan from the grades.txt file
} //end try statement
catch (FileNotFoundException e) { //start catch statement
System.out.println("Error opening file. Please make sure t that you have a grades.txt file in the same folder as GradeCalculator.class"); //print statement telling user that the grades.txt file is not in the right place
System.exit(0); //system exit
} //end catch statement
}
public Scanner getScanner(){
return scanner;
}
public void setfirstName(){
if(scanner.hasNext()){
firstName = scanner.next();
}
}
public String getFirstName(){
return firstName;
}
public void setLastName(){
if(scanner.hasNext()){
lastName = scanner.next();
}
}
public String getLastName(){
return lastName;
}
public void setAssignmentScore(){
assignmentScore = 0;
int i = 0;
int[] assignment = new int[6];
while(scanner.hasNext() && i <= 5){
assignment[i] = scanner.nextInt();
assignmentScore += assignment[i];
i++;
}
}
public int getAssignmentScore(){
return assignmentScore;
}
public void setLabScore(){
labScore = 0;
int i = 0;
int[] lab = new int[15];
while(scanner.hasNext() && i <=14){
lab[i] = scanner.nextInt();
labScore += lab[i];
i++;
}
}
public int getLabScore(){
return labScore;
}
public void setQuizScore(){
if(scanner.hasNext()){
quizScore = scanner.nextInt();
}
}
public int getQuizScore(){
return quizScore;
}
public void setAttendanceScore(){
if(scanner.hasNext()){
attendanceScore = scanner.nextInt();
}
}
public int getAttendanceScore(){
return attendanceScore;
}
public int computeTotalHomeworkScore(){
homeworkScore = (assignmentScore + labScore + attendanceScore);
return homeworkScore;
}
public void setMidterm1Score(){
if(scanner.hasNext()){
midterm1Score = scanner.nextInt();
}
}
public int getMidterm1Score(){
return midterm1Score;
}
public void setMidterm2Score(){
if(scanner.hasNext()){
midterm2Score = scanner.nextInt();
}
}
public int getMidterm2Score(){
return midterm2Score;
}
public void setFinalExamScore(){
if(scanner.hasNext()){
finalExamScore = scanner.nextInt();
}
}
public int getFinalExamScore(){
return finalExamScore;
}
public void setZyanteScore(){
if(scanner.hasNext()){
zyanteScore = scanner.nextInt();
}
}
public int getZyanteScore(){
return zyanteScore;
}
public void setPATScore(){
if(scanner.hasNext()){
patScore = scanner.nextInt();
}
}
public int getPATScore(){
return patScore;
}
public int computeTotalTestScore(){
testScore = (midterm1Score + midterm2Score + finalExamScore + quizScore + zyanteScore + patScore);
return testScore;
}
public void computeLetterGrade(){
if ((testScore <165 && homeworkScore <780) || (testScore <180 && homeworkScore <720) || (testScore <195 && homeworkScore <660) || (testScore <210 && homeworkScore <660) || (homeworkScore <600)){ //if statement that executes if scores earned a failing grade
letterGrade = "P" ; //sets letterGrade string to P
} //end if statement
if (((testScore >= 150 && testScore <= 164) && (homeworkScore >= 780)) || ((testScore >= 165 && testScore <= 179) && (homeworkScore >=720)) || ((testScore >=180 && testScore <=194) && (homeworkScore >= 660 && homeworkScore <= 1139)) ||
((testScore >= 195 && testScore <= 209) && (homeworkScore >= 660 && homeworkScore <= 1079)) || ((testScore >= 210 && testScore <= 224) && (homeworkScore>= 600 && homeworkScore <= 959)) || ((testScore >= 225 && testScore <= 239) && (homeworkScore >= 600 && homeworkScore <= 899)) ||
((testScore >= 240 && testScore <= 254) && (homeworkScore >= 600 && homeworkScore <= 839)) || ((testScore >= 255 && testScore <= 269) && (homeworkScore >= 600 && homeworkScore <= 779)) || ((testScore >= 270 && testScore <= 284) && (homeworkScore >= 600 && homeworkScore <= 779)) ||
((testScore >= 285 && testScore <= 300) && (homeworkScore >= 600 && homeworkScore <= 719))) { //if statement that executes if scores earned an average grade
letterGrade = "A" ; //sets letterGrade string to A
} //end if statement
if (((testScore >= 180 && testScore <= 194) && (homeworkScore >= 1140 && homeworkScore <= 1200)) || ((testScore >= 195 && testScore <= 209) && (homeworkScore >= 1080 && homeworkScore <= 1200)) ||
((testScore >= 210 && testScore <= 224) && (homeworkScore >= 960 && homeworkScore <= 1200)) || ((testScore >= 225 && testScore <= 239) && (homeworkScore >= 900 && homeworkScore <= 1200)) ||
((testScore >= 240 && testScore <= 254) && (homeworkScore >= 840 && homeworkScore <= 1200)) || ((testScore >= 255 && testScore <= 269) && (homeworkScore >= 780 && homeworkScore <= 1200)) ||
((testScore >= 270 && testScore <= 284) && (homeworkScore >= 780 && homeworkScore <= 1200)) || ((testScore >= 285 && testScore <= 300) && (homeworkScore >= 720 && homeworkScore <= 1200))) { //if statement that executes if scores earned a good grade
letterGrade = "G" ; //sets letterGrade string to G
} //end if statement
}
public String getLetterGrade(){
return letterGrade;
}
public void testing() {
for (int i = 0; i < 7; i++) {
if (scanner.hasNext()) {
String test = scanner.next();
}
}
}
}
CourseOffering class...
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class CourseOffering {
private Scanner scanner;
Student myStudent = new Student();
//initialize data members
private int students;
private String description;
private int allTotalHomeworkScore = 0;
private int allTotalTestScore = 0;
private int totalStudents = 0;
private int numberOfSemesters;
private int studentArrayCount = 0;
private double homeworkAverage;
private double testAverage;
public CourseOffering(Scanner inScanner){
scanner = inScanner;
}
public void setNumberOfSemesters(){
if(scanner.hasNext()){
numberOfSemesters = scanner.nextInt();
}
}
public int getNumberOfSemesters(){
return numberOfSemesters;
}
public void setStudents(){
int[] student = new int[numberOfSemesters];
student[studentArrayCount] = scanner.nextInt();
students = student[studentArrayCount];
studentArrayCount++;
totalStudents += students;
}
public double computeHomeworkAverage(){
allTotalHomeworkScore += myStudent.computeTotalHomeworkScore();
homeworkAverage = (allTotalHomeworkScore / totalStudents);
return homeworkAverage;
}
public double computeTestAverage(){
allTotalTestScore += myStudent.computeTotalTestScore();
testAverage = (allTotalTestScore / totalStudents);
return testAverage;
}
public void countPassingStudents(){
}
}
CourseStatistics class (the one that calls the others)...
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class CourseStatistics {
public static void main(String[] args) {
Scanner scanner = null;
try { //start try statement
scanner = new Scanner(new File("gradesA5.txt")); //initialize scanner to scan from the grades.txt file
} //end try statement
catch (FileNotFoundException e) { //start catch statement
System.out.println("Error opening file. Please make sure that you have a grades.txt file in the same folder as GradeCalculator.class"); //print statement telling user that the grades.txt file is not in the right place
System.exit(0); //system exit
} //end catch statement
Student myStudent = new Student();
CourseOffering myCourse = new CourseOffering(scanner);
myStudent.setScanner();
myStudent.getScanner();
myStudent.testing();
myCourse.setNumberOfSemesters();
for(int i = 0; i < 4; i++){
myStudent.setfirstName();
myStudent.setLastName();
myStudent.setAssignmentScore();
myStudent.setLabScore();
myStudent.setMidterm1Score();
myStudent.setMidterm2Score();
myStudent.setFinalExamScore();
myStudent.setQuizScore();
myStudent.setAttendanceScore();
myStudent.setPATScore();
myStudent.setZyanteScore();
myStudent.computeLetterGrade();
System.out.println(myStudent.getFirstName() + " " + myStudent.getLastName() + " " + myStudent.computeTotalHomeworkScore() + " " + myStudent.computeTotalTestScore() + " " + myStudent.getLetterGrade());
}
System.out.println(myCourse.getNumberOfSemesters());
}
}
Output is...
Anthony Hopkins 854 284 P
John Smith 730 214 G
Pan Mei 730 267 A
Rafael Vega 801 236 A
3
The data object in the .txt file is 3, and even though the myCourse.setNumberOfSemesters() isn't the first thing to scan, it still scans to that first data of 3. How do i get the two scanning classes to mix, meaning one continues off where the other left off.
You have some logic issues in your code.
In your Student class, you are opening the file to scan again. Try changing the setScanner method to:
public void setScanner(Scanner scanner){
this.scanner = scanner;
}
And at your main:
myStudent.setScanner(scanner);
1)You really should be more specific what, where, nobody wants to study so much code.
2)You should think about your OOP approach
OOP TIP NO.1
If you have a lot values which has similar meaning for its object, try to store them in some array/list, so you dont have to rewrite the class when new value appears (like midter3).
For example this :
private int assignmentScore;
private int labScore;
private int quizScore;
private int attendanceScore;
private int homeworkScore;
private int midterm1Score;
private int midterm2Score;
private int finalExamScore;
private int zyanteScore;
private int patScore;
private int testScore;
Would be better as
private Map<String, Integer> exams = new HashMap<>();
Then you can access it as this :
exams.get("midterm1")

Categories

Resources