(Another) "non-static method cannot be referenced from a static context" issue - java
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;
Related
I need to pass a variable into a method
In my code I created a class called Points which checks answer for given question and returns score. Another class called Report takes some information to prints it package finalproject; public class Points { public static float calculatePoints(byte[] userAnswer) { byte realAnswer[], gradeCounter; float score ; gradeCounter = 0; realAnswer = new byte[3]; realAnswer[0] = 3; realAnswer[1] = realAnswer[2] = 1; for (int i = 0; i < userAnswer.length; i++) { if (userAnswer[i] == realAnswer[i]) { gradeCounter++; } } score = (gradeCounter / 3) * 100; return score; } } package finalproject; public class Report { public static void getLoginInfo(String[] loginInformation) { loginInformation = new String[2]; String name, id; name = loginInformation[0]; id = loginInformation[1]; } public static void printReport() { System.out.println("\n\n-------------------\n\n"); System.out.println("\t\tJava Certification"); System.out.println("\t\t Test Result\n\n"); System.out.println("\tName: "); System.out.println("\tTest Registration ID: "); System.out.println("\tPassing Score 52%"); System.out.println("\tYour Score: "); /* * if (score1 >= 52.0) { System.out.println("\n\nComment GRADE: pass\n\n"); } * else { System.out.println("\n\nComment GRADE: fail\n\n"); } */ System.out.println("Max Score\t" + "---------------100%"); System.out.println("Max Score\t" + "--------52%"); } } In getLoginInfo variable called name and id should be set and I want to pass them into printReport. I want to pass variable called score in function calculatePoint() to printReport how can I do it ?
If you declare name and id outside any function the scope of strings name and id would be that of class meaning it will be visible to all functions in class Report. Each object/instance of class report will have name and id as attributes. Then getLoginInfo can be used to set and printReport() can be used to print name and id. public class Report { String name, id; public static void getLoginInfo(String[] loginInformation){ name = loginInformation[0]; id = loginInformation[1]; } public static void printReport() { ... } }
Java - Cannot display user input data as an output table using classes
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.
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!!
Java program grading
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); }
How to turn static methods into non-static. Small explanation/examples related to java oop
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.