Java - Cannot display user input data as an output table using classes - java

UPDATE - Thanks for the suggestions. At least now my program runs without major errors.
When items stored reaches 3 sets of data, program terminates and displays output table. However, only the titles are displayed and wondering how I would fetch the user input data of each element, and display under each column column heading stored within ChessList.java but going through ChessMain.java (As like the table headings stored within ChessList.java)
Any suggestions. Thanks
ChessMain.java
import java.util.Scanner;
public class ChessMain {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ChessList listOfNumbers = new ChessList("");
boolean finished = false;
for(int i = 0; i <2; i++) {
System.out.print("Enter piece number: \t ");
int pieceNum = input.nextInt();
System.out.print("Enter row number for piece " + pieceNum + ": \t ");
int rowNum = input.nextInt();
input.nextLine();
System.out.print("Enter a column number for piece " + pieceNum + ": \t ");
int columnNum = input.nextInt();
input.nextLine();
}
System.out.println(listOfNumbers);
listOfNumbers.printTable();
}
}
Chess.java
public class Chess {
private int pieceNum;
private int rowNum;
private int columnNum;
// piece
public int getpieceNum(){
return pieceNum;
}
public void setpieceNum(int piece){
pieceNum = piece;
}
// row
public int getrowNum(){
return rowNum;
}
public void setrowNum(int row){
rowNum = row;
}
// column
public int getcolumnNum(){
return columnNum;
}
public void setcolumnNum(int column){
columnNum = column;
}
public String toString(){
return "Piece " + pieceNum + " Row " + rowNum + " Column " + columnNum;
}
}
ChessList.java
import java.util.ArrayList;
public class ChessList {
private ArrayList<Chess> chessList = new ArrayList<>();
private String listName;
public ChessList(String name) {
this.listName = name;
}
/*
public void addChess(int piece, int row, int column){
Chess newPiece = new Chess(piece, row, column);
chessList.add(newPiece);
}
*/
public String toString(){
String valueString = "\nThe chessboard holds the follwing assets:\n";
for(Chess elem : chessList){
valueString += elem + " \n";
}
return valueString;
}
public void printTable(){
System.out.println("Piece\tRow\tColumn");
**// BELOW CODE DOES NOT DISPLAY USER INPUT DATA AS AN OUTPUT OF EACH PIECE, ROW, COLUMN**
for(Chess elem : chessList){
System.out.println(elem.getname() + "\t" + elem.getrowNum() + "\t" + elem.getcolumnNum() + "\n");
}
}
}

ChessList listOfNumbers = new ChessList("Chessboard");
needs to be changed to
ChessList listOfNumbers = new ChessList();
since ChessList does not have a constructor that takes a String parameter.
OR you could implement a constructor that saves a String:
public class ChessList {
private ArrayList<Chess> chessList = new ArrayList<>();
private String listName; // Type changed to String!
public ChessList(String name) {
this.listName = name;
}
// Your other mothods here ...
}

Your object ChessList doesn't have a constructor. In Java it sets up a default constructor that takes no parameters. Which is what you are trying to use but you are passing it a String.
Should be this:
ChessList listOfNumbers = new ChessList();
If you want to pass a String to the constructor to set a name for the ChessList then you need to create a constructor in your ChessList class that accepts a String.

Related

How to fix a loop for a heap structure

The code compiles but when you run it an error message occurs that gives a null pointer exception. As SEEN in the bottom. the code is supposed to read text from a txt file that is inputted in the program and then create a new txt file with the content of the first txt file sorted by years of service. However, i keep receiving that error message. Any help would be greatly appreciated. I added the error message at the bottom thank you to everyone who is helping your time and effort is greatly appreciated :)
(25 points)Define a Java class called Employee. The class has data members
and accompanying accessor and mutator methods for each of the following six data items. (This involves creating the file Employee.java.)
id (string)
name (string)
salary (double)
department (string)
position (string)
years of service (integer)
(25 points)Create a text (data) file containing data for at least five different
employees (objects). Let each data item sit on its own line in
the text file. For example, the first six lines of the file might look like:
086244
Sally L. Smith
100000.00
Accounting
Manager
7
(50 points)‘Heap’ is a tree-based data-structure that satisfies the heap property. A max-heap is a complete binary tree in which the value in each internal node is greater than or equal to the values in the children of that node.
By having a heap (or an array that satisfies the heap property), it would be more efficient (generally faster) to perform important tasks on the array such as finding the maximum element in the array (and removing it) and sorting the array.
In this assignment, you will have to write a program that reads a list of employees from a file. The name of the file will be ‘Employee.txt’. The program should output the sorted array to a file called “SortedEmployee.txt”
Heapsort code:
public class HeapSort
{
//heap sort method
public static <Employee extends Comparable<Employee>> void heapSort(Employee[] list)
{
//create a Heap of integers
Heap<Employee> heap = new Heap<>();
//add elements to the heap
for (int i = 0; i< list.length; i++)
heap.add(list[i]);
//remove elements from the heap
for(int i = list.length - 1; i >= 0; i--)
list[i] = heap.remove();
}
}
Heap code:
import java.util.ArrayList;
public class Heap<Employee extends Comparable<Employee>>
{
private ArrayList<Employee> list = new ArrayList<>();
public Heap(){}
public Heap(Employee[] objects)
{
for(int i = 0; i < objects.length; i++)
add(objects[i]);
}
public void add(Employee newObject)
{
list.add(newObject);
int currentIndex = list.size() - 1;
while(currentIndex > 0)
{
int parentIndex = (currentIndex -1)/2;
if(list.get(currentIndex).compareTo(list.get(parentIndex)) > 0)
{
Employee temp = list.get(currentIndex);
list.set(currentIndex, list.get(parentIndex));
list.set(parentIndex, temp);
}
else
break;
currentIndex = parentIndex;
}
}
public Employee remove()
{
if(list.size() == 0) return null;
Employee removeObject = list.get(0);
list.set(0, list.get(list.size() -1));
list.remove(list.size() -1);
int currentIndex = 0;
while(currentIndex < list.size())
{
int leftChildIndex = 2 * currentIndex + 1;
int rightChildIndex = 2 * currentIndex + 2;
if(leftChildIndex >= list.size()) break;
int maxIndex = leftChildIndex;
if(rightChildIndex < list.size())
{
if(list.get(maxIndex).compareTo(list.get(rightChildIndex)) < 0)
maxIndex = rightChildIndex;
}
if(list.get(currentIndex).compareTo(list.get(maxIndex)) < 0)
{
Employee temp = list.get(maxIndex);
list.set(maxIndex, list.get(currentIndex));
list.set(currentIndex, temp);
currentIndex = maxIndex;
}
else
break;
}
return removeObject;
}
public int getSize()
{
return list.size();
}
public void print()
{
for (int i = 0; i <= getSize()-1; i++)
{
System.out.print("Index: " + i + " Data: " + list.get(i));
System.out.println();
}
}
}
Employee Object Class:
public class Employee implements Comparable<Employee>
{
private String id;
private String name;
private double salary;
private String department;
private String position;
private int yos;
public Employee(String id, String name, double salary,String department,String position,int yos)
{
this.id = id;
this.name = name;
this.salary = salary;
this.department = department;
this.position = position;
this.yos = yos;
}
public void setid(String id)
{
this.id = id;
}
public void setname(String name)
{
this.name = name;
}
public void setsalary(double salary)
{
this.salary = salary;
}
public void setdepartment(String department)
{
this.department = department;
}
public void setposition(String position)
{
this.position = position;
}
public void setyos(int yos)
{
this.yos = yos;
}
public String getid()
{
return id;
}
public String getname()
{
return name;
}
public double getsalary()
{
return salary;
}
public String getdepartment()
{
return department;
}
public String getposition()
{
return position;
}
public int getyos()
{
return yos;
}
public int compareTo(Employee emp)
{
return (this.yos - emp.yos);
}
public String toString()
{
return "ID=" + this.id+ ", name=" + this.name+ ", salary= $" + this.salary+ ", department:" + this.department+ ", postion:" + this.position+ ",yos= $" + this.yos + "]\n";
}
}
Demo code:
import java.util.*;
import java.io.*;
public class EmployeeDemo
{
public static void main(String[] args)throws IOException
{
Employee[] list = new Employee[5];
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the text file: ");
String fileName = keyboard.nextLine();
File myFile = new File(fileName);
Scanner inputFile = new Scanner(myFile);
//Read all of the values from the file
//and calculate their total
//Read a value from the file
String id = inputFile.nextLine();
String name = inputFile.nextLine();
double salary = inputFile.nextDouble();
String clear = inputFile.nextLine();
String department = inputFile.nextLine();
String position = inputFile.nextLine();
int yrService = inputFile.nextInt();
String llear = inputFile.nextLine();
list[0] = new Employee(id,name,salary,department,position,yrService);
//close the file
// File o = new File("SortedEmployee.txt");
//o.createNewFile();
System.out.println("Enter the file name to be transfered to: ");
String filename = keyboard.nextLine();
PrintWriter outputFile = new PrintWriter(filename);//dont need the top
//HeapSort<Employee> h = new heapSort<Employee>(Employee);
HeapSort.heapSort(list);
//Display the sum of the numbers
while(inputFile.hasNext())//this loop is wrong too
{
outputFile.println(list[0].toString());
}
outputFile.close();
inputFile.close();
System.out.print("File Sorted and Transferred");
}
}
here is the error message i am receiving:
Please enter the text file:
C:\Users\jose385\Desktop\Employee.txt
Enter the file name to be transfered to:
green
Exception in thread "main" java.lang.NullPointerException
at Heap.add(Heap.java:22)
at HeapSort.heapSort(HeapSort.java:13)
at EmployeeDemo.main(EmployeeDemo.java:50)
----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.
You make the List have a size of 5
Employee[] list = new Employee[5];
but only add one element
list[0] = new Employee(id,name,salary,department,position,yrService);
Actually what is the point of only sorting one element
Also try to follow a tutorial on the correct way to implement Comparable

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!!

How do I implement the toString() method for an ArrayStack?

I want to display a list of orders of type ArrayQueue <Order>
The class Order has an ArrayStack<String> as one of its attributes. I overrode the toString() method in the class Order, but how do I override it in the ArrayStack class? Because this is the output I get when I display:
OrderNumber Name Date ArrayStack#481adc30
What would I have to do to display the Strings in ArrayStack correctly? Do I make changes to class ArrayStack or change something in my Display method?
This is my Display method:
public void display(){
if (!isEmpty())
for (int i = 0; i < numberOfEntries; i++) {
System.out.println(queue[(frontIndex + i) % queue.length]);
}
else System.out.println("You don't have any orders");
}
ArrayStack Class:
public class ArrayStack < T > implements StackInterface < T >
{
private T [] stack; // array of stack entries
private int topIndex; // index of top entry
private static final int DEFAULT_INITIAL_CAPACITY = 50;
public ArrayStack ()
{
this (DEFAULT_INITIAL_CAPACITY);
} // end default constructor
public ArrayStack (int initialCapacity)
{
// the cast is safe because the new array contains null entries
# SuppressWarnings ("unchecked")
T [] tempStack = (T []) new Object [initialCapacity];
stack = tempStack;
topIndex = -1;
} // end constructor
/* Implementations of the stack operations */
Order Class:
import java.util.Date;
public class Order {
int orderNumber;
String customerName;
Date date;
StackInterface <String> items;
Order( int number, String name, Date datum, StackInterface<String> item){
orderNumber = number;
customerName= name;
date= datum;
items = item;
}
/Overriding toString() to Display a list of Orders as one String line.
public String toString(){
return orderNumber + " " + customerName + " " + date + " " + items;
}
You can override toString() method in ArrayStack as shown here. This will solve your problem.
public String toString() {
String result = "";
for (int scan = 0; scan < top; scan++)
result = result + stack[scan].toString() + "\n";
return result;
}
May be you should do this:
System.out.println(Arrays.toString(queue.toArray()));
Use this:
System.out.println(Arrays.toString(queue));

(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