Java program grading - java

I've been working on this program for hours and I can't figure out how to get the program to actually print the grades from the scores Text file
public class Assign7{
private double finalScore;
private double private_quiz1;
private double private_quiz2;
private double private_midTerm;
private double private_final;
private final char grade;
public Assign7(double finalScore){
private_quiz1 = 1.25;
private_quiz2 = 1.25;
private_midTerm = 0.25;
private_final = 0.50;
if (finalScore >= 90) {
grade = 'A';
} else if (finalScore >= 80) {
grade = 'B';
} else if (finalScore >= 70) {
grade = 'C';
} else if (finalScore>= 60) {
grade = 'D';
} else {
grade = 'F';
}
}
public String toString(){
return finalScore+":"+private_quiz1+":"+private_quiz2+":"+private_midTerm+":"+private_final;
}
}
this code compiles as well as this one
import java.util.*;
import java.io.*;
public class Assign7Test{
public static void main(String[] args)throws Exception{
int q1,q2;
int m = 0;
int f = 0;
int Record ;
String name;
Scanner myIn = new Scanner( new File("scores.txt") );
System.out.println( myIn.nextLine() +" avg "+"letter");
while( myIn.hasNext() ){
name = myIn.next();
q1 = myIn.nextInt();
q2 = myIn.nextInt();
m = myIn.nextInt();
f = myIn.nextInt();
Record myR = new Record( name, q1,q2,m,f);
System.out.println(myR);
}
}
public static class Record {
public Record() {
}
public Record(String name, int q1, int q2, int m, int f)
{
}
}
}
once a compile the code i get this which dosent exactly compute the numbers I have in the scores.txt
Name quiz1 quiz2 midterm final avg letter
Assign7Test$Record#4bcc946b
Assign7Test$Record#642423
Exception in thread "main" java.until.InputMismatchException
at java.until.Scanner.throwFor(Unknown Source)
at java.until.Scanner.next(Unknown Source)
at java.until.Scanner.nextInt(Unknown Source)
at java.until.Scanner.nextInt(Unknown Source)
at Assign7Test.main(Assign7Test.java:25)

Exception aside, you actually are printing objects of type Record. What you would need to do is override toString() to provide a decent representation of your object.
#Override
public String toString() {
return "Something meaningful about your Record object.";
}
I also note that you're advancing the Scanner by use of nextLine() in System.out.println('...'). You may want to comment that part out of your code.

The reason you are getting this error is because of the fact that you are expecting an integer, but the next thing your scanner reads is not a number.
Also, put this in your toString of your record to stop printing out addresses.
i.e.
public static class Record {
public Record() {
}
public Record(String name, int q1, int q2, int m, int f)
{
}
public String toString(){}//print out stuff here.
}

change your Record to something like this
public static class Record {
String name;
int q1;
int q2;
int m;
int f;
public Record() {}
public Record(String name, int q1, int q2, int m, int f) {
// here you save the given arguments localy in the Record.
this.name = name;
this.q1 = q1;
this.q2 = q2;
this.m = m;
this.f = f;
}
#Override
public String toString(){
//here you write out the localy saves variables.
//this function is called when you write System.out.println(myRecordInstance);
System.out.println(name + ":" + q1 + ":" + q2 + ":" + m + ":" + f);
}
}
What it does: you have to save the argments by creating the Record.
Additional you have to override the toString method if you want to use System.out.println(myRecordInstance); instead you could write an other function returning a String in your Record and print out the return values of this function like System.out.println(myRecordInstace.writeMe()); Then you ne to add the function to the record.
public String writeMe(){
System.out.println(name + ":" + q1 + ":" + q2 + ":" + m + ":" + f);
}

Related

Parsing correct type value to a list in Java

First of all, I apologize because I am not sure I even know how to phrase my problem exactly. We have just started Object oriented programming in Uni and I'm having trouble with grasping the concept.
So the goal is to work get data from a .csv file. ( Periodic table )
The problem is that in the original file some fields are just empty. I am aware of the problem ( at least I think so) : The fileReader saves them as empty strings in to the array, and they get parsed in to my array list as a strings, while a type Double is expected. But I just don't know what to do.
: java.lang.NumberFormatException: empty String
at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1842)
at java.base/jdk.internal.math.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.base/java.lang.Double.parseDouble(Double.java:549)
at ChemicalElement.DAO.<clinit>(DAO.java:28)
I'm posting all the code I have in case there's something else wrong that I'm not aware of. All criticism (or advice) is welcome!
public class ChemicalElement {
private String element;
private int number;
private String symbol;
private double weight;
private double boil;
private double melt;
private double density;
private double vapour;
private double fusion;
public ChemicalElement()
{
}
public String GetElement()
{
return this.element;
}
public int GetNumber()
{
return this.number;
}
public String GetSymbol()
{
return this.symbol;
}
public double GetWeight()
{
return this.weight;
}
public double GetBoil()
{
return this.boil;
}
public double GetMelt()
{
return this.melt;
}
public double GetDensity()
{
return this.density;
}
public double GetVapour()
{
return this.vapour;
}
public double GetFusion()
{
return this.fusion;
}
public void SetElement(String element)
{
this.element = element;
}
public void SetNumber(int number)
{
this.number = number;
}
public void SetSymbol(String symbol)
{
this.symbol = symbol;
}
public void SetWeight(double weight)
{
this.weight = weight;
}
public void SetBoil(double boil)
{
this.boil = boil;
}
public void SetMelt(int melt)
{
this.melt = melt;
}
public void SetDensity(int density)
{
this.density = density;
}
public void SetVapour(double vapour)
{
this.vapour = vapour;
}
public void SetFusion(double fusion)
{
this.fusion = fusion;
}
public ChemicalElement(String element ,int number,String symbol, double weight, double boil,double melt , double density, double vapour, double fusion)
{
this.element = element;
this.number = number;
this.symbol = symbol;
this.weight = weight;
this.boil = boil;
this.melt = melt;
this.density = density;
this.vapour = vapour;
this.fusion = fusion;
}
public ChemicalElement(String element ,int number,String symbol, double weight, double boil,double melt , double density, double vapour)
{
this.element = element;
this.number = number;
this.symbol = symbol;
this.weight = weight;
this.boil = boil;
this.melt = melt;
this.density = density;
this.vapour = vapour;
}
public ChemicalElement(String element ,int number,String symbol, double weight)
{
this.element = element;
this.number = number;
this.symbol = symbol;
this.weight = weight;
}
#Override
public String toString()
{
return "Element{" + element + ", number= " + number + ", symbol= " + symbol + ", weight= " + weight + ", boil=" + ", melt= " + melt + "densitiy= " + density + ", vapour= " + vapour + "fusion= " + fusion + '}';
}
}
public class DAO {
public static List<ChemicalElement> elements = new ArrayList<>();
static {
try
{
Scanner scan = new Scanner(new FileReader("elements2.csv"));
String firstLine = scan.nextLine(); //skip first line ( title )
while(scan.hasNext())
{
String readFile[] = scan.nextLine().split(",");
if(readFile.length == 4)
{
ChemicalElement El = new ChemicalElement(readFile[0],Integer.parseInt(readFile[1]),readFile[2],Double.parseDouble(readFile[3]));
elements.add(El);
}
else if(readFile.length == 8)
{
//first exception is down below
ChemicalElement El = new ChemicalElement(readFile[0],Integer.parseInt(readFile[1]),readFile[2],Double.parseDouble(readFile[3]),Double.parseDouble(readFile[4]),Double.parseDouble(readFile[5]),Double.parseDouble(readFile[6]),Double.parseDouble(readFile[7]));
}
else
{
for(int i = 0; i < readFile[i].length(); i++)
{
if(readFile[i].equals(""))
{
readFile[i].replace("","0"); // what to do here ?
}
}
}
}
}
catch (FileNotFoundException ex)
{
System.out.println(ex.getMessage());
}
}
public static void PeriodicTable() {
for (ChemicalElement element : elements) {
System.out.println(element);
}
}
}
public class Main {
public static void main(String[] args) {
DAO.PeriodicTable(); // Just trying to at least print all elements on the list
}
}
EDIT! Adding my .csv file as requested: Not sure about the version of Java,but my IDE is IntelliJ
What's happening is as I can see is, the CSV file probably has a column for 'weight' of the element. But value for this column must be empty in at least one of the rows. So when it tries to parse the string value for the weight (or any other double field) it's throwing a numberFormatException. To correct this see if the CSV file adheres to the constraints you enforce on code OR do a round of validation for each row and set the correct default values
Basically your code has to handle all the unexpected cases including, for example, missing values or invalid values. Parsing a CSV file is not as simple as it at first seems. That is why there are utilities for parsing CSV files such as opencsv
Refer to my last comment to your question. I assume that you are using a comma as the delimiter and I also assumed that the delimiter in the image in your question is a tab and so I changed the tab characters in file elements2.csv to commas.
Also, I only took a few lines from the file including the following.
Element,Number,Symbol,Weight,Boil,Melt,Density,Vapour,Fusion
Hydrogen,1,H,1.01,20.46,13.96,71,0.45,0.06
Carbon,6,C,12.01,5103.16,4000.16,2260,719.01
Phosphorus,15,P,30.98
Gallium,31,Ga,69.72,2510.16,302.96,5910,,5.61
Niobium,41,Nb,92.91,3573.16,2741.16,8400,,26.8
Hydrogen has values for all the fields.
Carbon does not have a value for Fusion
Phosphorus only has the first four values.
Gallium is missing the value for Vapour (as is Niobium)
First I just checked how many fields are in each line using the following code.
try (Scanner scan = new Scanner(new FileReader("elements2.csv"))) {
scan.nextLine(); // skip first line
int counter = 0;
while (scan.hasNextLine()) {
String line = scan.nextLine();
counter++;
String[] readFile = line.split(",");
System.out.printf("%d. [%d] ^%s^%n", counter, readFile.length, line);
}
}
catch (IOException xIo) {
throw new ExceptionInInitializerError(xIo);
}
Note that the code uses try-with-resources that was added in Java 7.
The above code produced the following output for my "sample" file.
(I use ^ to help me see if there is any leading or trailing whitespace in the string or if it is an empty string.)
1. [9] ^Hydrogen,1,H,1.01,20.46,13.96,71,0.45,0.06^
2. [8] ^Carbon,6,C,12.01,5103.16,4000.16,2260,719.01^
3. [4] ^Phosphorus,15,P,30.98^
4. [9] ^Gallium,31,Ga,69.72,2510.16,302.96,5910,,5.61^
5. [9] ^Niobium,41,Nb,92.91,3573.16,2741.16,8400,,26.8^
So now that I have an idea of what to expect, I can write the code (for class DAO) to read and parse the CSV file. The code includes handling unexpected values.
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class DAO {
private static final int ELEMENT = 0;
private static final int NUMBER = 1;
private static final int SYMBOL = 2;
private static final int WEIGHT = 3;
private static final int BOIL = 4;
private static final int MELT = 5;
private static final int DENSITY = 6;
private static final int VAPOUR = 7;
private static final int FUSION = 8;
public static List<ChemicalElement> elements = new ArrayList<>();
static {
try (Scanner scan = new Scanner(new FileReader("elements2.csv"))) {
scan.nextLine(); // skip first line
String element;
int number;
String symbol;
double weight;
double boil;
double melt;
double density;
double vapour;
double fusion;
while (scan.hasNextLine()) {
String line = scan.nextLine();
String[] readFile = line.split(",");
if (readFile.length > ELEMENT &&
readFile[ELEMENT] != null &&
!readFile[ELEMENT].isEmpty()) {
element = readFile[ELEMENT];
}
else {
element = ""; // value to use when the CSV file does not contain a value
}
if (readFile.length > NUMBER &&
readFile[NUMBER] != null &&
!readFile[NUMBER].isEmpty()) {
try {
number = Integer.parseInt(readFile[NUMBER]);
}
catch (NumberFormatException xNumberFormat) {
number = 0; // value to use if value in CSV file is missing or invalid
}
}
else {
number = 0;
}
if (readFile.length > SYMBOL &&
readFile[SYMBOL] != null &&
!readFile[SYMBOL].isEmpty()) {
symbol = readFile[SYMBOL];
}
else {
symbol = "";
}
if (readFile.length > WEIGHT) {
weight = extractDoubleValue(readFile[WEIGHT], 0.0d);
}
else {
weight = 0.0d;
}
if (readFile.length > BOIL) {
boil = extractDoubleValue(readFile[BOIL], 0.0d);
}
else {
boil = 0.0d;
}
if (readFile.length > MELT) {
melt = extractDoubleValue(readFile[MELT], 0.0d);
}
else {
melt = 0.0d;
}
if (readFile.length > DENSITY) {
density = extractDoubleValue(readFile[DENSITY], 0.0d);
}
else {
density = 0.0d;
}
if (readFile.length > VAPOUR) {
vapour = extractDoubleValue(readFile[VAPOUR], 0.0d);
}
else {
vapour = 0.0d;
}
if (readFile.length > FUSION) {
fusion = extractDoubleValue(readFile[FUSION], 0.0d);
}
else {
fusion = 0.0d;
}
ChemicalElement elem = new ChemicalElement(element,
number,
symbol,
weight,
boil,
melt,
density,
vapour,
fusion);
elements.add(elem);
}
}
catch (IOException xIo) {
throw new ExceptionInInitializerError(xIo);
}
}
public static void periodicTable() {
for (ChemicalElement element : elements) {
System.out.println(element);
}
}
private static double extractDoubleValue(String raw, double defaultValue) {
double value;
try {
value = Double.parseDouble(raw);
}
catch (NullPointerException | NumberFormatException x) {
value = defaultValue;
}
return value;
}
}

I keep getting "Battle.java:11: error: illegal start of expression" Heelp

I'm trying to have two monsters fight and return a monster winner. And I attempterd to include a while loop in which monsters hit each other
public class Bat{
public static void main (String [] args){
monster s1 = new monster ["cat"];
monster s2 = new monster ["dog"];
s1.Strength = 10;
s2.Strenght = 98;
}
public fight(monster m1, monster m2){
int m1 = s1;
int m2 = s2;
int attack = s1;
int attack2 = s2;
if (m1 >= m2)
return m1;
else if(m2 >= m1)
return m2;
while ( m1 > m2 || m2 > m1) {
s1.Damn(attack2);
s2.Damn(attack);
}
}
}
One of your problems is, that you give your function "fightToDeath" two objects of type "monster". That is ok so far.
But here it gets very wrong:
int m1 = s1;
You assigend a monster-object (that has been declared globally and is not the argument) to an integer. I don't know what you are trying to achieve but this might be correct for you:
int m1Strength = m1.getStrength();
int m2Strength = m2.getStrength();
In your code your arguments in "fightToDeath" would be instantly overwritten. The way I wrote it, you would use your monsters you gave as an argument and get their strength and assign this strength to a local integer.
EDIT:
See this code:
public class Battle{
public static void main (String [] args){
Monster s1 = new Monster("Demorgogon", 10);
Monster s2 = new Monster("Godzilla", 98);
fightToDeath(s1, s2);
}
public static void fightToDeath(Monster m1, Monster m2){
int m1Strength = m1.getStrength();
int m2Strength = m2.getStrength();
int attack = 5;
int attack2 = 2;
while (m1Strength > 0 && m2Strength > 0) {
m1.oof(attack2);
m1Strength -= attack2;
m2.oof(attack);
m2Strength -= attack;
}
if(m1.getStrength() == 0){
System.out.println("Winner is: " + m2.getName() + " with " +
m2.getStrength() + " live left!");
} else {
System.out.println("Winner is: " + m1.getName() + " with " +
m1.getStrength() + " live left!");
}
}
}
public class Monster{
int strength;
String name;
public Monster(String name, int strength){
this.name = name;
this.strength = strength;
}
public void setStrength(int newStrength){
this.strength = newStrength;
}
public int getStrength(){
return this.strength;
}
public void setName(String newName) {
this.name = newName;
}
public String getName(){
return this.name;
}
public void oof(int attackValue){
this.strength -= attackValue;
}
}
You are missing a brace closing the main method as well as around the if/else blocks.

DemoSalesPerson2.java:15: error: constructor SalesPerson in class SalesPerson cannot be applied to given types;

Whenever I compile my code, I receive the following errors:
constructor SalesPerson in class SalesPerson cannot be applied to
given types; error: constructor Player in class Player cannot be
applied to given types;
But it doesn't list any types. The code in question is
Modify the DemoSalesperson application so each Salesperson has a successive ID number from 111 through 120 and a sales value that ranges from $25,000 to $70,000, increasing by $5,000 for each successive Salesperson. Save the file as DemoSalesperson2.java.*/
SalesPerson class:
public class SalesPerson {
// Data fields for Salesperson include an integer ID number and a double annual sales amount
private int idNumber;
private double salesAmount;
//Methods include a constructor that requires values for both data fields, as well as get and set methods for each of the data fields.
public SalesPerson(int idNum, double salesAmt) {
idNumber = idNum;
salesAmount = salesAmt;
}
public int getIdNumber() {
return idNumber;
}
public void setIdNumber(int idNum) {
idNumber = idNum;
}
public double getSalesAmount() {
return salesAmount;
}
public void setSalesAmount(double salesAmt) {
salesAmount = salesAmt;
}
}
Driver:
public class DemoSalesPerson2 {
public static void main(String[] args) {
SalesPerson s1 = new SalesPerson(111, 0);
final int NUM_PERSON = 10;
SalesPerson[] num = new SalesPerson[NUM_PERSON];
for (int x = 1; x < num.length; x++) {
// NUM_PERSON
num[x] = new SalesPerson((111 + x + "|" + 25000 + 5000 * (x)));
System.out.println(x + " " + s1.getIdNumber() + " " + s1.getSalesAmount());
}
}
}
Change this: num[x] = new SalesPerson((111 + x + "|" + 25000 + 5000 * (x)));
to this: num[x] = new SalesPerson((111 + x), (25000 + 5000 * (x)));
You had it right here SalesPerson s1 = new SalesPerson(111, 0);.
Notice the difference between the two constructor calls.
As Sssss pointed out, you're handing in a String as the constructor param when your method requires two ints.
Code jotted down here, haven't tested it. Should get you pointed in the right direction however.
public class DemoSalesPerson2
{
public static void main(String[] args)
{
SalesPerson[] num = new SalesPerson[10];
final int START_NUM =111;
final double START_SALARY=25_000;
for (int x =0; x<num.length; x++) {
num[x] =new SalesPerson(START_NUM+x,START_SALARY+5000*(x));
System.out.println(num[x].getIdNumber()+" "+num[x].getSalesAmount() );
}
}}
try this!!

(Another) "non-static method cannot be referenced from a static context" issue

ERROR: non-static method cannot be referenced from a static context.
In my case the method is called readFile().
Hi. I'm experiencing the same error that countless novice programmers have before, but despite reading about it for hours on end, I can't work out how to apply that knowledge in my situation.
I think the code may need to be restructured so I am including the full text of the class.
I would prefer to house the main() method in small Main class, but have placed it in the same class here for simplicity. I get the same error no matter where I put it.
The readFile() method could easily be placed within the main() method, but I’d prefer to learn how to create small modular methods like this and call them from a main() method.
Originally closeFile() was a separate method too.
The program is supposed to:
open a .dat file
read in from the file data regarding examination results
perform calculations on the information
output the results of the calculations
Each line of the file is information about an individual student.
A single consists of three examination papers.
Most calculations regard individual students.
But some calculations regard the entire collection of students (ie their class).
NB: where the word “class” is used in the code, it refers to academic class of the students, not class in the sense of OO programming.
I have tried various ways to solve problem.
Current approach is to house data concerning a single student examination in an instance of the class “Exam”.
This corresponds to a single line of the input file, plus subsequent calculations concerning other attributes of that instance only.
These attributes are populated with values during the while loop of readFile().
When the while loop ends, the three calculations that concern the entire collection of Exams (ie the entire academic class) are called.
A secondary question is:
Under the comment “Declare Attributes”, I’ve separated the attributes of the class into two subgroups:
Those that I think should be defined as class variables (with keyword static).
Those that I think should be defined as instance variables.
Could you guide me on whether I should add keyword static to those in first group.
A related question is:
Should the methods that perform calculations using the entire collection of instances be declared as static / class methods too?
When I tried that I then got similar errors when these tried to call instance methods.
Thanks.
PS: Regarding this forum:
I have enclosed the code with code blocks, but the Java syntax is not highlighted.
Perhaps it will change after I submit the post.
But if not I'd be happy to reformat it if someone can tell me how.
PPS: this is a homework assignment.
I have created all the code below myself.
The "homework" tag is obsolete, so I didn't use it.
Input File Name: "results.dat"
Input File Path: "C:/Users/ADMIN/Desktop/A1P3E1 Files/results.dat"
Input File Contents (randomly generated data):
573,Kalia,Lindsay,2,8,10
966,Cheryl,Sellers,8,5,3
714,Shea,Wells,7,6,2
206,April,Mullins,8,2,1
240,Buffy,Padilla,3,5,2
709,Yoko,Noel,3,2,5
151,Armand,Morgan,10,9,2
199,Kristen,Workman,2,3,6
321,Iona,Maynard,10,2,8
031,Christen,Short,7,5,3
863,Cameron,Decker,6,4,4
986,Kieran,Harvey,7,6,3
768,Oliver,Rowland,8,9,1
273,Clare,Jacobs,9,2,7
556,Chaim,Sparks,4,9,4
651,Paloma,Hurley,9,3,9
212,Desiree,Hendrix,7,9,10
850,McKenzie,Neal,7,5,6
681,Myra,Ramirez,2,6,10
815,Basil,Bright,7,5,10
Java File Name: "Exam.java"
Java Package Name: "a1p3e1"
Java Project Name: "A1P3E1"
Java File Contents:
/** TODO
* [+] Error Block - Add Finally statement
* [?] studentNumber - change data type to integer (or keep as string)
* [?] Change Scope of to Non-Instance Variables to Static (eg classExamGradeSum)
* [*] Solve "non-static method cannot be referenced from a static context" error
*
*/
package a1p3e1; // Assignment 1 - Part 3 - Exercise 1
import java.io.*;
import java.util.*;
/**
*
* #author
*/
public class Exam {
// (1) Declare Attributes
// (-) Class Attributes
protected Scanner fileIn;
protected Scanner lineIn;
private String line;
private String [] splitLine;
private String InFilePath = "C:/Users/ADMIN/Desktop/A1P3E1 Files/results.dat";
private int fileInRowCount = 20;
private int fileInColumnCount = 6;
private int fileOutRowCount = 20;
private int fileOutColumnCount = 14;
// private int classExamGradeSum = 0;
private int classExamGradeSum;
private double classExamGradeAverage = 0.0;
private int [] classExamGradeFrequency = new int [10];
protected Exam exam [] = new Exam [fileInRowCount];
// (-) Instance Attributes
private String studentNumber;
private String forename;
private String surname;
private int paper1Grade;
private int paper2Grade;
private int paper3Grade;
private String paper1Outcome;
private String paper2Outcome;
private String paper3Outcome;
private int fileInRowID;
private int failCount;
private int gradeAverageRounded;
private int gradeAverageQualified;
private String examOutcome;
// (3) toString Method Overridden
#Override
public String toString () {
return "\n Student Number: " + studentNumber
+ "\n Forename: " + forename
+ "\n Surname: " + surname
+ "\n Paper 1 Grade: " + paper1Grade
+ "\n Paper 2 Grade: " + paper2Grade
+ "\n Paper 3 Grade: " + paper3Grade
+ "\n Paper 1 Outcome: " + paper1Outcome
+ "\n Paper 2 Outcome: " + paper2Outcome
+ "\n Paper 3 Outcome: " + paper3Outcome
+ "\n File In Row ID: " + fileInRowID
+ "\n Fail Count: " + failCount
+ "\n Exam Grade Rounded: " + gradeAverageRounded
+ "\n Exam Grade Qualified: " + gradeAverageQualified
+ "\n Exam Outcome: " + examOutcome;
}
// (4) Accessor Methods
public String getStudentNumber () {
return studentNumber;
}
public String getForename () {
return forename;
}
public String getSurname () {
return surname;
}
public int getPaper1Grade () {
return paper1Grade;
}
public int getPaper2Grade () {
return paper2Grade;
}
public int getPaper3Grade () {
return paper3Grade;
}
public String getPaper1Outcome () {
return paper1Outcome;
}
public String getPaper2Outcome () {
return paper2Outcome;
}
public String getPaper3Outcome () {
return paper3Outcome;
}
public int getFileInRowID () {
return fileInRowID;
}
public int getFailCount () {
return failCount;
}
public int getGradeAverageRounded () {
return gradeAverageRounded;
}
public int getGradeAverageQualified () {
return gradeAverageQualified;
}
public String getExamOutcome () {
return examOutcome;
}
// (5) Mutator Methods
public void setStudentNumber (String studentNumber) {
this.studentNumber = studentNumber;
}
public void setForename (String forename) {
this.forename = forename;
}
public void setSurname (String surname) {
this.surname = surname;
}
public void setPaper1Grade (int paper1Grade) {
this.paper1Grade = paper1Grade;
}
public void setPaper2Grade (int paper2Grade) {
this.paper2Grade = paper2Grade;
}
public void setPaper3Grade (int paper3Grade) {
this.paper3Grade = paper3Grade;
}
public void setPaper1Outcome (String paper1Outcome) {
this.paper1Outcome = paper1Outcome;
}
public void setPaper2Outcome (String paper2Outcome) {
this.paper2Outcome = paper2Outcome;
}
public void setPaper3Outcome (String paper3Outcome) {
this.paper3Outcome = paper3Outcome;
}
public void setFileInRowID (int fileInRowID) {
this.fileInRowID = fileInRowID;
}
public void setFailCount (int failCount) {
this.failCount = failCount;
}
public void setGradeAverageRounded (int gradeAverageRounded) {
this.gradeAverageRounded = gradeAverageRounded;
}
public void setGradeAverageQualified (int gradeAverageQualified) {
this.gradeAverageQualified = gradeAverageQualified;
}
public void setExamOutcome (String examOutcome) {
this.examOutcome = examOutcome;
}
// (2) Constructor Methods
// (-) Constructor Method - No Arguments
public Exam () {
this.studentNumber = "";
this.forename = "";
this.surname = "";
this.paper1Grade = 0;
this.paper2Grade = 0;
this.paper3Grade = 0;
this.paper1Outcome = "";
this.paper2Outcome = "";
this.paper3Outcome = "";
this.fileInRowID = 0;
this.failCount = 0;
this.gradeAverageRounded = 0;
this.gradeAverageQualified = 0;
this.examOutcome = "";
}
// (-) Constructor Method - With Arguments (1)
public Exam (
String studentNumber,
String forename,
String surname,
int paper1Grade,
int paper2Grade,
int paper3Grade,
String paper1Outcome,
String paper2Outcome,
String paper3Outcome,
int fileInRowID,
int failCount,
int gradeAverageRounded,
int gradeAverageQualified,
String examOutcome) {
this.studentNumber = studentNumber;
this.forename = forename;
this.surname = surname;
this.paper1Grade = paper1Grade;
this.paper2Grade = paper2Grade;
this.paper3Grade = paper3Grade;
this.paper1Outcome = paper1Outcome;
this.paper2Outcome = paper2Outcome;
this.paper3Outcome = paper3Outcome;
this.fileInRowID = fileInRowID;
this.failCount = failCount;
this.gradeAverageRounded = gradeAverageRounded;
this.gradeAverageQualified = gradeAverageQualified;
this.examOutcome = examOutcome;
}
// (-) Constructor Method - With Arguments (2)
public Exam (
String studentNumber,
String forename,
String surname,
int paper1Grade,
int paper2Grade,
int paper3Grade) {
this.studentNumber = studentNumber;
this.forename = forename;
this.surname = surname;
this.paper1Grade = paper1Grade;
this.paper2Grade = paper2Grade;
this.paper3Grade = paper3Grade;
this.paper1Outcome = "";
this.paper2Outcome = "";
this.paper3Outcome = "";
this.fileInRowID = 0;
this.failCount = 0;
this.gradeAverageRounded = 0;
this.gradeAverageQualified = 0;
this.examOutcome = "";
}
// (6) Main Method
public static void main (String[] args) throws Exception {
Exam.readFile ();
}
// (7) Other Methods
// (-) Read File Into Instances Of Exam Class
// limitation: hard coded to 6 column source file
public void readFile () throws Exception {
try {
fileIn = new Scanner(new BufferedReader(new FileReader(InFilePath)));
int i = 0;
while (fileIn.hasNextLine ()) {
line = fileIn.nextLine();
splitLine = line.split (",", 6);
// create instances of exam from file data and calculated data
exam [i] = new Exam (
splitLine [0],
splitLine [1],
splitLine [2],
Integer.parseInt (splitLine [3]),
Integer.parseInt (splitLine [4]),
Integer.parseInt (splitLine [5]),
convertGradeToOutcome (paper1Grade),
convertGradeToOutcome (paper2Grade),
convertGradeToOutcome (paper3Grade),
i + 1,
failCount (),
gradeAverageRounded (),
gradeAverageQualified (),
convertGradeToOutcome (gradeAverageQualified));
fileIn.nextLine ();
i ++;
}
classExamGradeFrequency ();
classExamGradeSum ();
classExamGradeAverage ();
// close file
fileIn.close ();
} catch (FileNotFoundException | NumberFormatException e) {
// fileIn.next ();
System.err.println("Error: " + e.getMessage());
//System.out.println ("File Error - IO Exception");
}
for (Exam i : exam) {
System.out.println(i.toString());
System.out.println();
}
// System.out.println(classExamGradeSum);
// System.out.println();
System.out.println(classExamGradeAverage);
System.out.println();
System.out.println(classExamGradeFrequency);
System.out.println();
}
// (-) Fail Count (1 Student, 3 Papers)
public int failCount () {
//
if (paper1Grade > 6){
failCount = failCount + 1;
}
if (paper2Grade > 6){
failCount = failCount + 1;
}
if (paper3Grade > 6){
failCount = failCount + 1;
}
return failCount;
}
// (-) Grade Average Rounded (1 Student, 3 Papers)
public int gradeAverageRounded () {
gradeAverageRounded = (int) Math.ceil(
(paper1Grade + paper2Grade + paper3Grade) / 3);
return gradeAverageRounded;
}
// (-) Grade Average Qualified (1 Student, 3 Papers)
public int gradeAverageQualified (){
gradeAverageQualified = gradeAverageRounded;
if (failCount >= 2 && gradeAverageRounded <= 6) {
gradeAverageQualified = 7;
}
return gradeAverageQualified;
}
// (-) Convert Grade to Outcome (Pass / Fail)
public String convertGradeToOutcome (int grade) {
String outcome;
if (grade <= 6){
outcome = "Pass";
} else if (grade > 6){
outcome = "Fail";
} else {
outcome = "Unknown (Error)";
}
return outcome;
}
// (-) Class Exam Grade Sum (All Students, All Papers)
/** assumption: average grade for class is average of grades awarded,
* using rounded figures, not raw per paper results
*/
public void classExamGradeSum () {
classExamGradeSum = 0;
// for each loop (to iterate through collection of exam instances)
for (Exam i : exam) {
classExamGradeSum = classExamGradeSum + i.gradeAverageQualified;
}
}
// (-) Class Exam Grade Average (All Students, All Papers)
/** assumption: average grade for class is average of grades awarded,
* using rounded figures, not raw per paper results
* assumption: <fileInRowCount> is correct
*/
public double classExamGradeAverage () {
classExamGradeAverage = classExamGradeSum / fileInRowCount;
return classExamGradeAverage;
}
// (-) Class Exam Grade Frequency (Count of Instances of Each Final Grade)
/** Example:
* frequency of average grade "5"
* is stored in array <classExamGradeFrequency [4]>
*/
public void classExamGradeFrequency () {
// for each loop (to iterate through collection of exam instances)
for (Exam i : exam) {
classExamGradeFrequency [i.getGradeAverageQualified () - 1] ++;
}
}
}// endof class
readFile is an instance method. Create an instance of Exam to use:
new Exam().readFile();
Given that the Exam has many instance variables, some of which are used in the readFile method, this method should not be static. (Use of static class variables creates code smell and should not be considered.)
Given that readFile reads multiple entries from the file into many Exam objects, you could split out the read functionality into a new ExamReader class.
Aside: For flexibility use a List instead of a fixed size array
Exam exam [];
could be
List<Exam> examList;

java method error

I have a task to do, which is make a film archive. Here are my tasks:
Besides the main program, create a custom class that stores information about a movie. This class is then used in the main program. The following information should be stored for each film
title
length
grade
format
year
then
In the main program, you should be able to store 1,000 films.
The user should be able to do the following in the program (make a selection menu):
• Enter the information about a movie. Make a method for loading a movie from the user.
• Print the information on all films. Make a method for printing a film and use it.
• Save all your movies to a file. Please do your own method for this.
• Download movies from a file. Please do your own method for this.
The problem is that I got an error with my skrivUtInfo(PrintOut information) method
I create an array list of 1000 films. But how can I print 1000 films?
Here is my code:
public class Film {
String title ;
int length;
int grade ;
String format ;
int year ;
}
import java.util.*;
import java.io.*;
public class Filmarkiv {
static Scanner sc = new Scanner(System.in);
public static void main(String[] arg) {
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Scanner s = new Scanner(inFromUser);
Film[] film = new Film[1000];
int antal = 1;
film[0] = new Film();
film[0].title = "matrix";
film[0].length = 220;
film[0].grade = 5;
film[0].format = "DVD";
film[0].year = 1999;
while(true)
{
int n = 0;
System.out.println("valj 1 for inmata. 2 for utskrift");
String val = s.next();
if(val.equals("1")){
System.out.println("vad heter filmen?");
film[n].title = s.next();
System.out.println("hur lang ar filmen?");
film[n].length = s.nextInt();
System.out.println("vad har den for betyg?");
film[n].grade = s.nextInt();
System.out.println("vad har den for format?");
film[n].format = s.next() ;
System.out.println("i vilket år har filmen inspelat? ");
film[n].year = s.nextInt() ;
}
else if (val.equals("2"))
{
skrivUtInfo(film, antal);
/*System.out.println("title = "+film[n].title) ;
System.out.println("length = "+film[n].length) ;
System.out.println("grade = "+film[n].grade) ;
System.out.println("format = "+film[n].format) ;
System.out.println("year = "+film[n].year);*/
}
}
}
public skrivUtInfo (Film[] qwert, int a) {
for (int n=0; n<a; n++) {
System.out.println("title = "+film[n].title) ;
System.out.println("length = "+film[n].length) ;
System.out.println("grade = "+film[n].grade) ;
System.out.println("format = "+film[n].format) ;
System.out.println("year = "+film[n].year) ;
return Film[];
}
}
}
you have to change the method as
public static void skrivUtInfo (Film[] qwert) {
for (int n=0; n<qwert.length; n++) {
System.out.println("title = "+qwert[n].title) ;
System.out.println("length = "+qwert[n].length) ;
System.out.println("grade = "+qwert[n].grade) ;
System.out.println("format = "+qwert[n].format) ;
System.out.println("year = "+qwert[n].year) ;
}
}
also put a bracket here
else if (val.equals("2"))
{
skrivUtInfo(film);
// the comments
}
} //<- you must add this bracket. is from while (i think)
also a tip, in Film class you can override the toString method from class Object
public class Film{
String title ;
int length;
int grade ;
String format ;
int year ;
public String toString() {
return "title = " + title +
"length = " + length +
"grade = " + grade +
"format = " + format +
"year = " + year;
}
}
so the skrivUtInfo becomes
public static void skrivUtInfo (Film[] qwert) {
for (int n=0; n<qwert.length; n++) {
System.out.println(qwert[n]);
}
}
or
public static void skrivUtInfo (Film[] qwert) {
for (Film f : qwert) {
System.out.println(f);
}
}
If you've learned about java.util.List, you can do it this way:
List<Film> films = new ArrayList<Film>();
films.add(new Film("Amadeus", 120, 5, "DVD", 1984); ); // Add as many as you like
System.out.println(films); // Make sure your Film class overrides toString()
If you haven't, just do it in a loop:
Film [] films = new Film[1000];
films[0] = new Film("Amadeus", 120, 5, "DVD", 1984);
for (Film film : films) {
System.out.println(film); // Make sure you File class overrides toString()
}
You're probably having problems because your Film class is flawed. Do it this way:
public class Film {
private final String title ;
private final int length;
private final int grade ;
private final String format ;
private final int year ;
public Film(String title, int length, int grade, String format, int year) {
this.title = title;
this.length = length;
this.grade = grade;
this.format = format;
this.year = year;
}
public String getTitle() {
return title;
}
public int getLength() {
return length;
}
public int getGrade() {
return grade;
}
public String getFormat() {
return format;
}
public int getYear() {
return year;
}
#Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("Film");
sb.append("{title='").append(title).append('\'');
sb.append(", length=").append(length);
sb.append(", grade=").append(grade);
sb.append(", format='").append(format).append('\'');
sb.append(", year=").append(year);
sb.append('}');
return sb.toString();
}
}
The method public skrivUtInfo (Film[] qwert, int a) has no return type specified. In java either it should have a void or a valid type as return, but i see you returning Film[]. You cannot do that way. You have to declare like
public Film[] skrivUtInfo (Film[] qwert, int a){
....
return qwert;
}
Ultimately since you are just printing the stuff here you don't need to return anything. In that case you should have
public void skrivUtInfo (Film[] qwert, int a){
.....
return;
}
You can have an empty return or no return specified in a method which has a void return type.
I have test this code and works fine. I change a few parts as i thought it should play
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Filmarkiv {
static Scanner sc = new Scanner(System.in);
public static void main(String[] arg) {
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Scanner s = new Scanner(inFromUser);
Film[] film = new Film[1000];
int n = 0;
do {
System.out.println("valj 1 for inmata. 2 for utskrift");
String val = s.next();
if (val.equals("1")) {
film[n] = new Film();
System.out.println("vad heter filmen?");
film[n].title = s.next();
System.out.println("hur lang ar filmen?");
film[n].length = s.nextInt();
System.out.println("vad har den for betyg?");
film[n].grade = s.nextInt();
System.out.println("vad har den for format?");
film[n].format = s.next();
System.out.println("i vilket år har filmen inspelat? ");
film[n].year = s.nextInt();
n++;
} else if (val.equals("2")) {
skrivUtInfo(film);
}
} while(n < film.length);
}
public static void skrivUtInfo (Film[] qwert) {
for (Film f : qwert) {
if (f != null)
System.out.println(f);
}
}
}
class Film {
String title;
int length;
int grade;
String format;
int year;
public String toString() {
return "title = " + title + ", length = " + length + ", grade = " + grade
+ ", format = " + format + ", year = " + year;
}
}

Categories