I'm trying to figure out, how to get to my Objects in object list.
I have made "MainHolder.class" where I made my Object list with simple variables(Later I want to add there boolean, real, integer and string values, so simple int array list wont work for me).
My Idea is about simple getting to my object. For example:
Displaying values like: CarMain.PlayerLevel.name();
Adding values like: CarMain.PlayerLevel.count +=1;
But now I got problem trying to Adding values.
Got error : Cannot resolve symbol PlayerLevel
In Line CarMain.PlayerLevel.count +=1;
This is my MainHolder.class
package com.crelix.crelix;
public class MainHolder {
int id;
String name;
int count;
public void id(int id) {
}
public MainHolder(String name) {
}
public void count(int count){
this.count += count;
}
public static void main(String args[]) {
MainHolder Money = new MainHolder("Money: ");
MainHolder MoneyClicks = new MainHolder("Money Clicks: ");
MainHolder Boxes = new MainHolder("Boxes: ");
MainHolder BoxClicks = new MainHolder("Boxes Clicks: ");
MainHolder BoxLevel = new MainHolder("Box Level: ");
MainHolder PlayerLevel = new MainHolder("Player Level: ");
MainHolder GarageLevel = new MainHolder("Garage Level: ");
MainHolder GarageSlots = new MainHolder("Garage Slots: ");
Money.id(1);
Money.count(0);
MoneyClicks.id(2);
MoneyClicks.count(0);
Boxes.id(3);
Boxes.count(0);
BoxClicks.id(4);
BoxClicks.count(0);
BoxLevel.id(5);
BoxLevel.count(1);
PlayerLevel.id(6);
PlayerLevel.count(1);
GarageLevel.id(7);
GarageLevel.count(1);
GarageSlots.id(8);
GarageSlots.count(25);
}
}
And In MainActivity I want to add Player Level Like here:
public void upgradeLevel(View view){
for (int i =9; i >=0; i--){
if (CarMain.PlayerLevel.count() == i){
if (CarMain.Money.count() >= 100*i){
CarMain.Money.count() = CarMain.Money.count() - (100*i);
CarMain.PlayerLevel.count() += 1;
}
else{
//Else
}
}
}
if (CarMain.PlayerLevel.count() == 10){
//Max Level
}
}
Heres My Error in Image : Image
You are defining PlayerLevel inside the main method of MainHolder. So it isn't visible to calling classes (in this case MainActivity). To access them you need to define them as global variables at the top which is a very bad thing to do. Also, you shouldn't declare PlayerLevel inside MainHolder in the first place since all you want that class to do is hold the id and count. Instead declare PlayerLevel inside MainActivity.
If you absolutely want a super class holding all your MainHolders you should use nested classes.
Related
So currently I am studying Arrays so I am new to this. I have created this code but when I try to enter my inputs after specifying the size it gives me the error java.lang.NullPointerException
I know one of the ways is to use constructors but I want to try it this way.
Also I know my print statements are not configured correctly but I can fix that later should be simple.
import java.util.Scanner;
public class CourseTest {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("Enter size of Course");
int x=s.nextInt();
Course arr[]=new Course[x];
Course c =new Course();
for (int i = 0; i < arr.length; i++) {
System.out.println("Enter Course Code");
arr[i].setCchour(s.nextInt());
System.out.println("Enter course Title");
arr[i].setCtitle(s.next());
System.out.println("Enter Course Credit hour");
arr[i].setCchour(s.nextInt());
}
for (int i = 0; i < arr.length; i++) {
System.out.println("Course Code is");
System.out.println(arr[i]);
System.out.println("Course Title is");
System.out.println(arr[i]);
System.out.println("Course Credit hour is");
System.out.println(arr[i]);
}
}
}
"Class"
public class Course {
private int Ccode;
private String Ctitle;
private int Cchour;
public void setCcode(int Ccode) {
this.Ccode = Ccode;
}
public void setCtitle(String Ctitle) {
this.Ctitle = Ctitle;
}
public void setCchour(int Cchour) {
this.Cchour = Cchour;
}
public int getCcode() {
return Ccode;
}
public String getCtitle() {
return Ctitle;
}
public int getCchour() {
return Cchour;
}
}
Course arr[]=new Course[x];
Okay, you now have an array that can hold references (pointers) to course objects. It's like you've created a book where on each page you can write the details of a course, but the pages are still blank. It has x pages.
Course c =new Course();
Okay, you have created a new course object, and you have created a new variable named c which can reference (point at) course objects; c now points at the created course.
You never use c again, so this line does nothing.
arr[i].setCchour(s.nextInt());
okay, you flip to the first page of your book and,.. oh dear, it is blank, so, NullPointerException.
Solution
learn about how java works, what references are. Then it becomes obvious: That Course c = new Course(); line doesn't do anything; you want 1 course for each 'page' in your book-of-courses (your array), so new Course() needs to run x times. That suggests, correctly, that it needs be inside the for loop. First action in that for loop should be arr[i] = new Course(). Meaning: Create a new course object. Write the reference to this newly created object on the i-th page of your book of courses.
I am writing a programme for a Quiz score, I have the array in the main method and I need to supply an appropriate constructor and methods in a separate class, “addQuizScore(int score)”, “getTotalScore”. I'm still new to Java and stuck on how to do this correctly.
import java.util.*;
public class StudentQuiz
{
public static void main(String[] args)
{
int [] score = {7,8,5,6,0,10,7,6};
StudentQuizInfo newStudent = new StudentQuizInfo(score);
System.out.println("total score: " +newStudent.getTotalScore());
}
}
import java.util.*;
public class StudentQuizInfo {
private int overallScore = 0;
private int totalScore = 0;
public StudentQuizInfo(int[] score) {
}
public int addQuizScore(int [] score)
{
int k;
int overallScore = 0;
for(k = 0; k <score.length; k++)
{
overallScore = overallScore + score[k];
}
return overallScore;
}
int getTotalScore()
{
int totalScore = overallScore;
return totalScore;
}
}
ATM the code prints totalscore: 0 which is incorrect.
I realise my current code is very poor, so any pointers to how i can correct this would be much appreciated, particularly on how to use addQuizScore correctly.
Thanks
Adding
newStudent.addQuizScore(score);
after
StudentQuizInfo newStudent = new StudentQuizInfo(score);
should fix the problem.
Additionally, your architecture is a bit odd. Your constructor is doing nothing the way it is written now. As you have a method called addQuizScore I assume, that you don't need to keep the score inside of the StudentQuizInfo object, so you can safely remove the int[] score parameter from the constructor of the class.
Also the variables overallCore and totalScore seem to be redundant.
Change the constructor like this
public StudentQuizInfo(int[] score) {
addQuizScore(score)
}
or
StudentQuizInfo newStudent = new StudentQuizInfo(score);
newStudent.addQuizScore(score);
I have a problem with my code, in that it keeps saying that the constructor is undefined. I already read somewhere that I need to declare the constructor with no arguments. I just don't know how to do that.
If someone could help, I am new at java and programming. My code is below:
import java.util.*;//import library
class Input
{
public Input (int size,int startV,int endingV)
{
//declarations of variables
double difference;
double[] array= new double[size];
array[0]=startV;
//calculating the difference to add on each number in the array
difference=(endingV-startV)/size;
for (int counter=1;counter<size;counter++) //for loop to fill the array
{
array[counter]=array[counter-1] + difference;
}
}
public Input enter(int size,int startV,int endingV)
{
//declarations of variables
double difference;
double[] array= new double[size];
array[0]=startV;
//calculating the difference to add on each number in the array
difference=(endingV-startV)/size;
for (int counter=1;counter<size;counter++) //for loop to fill the array
{
array[counter]=array[counter-1] + difference;
}
return this;
}
}
class Show
{
public Show (int size,double[] array)
{
for (int i=0;i<size;i++) //for loop to print the array
System.out.println("This is the array " + i+ ": " + array[i]);
}
public Show print(int size,double[] array)
{
for (int i=0;i<size;i++) //for loop to print the array
System.out.println("This is the array " + i+ ": " + array[i]);
return this;
}
}
public class Assignment2
{
public static void main(String[] args)
{
//declaring variables
int startV,endingV;
int size=0;
System.out.print("Give the size of the array:");//Print message on screen
size = new Scanner(System.in).nextInt();//asking for the size of array
double[] array= new double[size]; //creation of array
System.out.print("Give the starting value of the array:");
startV = new Scanner(System.in).nextInt();//asking for the starting value of array
System.out.print("Give the ending value of the array:");
endingV = new Scanner(System.in).nextInt();//asking for the last value of array
//calling the functions from the other classes
Input enter= new Input(size,startV,endingV);
Show print= new Show(size,array);
}
}
You're close:
You have a method:
public Method enter(int size,int startV,int endingV) {
to make it a constructor it's signature must be
public Method (int size,int startV,int endingV) {
and you then have to delete the return this; statement.
Remember, constructors don't have a return type and their name is identical to the name of the class. With this information, you'll also be able to fix the Method1 constructor.
Also, please respect the Java naming conventions and have variables start with a lower-case letter to improve the readability of your code.
You need to create a
public Method(size,startV,endingV)
not
public Method enter = (size, startV, endingV)
The first is a constructor the second is a method
For class Method
the default constructor will be
public Method(){}
For class Method1
the default constructor will be
public Method1(){}
in your classes there are no constructors as the
constructor name must be will the same as class name.
enter(int size,int startV,int endingV)
and
print(int size,double[] array)
can be two methods in your classes.
also your two constructor can be -
public Method(int size,int startV,int endingV){ /..../}
and
public Method1(int size,double[] array){ /..../}
Your constructor must have the same name than your class and has no return type. So for your class Method, your constructor will simply be :
public Method(int size, int startV, int endingV)
{
// code...
}
Please also note that constructors exist to initialize your instances of objects, if you want to create a method that does a specific calcul, then yes, you'll have to do :
public int enter(int size, int startV, int endingV)
{
int result = 0;
// code to calculate, for example result = size + startV + endingV ...
return result;
}
I've been working on this program for a few weeks now, it's our final project in my Java programming class and it has been giving me (and a lot of other students) some pretty good headaches.
We need to create a program that allows a user to enter, display and remove new planes along with the plane's speed, altitude and type of plane.
I've been having the most problems with getting the main class to communicate with the other classes. Because of this, I don't know if my LinkedList is going to work properly, or if at all. I'm worried that the list is not going to properly store all the fields together and that the node is not properly coded.
I could really use any help or advice you can provide. Code is below. I'm open to any and all suggestions. The code does not have to stay in exactly the same classes it is currently in. If something would work better somewhere else, I'd be happy to try it.
Main Class. This is where the user will be interacting with the program. I have been having a hard time getting the methods from other classes to work in this class. I'm sure it is something simple that I am missing.
package airTraffic;
import java.util.*;
public class Main {
static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
do {
try {
System.out.println("Please enter command to proceed: ");
System.out.println("Enter new aircraft = e");
System.out.println("Display all aircraft = d");
System.out.println("Show specific flight = s");
System.out.println("Remove specific flight = r");
String command = in.next();
in.next(command);
if ( (in.next(command)).equals("e") ) {
ATControl.addToList(); // need to somehow "start" this class
} else if ( (in.next(command)).equals("d") ) {
ATControl.displayAll();
} else if ( (in.next(command)).equals("s") ){
ATControl.showFlight();
} else if ( (in.next(command)).equals("r") ) {
ATControl.removeFlight();
} else if ( (in.next(command)).equals(null) ) {
}
} catch (InputMismatchException exc) {
System.out.println("Wrong entry, please try again:");
}
} while (true);
}
}
Linked List and Node - I called it Aircraft. I think this is where the list is stored and created. Manipulation to the list occurs in the next class (ATControl), or at least I think it will.
package airTraffic;
import java.util.LinkedList;
public class Aircraft {
// stores data
private static final int INITIAL_ALLOCATION = 20;
private int size = INITIAL_ALLOCATION;
//declare LinkedList and node names
static LinkedList <String> list = new LinkedList <String> ();
private Aircraft head = new Aircraft ();
private Aircraft tail = new Aircraft ();
// tells list to add nodes
public void addNodes (int n, LinkedList<String> s) {
s = list;
head.next = tail;
tail.next = tail;
size = n;
Aircraft temp = head;
for (int i= 0; i < size; ++i) {
temp.next = new Aircraft ();
temp = temp.next;
}
temp.next = tail;
}
private String value;
Aircraft craft;
public Aircraft (String v) {
value = v;
}
public Aircraft () {
}
public String get () {
return value;
}
public void set (String v) {
value = v;
}
public Aircraft next = null;
//auto generated method from ATControl
public static void add(String flight) {
// a for or while loop might be needed here. Seems to easy to just have an empty add class
}
//auto generated method from ATControl
public static void remove() {
}
}
ATControl class. This is where (I think) the list is manipulated, allowing the user to add, remove and show the flights.
package airTraffic;
import java.util.*;
public class ATControl{
// implement Aircraft class (node) - empty argument list??
Aircraft aircraft = new Aircraft ();
static Scanner in = new Scanner (System.in);
// list of planes
static String [] planeList = {"Wide-body Airliner = w", "Regional Airliner = r", "Private Plane = p",
"Military = m", "Cargo only: c", "Unknown = u"};
//add plane and details
public static void addToList () {
System.out.printf("Enter flight number: ");
String flight = in.nextLine();
Aircraft.add(flight);
//type of plane
System.out.printf("Enter type of plane, ", "Choose from: " + planeList);
String type = in.nextLine();
try {
if (type == "w") {
System.out.println("Wide-body Airliner");
}else if (type == "r") {
System.out.println("Regional Airliner");
}else if (type == "p") {
System.out.println("Private Plane");
}else if (type == "m") {
System.out.println("Military");
}else if (type == "c") {
System.out.println("Cargo only");
}else if (type == "u") {
System.out.println("Unknown");
} else type = null;
}
catch (InputMismatchException i) {
System.out.println("You must enter valid command: " + planeList);
}
Aircraft.add(type);
//plane speed
System.out.printf("Enter current speed: ");
String speed = in.nextLine();
Aircraft.add(speed);
//add Altitude
System.out.printf("Enter current altitude: ");
String alt = in.nextLine();
Aircraft.add(alt);
}
//show flight
public static void showFlight () {
System.out.printf("Enter flight number for details: ");
in.nextLine();
Aircraft.get(Aircraft, index);
}
// display all flights
public static void displayAll () {
System.out.printf("All flights: " );
}
//remove flight
public static void removeFlight () {
System.out.printf("Enter flight number to be removed: ");
in.nextLine();
Aircraft.remove();
}
}
Any ideas? Thank you!
To "start" ATControl, you need to create a new instance of it:
ATControl control = new ATControl();
control.addToList();
Same with your Aircraft. You will want to create new instances with new, and then call Add(), etc. on them.
You will also probably want to pass your Scanner from main into the new ATControl and use it to read the input, instead of using a brand new Scanner
When using object oriented design, think of your objects as representations of actual objects. Your aircraft class should represent an actual aircraft. The aircraft should keep track of things that are associated with it. So things like flight number, speed, altitude, etc.. should be properties of that class.
public class Aircraft{
private int speed;
private int altitude;
private int flightNum;
//
//Regional Airliner, Military, Private Plane, etc.
private String type;
public void setSpeed(int speed){
this.speed = speed;
}
public int getSpeed(){
return speed;
}
//
//TODO: Getters and Setters for the rest of the aircraft properties
}
Now pretty much everything else should be handled by your ATControl class. An array list of type Aircraft seems much more logical to use in this case.
public class ATControl{
private ArrayList<Aircraft> currentFlights;
//
//Constructor gets called on initialization
public ATControl(){
currentFlights = new ArrayList<Aircraft>();
}
//
//User input should be handled in main class and passed into this
public void addFlight(int flightNum, int speed, int altitude){
Aircraft newCraft = new Aircraft();
//
//assign the properties we just got from the user to our new aircraft
newCraft.setFlightNumber(flightNum);
newCraft.setSpeed(speed);
//
//Now add our new flight to the list of current flights
currentFlights.add(newCraft);
}
}
Your main class can remain pretty much as you have it. I would handle all user input there, though.
public class Main {
static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
ATControl denverTrafficControl = new ATControl();
//
//Handle user input here: get the speed, altitude, flightNum, etc..
denverTrafficControl.addFlight(flightNum, speed, altitude);
}
}
This is how it should be done. Hopefully this has helped you grasp the objected oriented design a bit better. Let the main class handle I/O and your other actual "object" classes handle the data. Good luck.
Your general design seems to ignore object oriented principles. As I see it, aircraft should hold its type, speed and altitude together in one object.
Why reinvent the wheel? There are plenty of premade (and well tested) collection classes already built into the JRE (e.g. ArrayList, LinkedList). Make use of them to hold your aircraft instances.
These two changes should drastically reduce the amount of code you need to write/maintain and the overall complexity of the program should be reduced considerably.
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.