I have this assignment that I need use a static method to get student IDs then within that static method evaluate them if the students have passed or failed their classes. It is a bit challenging for me because the static method should only take one argument.
Can this be accomplished by not changing private variables to private static variables?
Any direction is much appreciated.
import java.util.ArrayList;
public class Grade {
public static void main(String[] args) {
ArrayList<GradeDetail> gradeList = new ArrayList<GradeDetail>() ;
System.out.println("Student ID: ");
for(String s : args) {
boolean match = false;
for(GradeDetail grade : GradeDetail.values()) {
if(s.equals(grade.getCode())) {
gradeList.add(grade);
match = true;
}
}
if(!match) {
System.out.printf("unknown student ID entered!");
}
}
System.out.println("Students who passed: ");
//Some function here
System.out.println("Students who failed: ")
//Some function here
return;
}
}
enum GradeDetail {
JOHN (101, 90)
, ROB (102, 50)
, JAMES (103, 55)
;
private final int studentID;
private final int studentGrade;
GradeDetail(int id, int sGrade) {
studentID = id;
studentGrade = sGrade;
}
public int getID() {return studentID;}
public int getGrade() {return studentGrade;}
}
I honestly don't know how to go about this..
Enums are for Static data such as the value of the grade A, B, C. You would never store transient values like John's grade in an Enum. Why don't you try using the enum for the static values.
enum GradeRange {
A (100, 90),
B (89, 80),
C (79, 70);
private final int high;
private final int low;
GradeRange(int high, int low) {
high = high;
low = low;
}
public GradeRange getGrade(int percent) {
for (GradeRange gradeRange : GradeRange.values() {
if (percent <= high && percent >= low)
return gradeRange;
}
}
}
PS - I did not test this code
It would be appropriate to store your data in a class like
class GradeDetail {
public final String sName ;
public final int iId ;
public final int iGrade;
public GradeDetail(String s_name, int i_id, int i_grade) {
sName = s_name;
iId = i_id;
iGrade = i_grade;
}
}
You would then create instances with
GradeDetail gdJohn = new GradeDetail("John", 101, 90)
and access it, for example, with
gdJohn.iGrade;
This should hopefully get you started on the right path.
Related
Greetings StackOverFlow Community!
I have recently started studying java at school, and one of the assignments is to create a sorting method, like selection sort or insertion sort, without using java's own built-in functions. I have looked online a lot, and all of the methods I have found are for Arrays and not ArrayLists. The goal with the assignment is to sort a dog class after tail length, and if the dogs have the same tail length, to also sort after name.
So far this is what I have done;
Dog Class
public class Dog {
private static final double DEFAULT_TAIL_SIZE = 10.0;
private static final double DEFAULT_TAX_SIZE = 3.7;
private static int count;
private String name;
private String breed;
private int age;
private int weight;
private double tailLenght;
public Dog(String name, String breed, int age, int weight) {
//count++;
this.name = name;
this.age = age;
this.breed = breed;
this.weight = weight;
this.tailLenght = tailLenght;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getBreed() {
return breed;
}
public int getWeight() {
return weight;
}
public void setAge(int age) {
age = age <= 0 ? 1 : age;
}
public double getTailLength() {
if (breed.equals("Tax") || breed.equals("dachshund")||breed.equals("tax") || breed.equals("Dachshund")) {
return tailLenght = DEFAULT_TAX_SIZE;
} else {
return tailLenght = age * weight/DEFAULT_TAIL_SIZE;
}
}
#Override
public String toString() {
//System.out.println(String.format("name=%s breed=%s age=%d weight=%d taillenght=%.1f", name, breed, age, weight, getTailLength()));
return name + " " + breed + " " + age + " " + weight + " " + getTailLength();
}
And this is the sorting code I have made, that was not accepted due to the code using in-built java sorting methods. This is the only code I'm allowed to edit during this assignment
public class DogSorter {
public void sort(ArrayList<Dog> dogs) {
dogs.sort(new Comparator<Dog>() {
#Override
public int compare(Dog d1, Dog d2) {
int comparison = 0;
comparison = Double.valueOf(d1.getTailLength()).compareTo(d2.getTailLength());
if (comparison == 0) {
comparison = String.valueOf(d1.getName()).compareTo(d2.getName());
}
return comparison;
}
});
}
And lastly this is the runner code we received from our teachers
import java.util.ArrayList;
import java.util.Random;
public class DogSorterRunner {
private static final int NUMBER_OF_DOGS = 12;
private static final Random RND = new Random();
private static final String[] NAMES = { "Fido", "Karo", "Molly", "Bella", "Wilma", "Doris", "Sigge", "Charlie",
"Ludde", "Bamse", "Lassie", "Ronja", "Ratata", "Maki", "Dora", "Luna", "Spike", "Mumsan", "Cherie" };
private static final String[] BREEDS = { "Labrador", "Golden retriever", "Tax", "Dachshund" };
private static String getRandomValueFromArray(String[] array) {
return array[RND.nextInt(array.length)];
}
private static String randomName() {
return getRandomValueFromArray(NAMES);
}
private static String randomBreed() {
return getRandomValueFromArray(BREEDS);
}
private static int randomNumber() {
return RND.nextInt(10) + 1;
}
public static void main(String[] args) {
ArrayList<Dog> dogs = new ArrayList<>();
for (int n = 0; n < NUMBER_OF_DOGS; n++) {
Dog dog = new Dog(randomName(), randomBreed(), randomNumber(), randomNumber());
dogs.add(dog);
}
new DogSorter().sort(dogs);
for (Dog dog : dogs) {
System.out.println(dog);
}
}
Any help and feedback would be greatly appreciated!
The point of the assignment is that you should implement selection or insertion sort by yourself instead of using Java's built-in sort function. That is how you show some knowledge in implementing sorting algorithms.
Here is an example of a selection sort, which is based on your conditions (tail & name) and should give you a feeling of how the functions should look like. To do some more exercise, I suggest that you try to implement insertion sort by yourself.
public class DogSorter {
public void sort(ArrayList<Dog> dogs) {
dogs.sort(new Comparator<Dog>() {
#Override
public int compare(Dog d1, Dog d2) {
int comparison = 0;
comparison = Double
.valueOf(d1.getTailLength())
.compareTo(d2.getTailLength());
if (comparison == 0) {
comparison = String
.valueOf(d1.getName())
.compareTo(d2.getName());
}
return comparison;
}
});
}
public void selectionSort(ArrayList<Dog> dogs) {
int n = dogs.size();
// One by one move boundary of unsorted subarray
for (int i = 0; i < n - 1; i++) {
// Find the minimum element in unsorted array
int min_idx = i;
for (int j = i + 1; j < n; j++) {
Dog d1 = dogs.get(j);
Dog d2 = dogs.get(min_idx);
int comparison = Double
.valueOf(d1.getTailLength())
.compareTo(d2.getTailLength());
if (comparison == 0) {
comparison = String
.valueOf(d1.getName())
.compareTo(d2.getName());
}
if (comparison < 0)
min_idx = j;
}
// Swap the found minimum element with the first
// element
// using built in swap
// Collections.swap(dogs, min_idx, i);
// using classic temp method
Dog temp = dogs.get(min_idx);
dogs.set(min_idx, dogs.get(i));
dogs.set(i, temp);
// using classic method without temp element
// dogs.set(i, dogs.set(min_idx, dogs.get(i)));
}
}
}
Here is also a repl, where you can see this function in practice: https://repl.it/repls/VividMeekPlans
I have three class Homework that has my main(...), GradeArray, which has my methods, and StudentGrade, which has my constructor.
Currently , which is clearly wrong, I have in Homework:
GradeArray grades = new GradeArray();`
In GradeArray at the top I have StudentGrade[] ArrayGrades = new StudentGrade[size]; however this method did not give me both the contructor and the methods. I know I don't need three classes for this but my professor wants three class. How do I declare an array that has attributes from two classes so that I can get the methods from GradeArray and the constructor from StudentGrade?
Thank you for you time and help.
Here is all of my code
package homework1;
public class Homework1
{
public static int pubSize;
public static String pubCourseID;
public static void makeVarsPub(int maxSize, String courseID) //this is to makes the varibles public
{
pubSize = maxSize;
pubCourseID = courseID;
}
public int giveSize()
{
return pubSize;
}
public static void main(String[] args)
{
int maxSize = 100;
String courseID = "CS116";
//this is to makes the varibles public
makeVarsPub(maxSize, courseID);
StudentGrade grades = new StudentGrade();
grades.insert("Evans", 78, courseID);
grades.insert("Smith", 77, courseID);
grades.insert("Yee", 83, courseID);
grades.insert("Adams", 63, courseID);
grades.insert("Hashimoto", 91, courseID);
grades.insert("Stimson", 89, courseID);
grades.insert("Velasquez", 72, courseID);
grades.insert("Lamarque", 74, courseID);
grades.insert("Vang", 52, courseID);
grades.insert("Creswell", 88, courseID);
// print grade summary: course ID, average, how many A, B, C, D and Fs
System.out.println(grades);
String searchKey = "Stimson"; // search for item
String found = grades.find(searchKey);
if (found != null) {
System.out.print("Found ");
System.out.print(found);
}
else
System.out.println("Can't find " + searchKey);
// Find average and standard deviation
System.out.println("Grade Average: " + grades.avg());
System.out.println("Standard dev; " + grades.std());
// Show student grades sorted by name and sorted by grade
grades.reportGrades(); // sorted by name
grades.reportGradesSorted(); // sorted by grade
System.out.println("Deleting Smith, Yee, and Creswell");
grades.delete("Smith"); // delete 3 items
grades.delete("Yee");
grades.delete("Creswell");
System.out.println(grades); // display the course summary again
}//end of Main
}//end of homework1
package homework1;
class GradeArray
{
int nElems = 0; //keeping track of the number of entires in the array.
Homework1 homework1InfoCall = new Homework1(); //this is so I can get the information I need.
int size = homework1InfoCall.giveSize();
StudentGrade[] ArrayGrades = new StudentGrade[size];
public String ToString(String name, int score, String courseID)
{
String res = "Name: " + name + "\n";
res += "Score: " + score + "\n";
res += "CourseID " + courseID + "\n";
return res;
}
public String getName(int num) //returns name based on array location.
{
return ArrayGrades[num].name;
}
public double getScore(int num) //returns score based on array location.
{
return ArrayGrades[num].score;
}
public void insert(String name, double score, String courseID) //part of the insert method is going to be
//taken from lab one and modified to fit the need.
{
if(nElems == size){
System.out.println("Array is full");
System.out.println("Please delete an Item before trying to add more");
System.out.println("");
}
else{
ArrayGrades[nElems].name = name;
ArrayGrades[nElems].score = score;
ArrayGrades[nElems].courseID = courseID;
nElems++; // increment the number of elements
};
}
public void delete(String name) //code partly taken from lab1
{
int j;
for(j=0; j<nElems; j++) // look for it
if( name == ArrayGrades[j].name)
break;
if(j>nElems) // can't find it
{
System.out.println("Item not found");
}
else // found it
{
for(int k=j; k<nElems; k++) // move higher ones down
{
boolean go = true;
if ((k+2)>size)
go = false;
if(go)
ArrayGrades[k] = ArrayGrades[k+1];
}
nElems--; // decrement size
System.out.println("success");
}
}
public String find (String name){ //code partly taken from lab1
int j;
for(j=0; j<nElems; j++) // for each element,
if(ArrayGrades[j].name == name) // found item?
break; // exit loop before end
if(j == nElems) // gone to end?
return null; // yes, can't find it
else
return ArrayGrades[j].toString();
}
public double avg() //this is to get the average
{
double total = 0;
for(int j=0; j<nElems; j++)
total += ArrayGrades[j].score;
total /= nElems;
return total;
}
public double std() //this is to get the standard deviation. Information on Standard deviation derived from
//https://stackoverflow.com/questions/18390548/how-to-calculate-standard-deviation-using-java
{
double mean = 0; //this is to hold the mean
double newSum = 0;
for(int j=0; j < ArrayGrades.length; j++) //this is to get the mean.
mean =+ ArrayGrades[j].score;
for(int i=0; i < ArrayGrades.length; i++) //this is to get the new sum.
newSum =+ (ArrayGrades[i].score - mean);
mean = newSum/ArrayGrades.length; //this is to get the final answer for the mean.
return mean;
}
public StudentGrade[] reportGrades() //this is grade sorted by name
{
int in,out;
char compair; //this is for compairsons.
StudentGrade temp; //this is to hold the orginal variable.
//for the first letter cycle
for(out=1; out<ArrayGrades.length; out++)
{
temp = ArrayGrades[out];
compair= ArrayGrades[out].name.charAt(0);
in=out;
while(in>0 && ArrayGrades[in-1].name.charAt(0) > compair)
{
ArrayGrades[in] = ArrayGrades[in-1];
in--;
}
ArrayGrades[in]=temp;
}
//this is for the second run.
for(out=1; out<ArrayGrades.length; out++)
{
temp = ArrayGrades[out];
compair= ArrayGrades[out].name.charAt(1);
in=out;
while(in>0 && ArrayGrades[in-1].name.charAt(1) > compair)
{
ArrayGrades[in] = ArrayGrades[in-1];
in--;
}
ArrayGrades[in]=temp;
}
return ArrayGrades;
}
public StudentGrade[] reportGradesSorted() //this is grades sorted by grades.
//this is grabbed from lab2 and repurposed.
{
int in,out;
double temp;
for(out=1; out<ArrayGrades.length; out++)
{
temp=ArrayGrades[out].score;
in=out;
while(in>0 && ArrayGrades[in-1].score>=temp)
{
ArrayGrades[in]= ArrayGrades[in-1];
in--;
}
ArrayGrades[in].score=temp;
}
return ArrayGrades;
} //end of GradeArray
package homework1;
public class StudentGrade extends GradeArray
{
public String name;
double score;
public String courseID;
public void StudentGrade (String name, double score, String courseID) //this is the constructor
{
this.name = name;
this.score = score;
this.courseID = courseID;
}
}//end of StudentGrade class.
First, I feel #Alexandr has the best answer. Talk with your professor.
Your question doesn't make it quite clear what you need. However, it sounds like basic understanding of inheritance and class construction would get you going on the right path. Each of the 3 classes will have a constructor that is unique to that type. Each of the 3 classes will have methods and data (members) unique to those types.
Below is just a quick example of what I threw together. I have strong concerns that my answer is actually what your professor is looking for however--it is not an object model I would suggest--just an example.
public class Homework {
private String student;
public Homework(String name) {
student = name;
}
public String getStudent() {
return student;
}
}
public class StudentGrade extends Homework {
private String grade;
public StudentGrade(String grade, String name) {
super(name);
this.grade = grade;
}
public String getGrade() {
return grade;
}
}
public class HomeworkGrades {
public List<StudentGrade> getGrades() {
// this method isnt implemented but should
// be finished to return array of grades
}
}
Take a look and see if that helps you understand something about inheritance and class construction.
Hopefully you can infer a bit about inheritence (StudentGrade inherits -- in java extends -- from HomeWork) and class construction.
Thnx
Matt
I change the array creation in Homework1 to be StudentGrade grades = new StudentGrade(); and I added extends GradeArray to the StudentGrade class. it is now public class StudentGrade extends GradeArray.
I've been studying code on my own, and I got a problem that I do not know how to answer.
I am given a student and classroom class, and from those two I need to be able to create a method for getTopStudent, as well as thegetAverageScore.
**Edit: All of the code was given except for the two methods, I needed to create those 2. The thing is that I'm not sure if what I'm doing is correct.
public class Student
{
private static final int NUM_EXAMS = 4;
private String firstName;
private String lastName;
private int gradeLevel;
private double gpa;
private int[] exams;
private int numExamsTaken;
public Student(String fName, String lName, int grade)
{
firstName = fName;
lastName = lName;
gradeLevel = grade;
exams = new int[NUM_EXAMS];
numExamsTaken = 0;
}
public double getAverageScore() //this is the method that I need to, but I'm not sure if it is even correct.
{
int z=0;
for(int i =0; i<exams.length; i++)
{
z+=exams[i];
}
return z/(double) numExamsTaken;
}
public String getName()
{
return firstName + " " + lastName;
}
public void addExamScore(int score)
{
exams[numExamsTaken] = score;
numExamsTaken++;
}
public void setGPA(double theGPA)
{
gpa = theGPA;
}
public String toString()
{
return firstName + " " + lastName + " is in grade: " + gradeLevel;
}
}
public class Classroom
{
Student[] students;
int numStudentsAdded;
public Classroom(int numStudents)
{
students = new Student[numStudents];
numStudentsAdded = 0;
}
public Student getTopStudent() //this is the other method I need to create
{
int x=0;
int y=0;
for(int i =0; i<numStudentsAdded; i++)
{
if(x<students.getAverageScore())
{
x=students.getAverage();
y++;
}
}
return students[y];
}
public void addStudent(Student s)
{
students[numStudentsAdded] = s;
numStudentsAdded++;
}
public void printStudents()
{
for(int i = 0; i < numStudentsAdded; i++)
{
System.out.println(students[i]);
}
}
}
I have something down for each of them but it isn't running. I don't fully understand arrays yet, but this is apparently a beginner code using arrays. If anyone could help with what I need to do and tell me how arrays work, much would be appreciated.
getAverageScore() is a method of Student. But students is not a Student object, it's an array of Student objects. (And getAverage(), which you call inside the for loop, isn't a method at all.) An array is a separate object that contains other objects or primitives (like ints) in it. So students.getAverageScore() is not going to compile, because students doesn't have that method, each of its members (student[0], student[1], etc.) has it.
Try replacing the getTopStudent method with something like this:
public Student getTopStudent() //this is the other method I need to create
{
int x=0; //this will contain the highest average
int y=0; //this will be the index in the array of the highest scoring student
for(int i =0; i<numStudentsAdded; i++)
{
int currentAverage = students[i].getAverageScore(); //run the getAverageScore() on the current student
if(x<currentAverage) // compare it to the previous high average
{
x=currentAverage; // replace x with new high average
y=i; //replace the index of the highest scoring student with current index i
}
}
return students[y]; // so if the fifth student had the highest score, y would be 4
}
So you are having trouble int the method public Student getTopStudent()
public Student getTopStudent() //this is the other method I need to create
{
double x= students[0].getAverageScore();
int y = 0;
for(int i=1;i<students.length;i++){
if(x<students[i].getAverageScore()) {
x = students[i].getAverageScore();
y =i;
}
}
return students[y];
}
See if this helps
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;
I cant get how to use/create oop code without word static. I read Sun tutorials, have book and examples. I know there are constructors, then "pointer" this etc. I can create some easy non-static methods with return statement. The real problem is, I just don't understand how it works.I hope some communication gives me kick to move on. If someone asks, this is not homework. I just want to learn how to code.
The following code are static methods and some very basic algorithms. I'd like to know how to change it to non-static code with logical steps(please.)
The second code shows some non-static code I can write but not fully understand nor use it as template to rewrite the first code.
Thanks in advance for any hints.
import java.util.Scanner;
/**
*
* #author
*/
public class NumberArray2{
public static int[] table() {
Scanner Scan = new Scanner(System.in);
System.out.println("How many numbers?");
int s = Scan.nextInt();
int[] tab = new int[s];
System.out.println("Write a numbers: ");
for(int i=0; i<tab.length; i++){
tab[i] = Scan.nextInt();
}
System.out.println("");
return tab;
}
static public void output(int [] tab){
for(int i=0; i<tab.length; i++){
if(tab[i] != 0)
System.out.println(tab[i]);
}
}
static public void max(int [] tab){
int maxNum = 0;
for(int i=0; i<tab.length; i++){
if(tab[i] > maxNum)
maxNum = tab[i];
}
//return maxNum;
System.out.println(maxNum);
}
static public void divide(int [] tab){
for(int i=0; i<tab.length; i++){
if((tab[i] % 3 == 0) && tab[i] != 0)
System.out.println(tab[i]);
}
}
static public void average(int [] tab){
int sum = 0;
for(int i=0; i<tab.length; i++)
sum = sum + tab[i];
int avervalue = sum/tab.length;
System.out.println(avervalue);
}
public static void isPrime(int[] tab) {
for (int i = 0; i < tab.length; i++) {
if (isPrimeNum(tab[i])) {
System.out.println(tab[i]);
}
}
}
public static boolean isPrimeNum(int n) {
boolean prime = true;
for (long i = 3; i <= Math.sqrt(n); i += 2) {
if (n % i == 0) {
prime = false;
break;
}
}
if ((n % 2 != 0 && prime && n > 2) || n == 2) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
int[] inputTable = table();
//int s = table();
System.out.println("Written numbers:");
output(inputTable);
System.out.println("Largest number: ");
max(inputTable);
System.out.println("All numbers that can be divided by three: ");
divide(inputTable);
System.out.println("Average value: ");
average(inputTable);
System.out.println("Prime numbers: ");
isPrime(inputTable);
}
}
Second code
public class Complex {
// datové složky
public double re;
public double im;
// konstruktory
public Complex() {
}
public Complex(double r) {
this(r, 0.0);
}
public Complex(double r, double i) {
re = r;
im = i;
}
public double abs() {
return Math.sqrt(re * re + im * im);
}
public Complex plus(Complex c) {
return new Complex(re + c.re, im + c.im);
}
public Complex minus(Complex c) {
return new Complex(re - c.re, im - c.im);
}
public String toString() {
return "[" + re + ", " + im + "]";
}
}
Let's start with a simple example:
public class Main
{
public static void main(final String[] argv)
{
final Person personA;
final Person personB;
personA = new Person("John", "Doe");
personB = new Person("Jane", "Doe");
System.out.println(personA.getFullName());
System.out.println(personB.getFullName());
}
}
class Person
{
private final String firstName;
private final String lastName;
public Person(final String fName,
final String lName)
{
firstName = fName;
lastName = lName;
}
public String getFullName()
{
return (lastName + ", " + firstName);
}
}
I am going to make a minor change to the getFullName method now:
public String getFullName()
{
return (this.lastName + ", " + this.firstName);
}
Notice the "this." that I now use.
The question is where did "this" come from? It is not declared as a variable anywhere - so it is like magic. It turns out that "this" is a hidden parameter to each instance method (an instance method is a method that is not static). You can essentially think that the compiler takes your code and re-writes it like this (in reality this is not what happens - but I wanted the code to compile):
public class Main
{
public static void main(final String[] argv)
{
final Person personA;
final Person personB;
personA = new Person("John", "Doe");
personB = new Person("Jane", "Doe");
System.out.println(Person.getFullName(personA));
System.out.println(Person.getFullName(personB));
}
}
class Person
{
private final String firstName;
private final String lastName;
public Person(final String fName,
final String lName)
{
firstName = fName;
lastName = lName;
}
public static String getFullName(final Person thisx)
{
return (thisx.lastName + ", " + thisx.firstName);
}
}
So when you are looking at the code remember that instance methods have a hidden parameter that tells it which actual object the variables belong to.
Hopefully this gets you going in the right direction, if so have a stab at re-writing the first class using objects - if you get stuck post what you tried, if you get all the way done post it and I am sure we help you see if you got it right.
First, OOP is based around objects. They should represent (abstract) real-world objects/concepts. The common example being:
Car
properties - engine, gearbox, chasis
methods - ignite, run, brake
The ignite method depends on the engine field.
Static methods are those that do not depend on object state. I.e. they are not associated with the notion of objects. Single-program algorithms, mathematical calculations, and such are preferably static. Why? Because they take an input and produce output, without the need to represent anything in the process, as objects. Furthermore, this saves unnecessary object instantiations.
Take a look at java.lang.Math - it's methods are static for that precise reason.
The program below has been coded by making the methods non-static.
import java.util.Scanner;
public class NumberArray2{
private int tab[]; // Now table becomes an instance variable.
// allocation and initilization of the table now happens in the constructor.
public NumberArray2() {
Scanner Scan = new Scanner(System.in);
System.out.println("How many numbers?");
int s = Scan.nextInt();
tab = new int[s];
System.out.println("Write a numbers: ");
for(int i=0; i<tab.length; i++){
tab[i] = Scan.nextInt();
}
System.out.println("");
}
public void output(){
for(int i=0; i<tab.length; i++){
if(tab[i] != 0)
System.out.println(tab[i]);
}
}
public void max(){
int maxNum = 0;
for(int i=0; i<tab.length; i++){
if(tab[i] > maxNum)
maxNum = tab[i];
}
System.out.println(maxNum);
}
public void divide(){
for(int i=0; i<tab.length; i++){
if((tab[i] % 3 == 0) && tab[i] != 0)
System.out.println(tab[i]);
}
}
public void average(){
int sum = 0;
for(int i=0; i<tab.length; i++)
sum = sum + tab[i];
int avervalue = sum/tab.length;
System.out.println(avervalue);
}
public void isPrime() {
for (int i = 0; i < tab.length; i++) {
if (isPrimeNum(tab[i])) {
System.out.println(tab[i]);
}
}
}
public boolean isPrimeNum(int n) {
boolean prime = true;
for (long i = 3; i <= Math.sqrt(n); i += 2) {
if (n % i == 0) {
prime = false;
break;
}
}
if ((n % 2 != 0 && prime && n > 2) || n == 2) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
// instatiate the class.
NumberArray2 obj = new NumberArray2();
System.out.println("Written numbers:");
obj.output(); // call the methods on the object..no need to pass table anymore.
System.out.println("Largest number: ");
obj.max();
System.out.println("All numbers that can be divided by three: ");
obj.divide();
System.out.println("Average value: ");
obj.average();
System.out.println("Prime numbers: ");
obj.isPrime();
}
}
Changes made:
int tab[] has now been made an
instance variable.
allocation and initialization of the
table happens in the constructor.
Since this must happen for every
instantiated object, it is better to
keep this in a constructor.
The methods need not be called with
table as an argument as all methods
have full access to the instance
variable(table in this case)
The methods have now been made
non-static, so they cannot be called
using the class name, instead we need
to instantiate the class to create an
object and then call the methods on
that object using the obj.method()
syntax.
It is easy to transform class methods from beeing static to non-static. All you have to do is remove "static" from all method names. (Ofc dont do it in public static void main as you would be unable to run the example)
Example:
public static boolean isPrimeNum(int n) { would become
public boolean isPrimeNum(int n) {
In public static void main where you call the methods you would have to chang your calls from beeing static, to refere to an object of the specified class.
Before:
NumberArray2.isPrimeNum(11);
After:
NumberArray2 numberarray2 = new NumberArray2(); // Create object of given class
numberarray2.isPrimeNum(11); // Call a method of the given object
In NumberArray2 you havent included an constructor (the constructor is like a contractor. He takes the blueprint (class file, NumberArray2) and follows the guidelines to make for example a building (object).
When you deside to not include a constructor the java compilator will add on for you. It would look like this:
public NumberArray2(){};
Hope this helps. And you are right, this looks like homework :D
I belive its common practice to supply the public modifier first. You haven done this in "your" first method, but in the others you have static public. Atleast for readability you should do both (code will compile ether way, as the compilator dosnt care).
The code is clean and easy to read. This is hard to do for someone who is "just want to learn how to code". Hope this helps you on your way with your "justlookslikehomeworkbutisnt" learning.
I'm guessing you're confused of what "static" does. In OOP everything is an object. Every object has its own functions/variables. e.g.
Person john = new Person("John",18);
Person alice = new Person("Alice",17);
if the function to set the 'name' variable would be non static i.e. string setName(string name){} this means that the object john has a name "John" and the object alice has a name "Alice"
static is used when you want to retain a value of something across all objects of the same class.
class Person{
static int amountOfPeopleCreated;
public Person(string name, int age){
amountOfPeopleCreated++;
setName(name);
setAge(age);
}
...
}
so if you'd the value of amountOfPeopleCreated will be the same no matter if you check alice or john.