Getting object array data - java

So i first declare this object of a class:
static enterprise[] en = new enterprise[10];
Then, inside main:
for(int i=0;i<=9;i++){
System.out.println("Insert name of the " + (i+1) + "ª enterprise");
en[i] = new enterprise(i);
Scanner scanner = new Scanner(System.in);
en[i].setName(scanner.next());
System.out.println(en[i].Name);
}
And then, in another method of the same class:
for(int i = 0; i<=9;i++){
System.out.println(en[i].index + "- " + en[i].Name);
}
So if at first I inserted on the first enterprise A, second B, C,D,E,F,G,H,I,J.. I should get as an output 1 A 2 B etc, but I get 9 J ten times. why does this happen?
Edit: here is the enterprise class: http://pastebin.com/gUCWRRgK

It's because your fields are declared static.
public class enterprise {
static String Name;
static int index;
When a field is static it means that variable is associated with the class. Static variables cannot have different values for each instance.
It should be this:
public class enterprise {
String Name;
int index;

That's because you made your variables static. Remove the static keywords and it'll work. static does not work in Java like it does in C.

Related

why doesn't the variable increase?

I am learning Java, so I understand this is a very simple question, but I still want to understand it.
I want to let my code automatically generate soldiers, and the number automatically increases, but I failed.
the Soldier.class:
package com.mayer;
import java.util.Random;
public class Soldier {
private int number=0;
private int ATK;
private int HP;
Random ra = new Random();
public Soldier(){
this.number++;
this.ATK = ra.nextInt(10)+90;
this.HP = ra.nextInt(20)+180;
}
public void report(){
System.out.println("number:"+this.number+"\t"+
"ATK:"+this.ATK+"\t"+
"HP:"+this.HP);
}
}
the main.class
package com.mayer;
public class Main {
public static void main(String[] args) {
Soldier[] soldiers = new Soldier[5];
int i = 0;
while(i<5){
soldiers[i] = new Soldier();
i++;
}
for(Soldier sol:soldiers){
sol.report();
}
}
}
That's what I get:
number:1 ATK:94 HP:187
number:1 ATK:94 HP:181
number:1 ATK:96 HP:193
number:1 ATK:90 HP:183
number:1 ATK:95 HP:193
So you see,each of this number is 1.
You have added number field which is instance field. It will initialize per instance. You are looking for static type variable. Please check static into java.
Instance Variables (Non-Static Fields) Technically speaking, objects
store their individual states in "non-static fields", that is, fields
declared without the static keyword. Non-static fields are also known
as instance variables because their values are unique to each instance
of a class (to each object, in other words); the currentSpeed of one
bicycle is independent from the currentSpeed of another.
Class Variables (Static Fields) A class variable is any field declared with the static modifier; this tells the compiler that there
is exactly one copy of this variable in existence, regardless of how
many times the class has been instantiated. A field defining the
number of gears for a particular kind of bicycle could be marked as
static since conceptually the same number of gears will apply to all
instances. The code static int numGears = 6; would create such a
static field. Additionally, the keyword final could be added to
indicate that the number of gears will never change.
The constructor is changed to:
public Soldier(int number){
this.number = number;
this.ATK = ra.nextInt(10)+90;
this.HP = ra.nextInt(20)+180;
}
As others have said, each Soldier instance has its own separate number field which starts with 0. You can use a static field to count the instances:
public class Soldier {
private static int counter = 0;
private int number;
// other fields left out for clarity
public Soldier(){
Soldier.counter++; // field shared among all Soldier instances
this.number = counter; // number belongs to this instance only
// ...
}
// ...
}
However, I wouldn't recommend doing it this way. When you get more advanced, you'll learn that using a static field like this can cause problems in a multi-threaded application. I would instead advise passing the number to the Soldier constructor:
public class Soldier {
private int number;
// ...
public Soldier(int number){
this.number = number;
// ...
}
// ...
}
And then:
public static void main(String[] args) {
Soldier[] soldiers = new Soldier[5];
int i = 0;
while(i<5){
soldiers[i] = new Soldier(i);
i++;
}
Soldier.class
all-uppercase field names tend to be used for constants.. basic fields use headless camel-case.. They should also be descriptive, i.e. you should look at them an it should be apparent what they represent - for example a variable "number" is not a good idea, because it's ambiguous
Random can be converted to a local variable, no need to keep it on the class level
The mechanism by which soldiers are assigned IDs should be on a higher level - it can't be managed by the soldier object itself, hence the constructor with an argument
overriding the toString method is the traditional way of transforming the object to string for debugging purposes.. also most IDEs can generate it with a press of a button so no space for human error
You will obviously need getters and setters for your variables, if you wish to read or change them from elsewhere, but I don't think that's necessary to post here.
private int soldierID;
private int attack;
private int health;
public Soldier(int id){
this.soldierID = id;
Random random = new Random();
this.attack = random.nextInt(10) + 90;
this.health = random.nextInt(20) + 180;
}
#Override
public String toString() {
return "Soldier{" +
"soldierID=" + soldierID +
", attack=" + attack +
", health=" + health +
'}';
}
Main.class
it's perfectly fine and actually preferred to use a List instead of an array, because it's more comfortable to work with
this way it's even much easier to add them dynamically and use the iterator for ID
you can "report" in the creation cycle
This even shortens the method a bit, not that it's that important here.
public static void main(String[] args){
List<Soldier> soldiers = new ArrayList<>();
for(int i=0; i<5; i++){
Soldier newSoldier = new Soldier(i);
soldiers.add(newSoldier);
System.out.println(newSoldier.toString());
}
}
This way when you define the soldier IDs it's not from within the Soldier class but rather from something that is "observing" all the soldier classes and knows which is which.

Call method from main and pass Array from one class to another

I am facing a roadblock with static methods.
How do I call this method ?
How do Pass the array to another class , so I can edit the array.
Thank you
import java.util.Scanner;
class getArray {
public static void change(String x[]){
Scanner keyboard = new Scanner(System.in);
String dayName[] = {"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};
String[] day = new String[7];
for(int i=0;i<7;i++){
System.out.print(dayName[i]+ " ");
day[i] = keyboard.nextLine();
String str = (dayName[i]+" "+day[i]);
x[i] = str;
}
System.out.println(" ");
for(int j=0;j<7;j++){
System.out.println(x[j]);
}
}
}
class toParse{//would parse the integer out from String[x]
}
class averageTemp{//calculate average of weather
}
public class UniSeven2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
}
}
As pointed out in the comment, try not using static method. That said:
import java.util.Scanner;
class getArray {
public String change(String x[]){
Scanner keyboard = new Scanner(System.in);
String dayName[] = {"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};
String[] day = new String[7];
String str;
for(int i=0;i<7;i++){
System.out.print(dayName[i]+ " ");
day[i] = keyboard.nextLine();
str = (dayName[i]+" "+day[i]);
x[i] = str;
}
return str;
}
}
You can now access the "modified" String from whatever class you want.
Static methods belong to the Class itself, rather than the instances created by the class. Hence, when calling static method from outside it's class you would call it at the class level.
So, say we have the following..
MyClass {
public static void myStaticMethod(int[] myIntArray) {
//Do something
}
public void myNonStaticMehtod(int[] myIntArray) {
//Do something
}
}
When calling these methods from another class they would be called in the following ways..
Non static method
Because the non static method belongs to a given instance of a class, we must first make an instance of the class and call the method from the instance.
int[] myIntArray = new int[4];
MyClass myClass = new MyClass();
myClass.myNonStaticMethod(myIntArray);
Static method
The Static method belongs to the Class itself and should be called from the class level rather than from an instance of the class.
int[] myIntArray = new int[4];
MyClass.myStaticMethod(myIntArray);
On an unrelated note, the classes you are creating seem that they should be methods instead. Thinking in terms of object oriented programming, a class is the framework for an object, such as a car or person. The methods of that class should represent some action that these objects can perform. for example car.speedUp() speeds up a car, or car.getSpeed(), which gets the current speed of the car.
Hope this was helpful!
Edit: Added arrays as method parameters to help answer your second question.

non-Static method toString cannot be referenced from a static context

I'm trying to create a program that reads user input and stores it and then calculates the area of a polygon. When I try and compile it it gives me one error which is the one about .toString being non static.
import java.util.Scanner;
class regularpoTest {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean finished = false;
double s;
double n;
double area;
//starts loop to record data
do {
s =0;
n =0;
System.out.println("Enter the side length, or anything else to quit: ");
s = in.nextDouble();
in.nextLine();
if (in.hasNextDouble()) {
System.out.println("Enter number of sides");
n = in.nextDouble();
area = (s*s*n)/(4*Math.tan(Math.PI/n));
} else {
finished = true;
}
} while(!finished);
//This prints out the student details
System.out.println(regularpo.toString());
}
}
public class regularpo {
private double side;
private double numberOf;
private double area;
public regularpo(double side, double numberOf){
side = 0;
numberOf = 0;
area = 0;
}
public double getSide(){
return side;
}
public double getNumberOf(){
return numberOf;
}
public String toString(){
return ("area = " + area+ " side length "+side+ " number of sides "+numberOf);
}
}
You are trying to call a method of a class, when that method has been defined for (and only makes sense as) a method of an instance of that class. Maybe you mean to make an object of that class, and call its toString method, although I can't be sure from your code.
You can not access non-static methods by using classname.nonStaticMethodName. You need to instantiate your object using the new keyword. Basically, you create an instance of your object by regularpo r = new regularpo(2.0, 2.0). After that you can invoke r.toString();
Check out this SO-question for more info.
And this Oracle-tutorial explains class members well.
Suggestions:
1) Eliminate "regularpoTest". Just move "main()" into "regularpo".
2) Capitalize "RegularPo" (by convention, class names should start with a capital letter).
3) Make the RegularPo constructor actually save the initial values (not just set them to zero).
... and, most important ...
4) Your main should call RegularPo regularPo = new RegularPo (...).
Then reference object instance "regularPo".
Try to make a object of class regularpo and call toString over that object
regularpo obj=new regularpo();
obj.toString();
Also as per conventions a class name must start with Upper case,so name your class asRegularpo
toString() is a non static method in regularpro class , and we know that the non static belongs to an object so we need to create and object of same class and call it.
toString() is belongs to Object class so its non static method.
regularpo obj=new regularpo();
obj.toString();

non-static variable arr cannot be referenced from a static context [duplicate]

This question already has answers here:
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 9 years ago.
I've read the Oracle documents regarding scope and controlling access yet it just isn't sticking, so I'm assuming that my issue comes from my failure to understand... Anyways Here's my code. I'm trying to access the unique Player objects created in an array, and change their unique variables like their balances, using methods from the Player class. Any solutions and ESPECIALLY explanations are welcome!
public class Player
{
private int currentBal;
private String myName;
private int rollOne;
private int rollTwo;
private int rollTotal;
private int doublesCount;
private int currentPosition;
private int currentDoubles;
private int move;
private int moveMult;
private int newBal;
private boolean rollAgain;
private boolean inJail;
public Player(String userName, int changeInMoney)
{
myName = userName;
currentBal -= changeBalance(changeInMoney);
}
public int changeBalance(int changeInMoney){newBal -= changeInMoney; return newBal;}
public int viewBalance(){return currentBal;}
Here is my PlayerArray class.
public class PlayerArray
{
Scanner scan = new Scanner(System.in);
private int numbHuman;
private Player[] arr;
private String[] userName;
private int startingMoney;
public PlayerArray()
{
Scanner scan = new Scanner(System.in);
System.out.println("There will be 4 players, how many do you wish to be human? 0><4");
numbHuman = scan.nextInt();
while (numbHuman < 1 || numbHuman > 4)
{
System.out.println("Invalid entry, try again.");
numbHuman = scan.nextInt();
}
arr = new Player[numbHuman];
userName = new String[numbHuman];
startingMoney = 1500;
for(int i = 0; i < arr.length; i++)
{
System.out.println("Player " + (i + 1) + ", Please enter your first name:");
userName[i] = scan.next();
arr[i] = new Player(userName[i],startingMoney);
}
}
public Player[] getPlayerArray()
{
int charge = 500;
arr[0].changeBalance(charge);
System.out.println(arr[0].viewBalance()); //look here as example
return arr;
}
}
this is my player class, minus some methods I can't use till later. Bellow is my main method to call it,
import java.util.Scanner;
import java.util.Random;
public class Launcher
{
private Planet myTest;
private PlanetInfo myPlanetInfo;
private static Player[] arr;
public static void main(String[] args)
{
Launcher testLauncher = new Launcher();
PlayerArray myArray = new PlayerArray();
Pay myCharge = new Pay(); // continue work on charges
myArray.getPlayerArray();
//STILL TRYING TO GET BELLOW LINE TO WORK LAST NIGHT!!!
int testBal = arr[0].viewBalance(); //ERROR HERE
System.out.println("player 1's balance: " + testBal);
}
}
Error "Java.lang.NullPointerException: null"
Your main method is a static method. It actually exists before any object is created from your class, and thus cannot access instance variables and methods directly. You cannot access non static methods or variables from the same class unless you create an object for the class, i.e Launcher launcher = new Launcher();.
In this case, your player array arr is not static. You either need to make this static or create a Launcher object and access the variable from there. In the latter case, you will need to make the arr array public.
The first option requires you to change your player array declaration to private static Player arr;.
The second requires you to change the access of the arr array to public and access it like so: launcher.arr.
Regarding your second error, you need to either do this: arr = myArray.getPlayerArray();
or just access the array directly like this: myArray.getPlayerArray()[0] (for the first item in that array).
Variable 'Player[] arr' is instance variable, i.e. it should belongs to particular instance. Static method 'main' can't directly access an instance variable from the class it's in, because it doesn't have an explicit reference to any particular instance of the class (simply said at this point, you don't have an instance to whom your Player[] arr belongs).
Make your variables static, since main is a static method, you can't reference non-static methods.
so make your variables on top something like:
private static Player[] arr;
Since your Launcher has no instance none of its non static members exist. Static method main cannot access such - in this case your arr does not exist. You may want to make it static to make it work.
Read static and instance members

Unusual behavior of java program

I am new to Java and trying to learn it. I wrote two class as follows, and I expect to print as 1, 2, 3 but it prints 3, 3, 3. I read a java book about I couldn't figure out the above behavior and print 1, 2, 3.
public class Student{
private static int indexNumber = 0;
Student(){
indexNumber=indexNumber+1;
}
public void test() {
System.out.println(this.getIndexNumber());
}
public int getIndexNumber(){
return indexNumber;
}
}
public class College {
public static void main(String args[]){
Student student1 = new Student();
Student student2 = new Student();
Student student3 = new Student();
student1.test();
student2.test();
student3.test();
}
}
Can anyone help?
indexNumber is static, so it's "shared" between every instance of the class.
If you want a unique, incrementing ID, do the following:
static int nextID = 1;
int indexNumber;
Student() {
indexNumber = (nextID++);
}
This makes indexNumber an instance field, so that each Student gets its own copy. The static variable is used to keep track of the next ID to be assigned.
You get 3,3,3 because you have defined the variable indexNumber as static. So when instantiating three student objects the indexNumber gets value 3.
To increment define the indexNumber as instance variable and pass the value for it as parameter.
Your field is static.It will be shared by all objects.
private static int indexNumber = 0;
s1-------->indexNumber<------s2
^
|
|
|
s3
Instantiating each time,the constructors gets called,which increments the indexNumber by 1.
indexNumber is declared as static and its common to all objects. Hence you got 3,3,3
Static members are associated with the class, rather than with any object.
Static members are shared with all objects. You not indexed, you counted with your test.
Since you have declared the INDEX NUMBER as static, therefore it will be shared by every instance you create for the class. The answer which you were expecting will come in the case you remove the static keyword. That's why for all three objects you get the same value for index number. I hope it's clear to u now. Thank you.

Categories