Overlapping object in Java - java

I created 2 instances of my class player, but it seems as though the last instance created always takes over (overlaps?) All of the other objects, what is the issue here?
Here is the program:
public class Test
{
public static void main (String[] args)
{
Player player1 = new Player("Player 1");
Player player2 = new Player("Player 2");
Player player3 = new Player("Player 3");
System.out.println(player1.getName());
}
}
This is the output
Player 3
And this is the class
import java.util.Scanner;
import java.util.Random;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Player
{
public static String name;
public static int score;
public static Die[] dice = new Die[5];
public static JRadioButton[] rerollButton = new JRadioButton[5];
//----------------------------------------------------------------
// Constructor - initialize values
//----------------------------------------------------------------
public Player(String n)
{
name = n;
score = 0;
// initialize all dice and rerollButtons in their respective arrays
for (int i = 0; i < 5; i++) {
dice[i] = new Die();
rerollButton[i] = new JRadioButton();
}
}
public String getName()
{
return name;
}
}
I have tried to look for other similar questions but every one I found was far to complex for me to really understand.

The attributes in your Player class such as name,score, dice etc are defined as class variables(static) instead of instances variables(non-static). Class/static variables are shared by all the objects and hence you see that behavior. Try changing this:
public static String name;
to
public String name;
Make a wise decision what you need to declare as class variable and what as member variable. Learn more about instance and class members here:
http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html

That's because name is a static field in your Player class. And the static fields are shared by all the instances of a class. Therefore, you need to make the name as an instance variable, so that each instance will have their own copy of the it.
public String name; // Now each instance will have its own copy of name
and I'm guessing that the same needs to be done for score as well.
public int score;

public static String name;
should be
public String name;
or even better
private String name;

Because, your field is static,
public static String name;
To change the name with object make it as instance(non-static)
public String name;

Related

Access instance of a class in another class

I'm very new to coding and have a strict deadline for this assignment so I couldn't find an explanation I understood very well so I am asking here.
I am makign an instance of my Pokemon class in a another class for my main game. I however need info on how many times a pokemon was defeated in my catch pokemon class as I want a user to only be able to catch a pokemon if they've beat it a certain amount of times. I have no clue how to do this however.
This is how the class is used if it is of any help:
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Battle extends JFrame{
public Pokemon fire = new Pokemon("Charmander", "Fire");
public Pokemon water = new Pokemon("Squirtle", "Water");
public Pokemon plant = new Pokemon("Bulbasaur", "Grass");
public Pokemon ground = new Pokemon("X", "Ground");
I have tried something like Battle.pikachu.toString() in the main class to just test how to access it because that is what someone else told me but the battle part confuses me as I don't think it is actually referrign to anything when in my main class.
You should not define your Pokemon inside a Battle. You should instead pass your Pokemon into this Battle class.
So you should instead define your Pokemon in your Main class:
public class Main {
// Your functions...
private ArrayList<Pokemon> getMyPokemons() {
ArrayList<Pokemon> myPokemonList = new ArrayList<>();
Pokemon fire = new Pokemon("Charmander", "Fire");
Pokemon water = new Pokemon("Squirtle", "Water");
Pokemon plant = new Pokemon("Bulbasaur", "Grass");
Pokemon ground = new Pokemon("X", "Ground");
myPokemonList.add(fire);
myPokemonList.add(water);
myPokemonList.add(plant);
myPokemonList.add(ground);
return myPokemonList;
}
private void triggerBattle() {
ArrayList<Pokemon> myPokemonList = getMyPokemons();
Battle battle = new Battle(myPokemonList);
}
}
And in your Battle class,
public class Battle extends JFrame {
private ArrayList<Pokemon> myPokemons;
// Create constructor to receive your Pokemon
public Battle(ArrayList<Pokemon> myPokemons) {
this.myPokemons = myPokemons;
}
// And in other functions within this class, you can access
// myPokemons list
}
And of course if you need more information related to the Pokemon, you need to refer to #Boycpu suggestion and add more attributes to your Pokemon class.
Do you mean?
public class Pokemon {
private String name;
private String group;
private int defeatedTimes;
public Pokemon(String name, String group, int defeatedTimes) {
this.name = name;
this.pass = group;
this.defeatedTimes = defeatedTimes;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public int getDefeatedTimes() {
return defeatedTimes;
}
public void setDefeatedTimes(int defeatedTimes) {
this.defeatedTimes = defeatedTimes;
}
}

How can I assign variables to my class constructor if they are static?

I'm running into a problem where I am using a method to take in user data and the method is to return an object. The problem is whenever I get to assigning the inputted values to the class constructor I am met with an error message stating, "non-static variable this cannot be referenced from a static context." I am aware that my methods are declared using public static [return value], which is ultimately leading to this issue. I have to keep the methods as static, though, as a part of this project. That leaves me somehow manipulating the class or class constructor, but I'm not certain as to how to do that.
This is the class and class constructor:
public class Project1 {
public class Student {
String name;
String ID;
float GPA;
int creditHours;
double tuitionCost;
public static Student (String name, String ID, float GPA, int creditHours, double tuitionCost) {
this.name = name;
this.ID = ID;
this.GPA = GPA;
this.creditHours = creditHours;
this.tuitionCost = tuitionCost;
}
}
This is how I am attempting to assign the user inputted data to the class constructor.
Student ret = new Student();
ret.name = name;
ret.ID = ID;
ret.GPA = GPA;
ret.creditHours = creditHours;
ret.tuitionCost = tuitionCost;
return ret;
How can I assign the values I have read in from the user (using Scanner) to the class constructor if the method in which they are read in is static?
Note: I'm new to Java, so some of my jargon may be a bit off.
static constructors are not allowed in Java
Then your Student class is not static, it means that it could be created only with parent Project1.
public class Project1 {
public class Student {
public Student() {
}
}
public static void main(String... args) {
Project1 project1 = new Project1();
Student student = project1.new Student();
}
}
You have to make Student class statis if you want to use Student class without Project1.
public class Project1 {
public static class Student {
public Student() {
}
}
public static void main(String... args) {
Student student = new Project1.Student();
}
}
The title of the question seems very simple but the description is quite confusing:
How can I assign variables to my class constructor if they are static?
As per my understanding, if you want to assign some static variables in your constructor then in the first place you should have static variables present in your class which seems to be missing.BUT there is something more which you are missing.
There are no static constructors in java, you might need to refer:
Why a constructor cannot be static or Can we define static constructors
I doubt the code snippet you posted would compile because the compiler should throw an error as you can never have a static constructor in a class.
Now coming to your actual issue:
How can I assign the values I have read in from the user (using Scanner) to the class constructor if the method in which they are read in is static?
I modified your code little bit to solve your issue:
package com.sopra.banking.compliance.report.backend.common.bean;
import java.util.Scanner;
public class Test
{
public static class Student
{
String name;
public Student()
{
}
public Student(String name)
{
Student student = readValues();
this.name = student.name;
}
static Student readValues()
{
Scanner sc = new Scanner(System.in);
Student student = new Student();
String name = sc.next();
student.name = name;
return student;
}
}
}
As a side note, you were having an inner class and if you want to define a static method in an inner class then you need to make that class as static.
Constructors cannot be static. Methods can.
If you need a static method that returns a Student, it would look like
public static Student buildStudent(String name, String ID, float GPA, int creditHours, double tuitionCost) {
Student ret = new Student();
ret.name = name;
ret.ID = ID;
ret.GPA = GPA;
ret.creditHours = creditHours;
ret.tuitionCost = tuitionCost;
return ret;
}
However, using an actual constructor is arguably more straightforward for object creation

passing an object(s) to be serialised java

I have scoured many web pages trying to solve this issue, but I am struggling. I don't want someone to fix it for me, I just want someone to point me in the right direction please :). My problem is two-fold, I have an array of objects,I want to pass each object to my Teams class, so that the team name can be saved. This code doesn't compile, error concerns line: "Teams(MainmenuTest[]) teamName() {"
error is '.class' expected
followed by
';' expected
I can get serialisation to work when the objects are created in my Teams class, (if I comment out the code for passing objects), and it does create a .ser file in the directory I have specified.
Here are the snippets of code:
public class Teams implements java.io.Serializable{
public Teams(){
// constructor
MainmenuTest[] teamName;
Teams(MainmenuTest[]) teamName() {
this.teamName = teamName;
}
}
public String name;
public String address;
public transient int SSN;
public int number;
public void mailCheck()
{
System.out.println("Mailing a check to " + name + " " + address);
}
} // end Teams class
public class premierLeagueClubs{
public String club;
Teams[] teamName = new Teams[19];
premierLeagueClubs f = new premierLeagueClubs();
Teams t = new Teams(f,teamName);
public String arsenal(){
teamName[0].club = "Arsenal";
System.out.println("You are the new manager of" + club);
return club;
} // end method arsenal
Here is the MainmenuTest code:
import java.util.InputMismatchException;
import java.util.Scanner;
import java.io.*;
import java.util.Arrays;
public class MainmenuTest extends premierLeagueClubs{
int choice;
public MainmenuTest(){
//constructor
}
public static void main(String args[]){
MainmenuTest team = new MainmenuTest();
team.getInput();
} // end main method

Cannot reference method from a static context error when attempting to output contents of linked list in instance class

I'm a beginner Java programmer and I'm trying to check whether I've successfully copied an instance of Person in a linked list stored in class Clients to the linked list called passengers inside an instance of class Boat by having Boat print out the contents of it's linked list.
I am using the method givePassengers() from class Boat to have the Boat class printout it's passengers linked list contents.
However when I attempt to do so I am encountering the error 'non-static method givePassengers() cannot be referenced from a static context' and I'm not sure what to write to solve that problem. I've listed what I believe to be the problem code below. Any assistance is greatly appreciated.
I have marked important code with '// !!'
This is the class that contains the linked list of boats
import java.io.*;
import java.util.*;
public class Base implements Serializable
{ private LinkedList<Boat> boats = new LinkedList<Boat>();
private Clients clients = new Clients();
public void setup() // !! Here are the instances of the boat class
{ boats.add(new Boat(1, "Ed", 2));
boats.add(new Boat(2, "Fred", 7));
boats.add(new Boat(3, "Freda", 5)); }
public void showpassengers() {
for (Boat i: boats) `// !! The for each loop cycles through each boat to check for passengers`
Boat.givePassengers(); // !! This line produces the error
}
Here is the boat class
import java.io.*;
import java.util.*;
public class Boat implements Serializable
{ private int id;
private String pilot;
private int stops;
private LinkedList<Person> passengers = new LinkedList<Person>();
private double rate = 10.00;
public int scannableId = this.id;
public Boat(int id, String pilot, int stops)
{ this.id = id;
this.pilot = pilot;
this.stops = stops; }
public void givePassengers () {
System.out.println(passengers); // !! this line is supposed to print out the contents of the boat classes' linked list so I can check that it worked.
}
Here is the Person class
import java.io.*;
import java.text.*;
public class Person implements Serializable
{ private String name;
private int id;
private double cash = 100.00;
private int start = 0;
private int end = 0;
private double charge = 0;
public Person(String name, int id)
{ this.name = name;
this.id = id + 100; }
}
Here is the class that contains the linked list of Person
import java.io.*;
import java.util.*;
public class Clients implements Serializable
{ private LinkedList<Person> clients = new LinkedList<Person>();
private int id = 1;
public Clients() `// !! Here are the instances of Person in the class clients`
{ clients.add(new Person("Homer", id++));
clients.add(new Person("Marge", id++));
}
)
And here is the root class if that helps
import java.io.*;
public class Root
{ public Root() {
new Base();
}
public static void main(String[] args)
{ new Root(); }
private Base base;
}
Your problem is here:
for (Boat i: boats)
Boat.givePassengers(); // !! This line produces the error
You need to say i.givePassengers() to reference the specific instance of the class Boat. There's a good primer on the difference between classes and objects here.
You can't call givePassengers() statically from Boat, it's not a static method. You need to call it from an instance of Boat. Replace Boat.givePassengers(); with i.givePassengers(); within your foreach loop. This will cause the currently selected Boat instance to run givePassengers().

Why every elements of an array changes continuously in Java?

I wanted to create array of an objects. There will be many user objects and I want to keep these user objects in an array. I have a class called Data. I tried and searched a lot but couldn't find the solution. When user enters a new name the names of all objects changes with the given name, and at last when i print all the names it prints the last entered name for several times. Here is my code, it will be much helpful you to understand:
testClass.java
public class testClass {
public static void main(String[] args) {
mainScreen();
}
public static void mainScreen(){
Scanner scan = new Scanner(System.in);
System.out.println("1) Add a new user:");
int choice = scan.nextInt();
switch(choice){
case 1:
System.out.println("Enter name:");
String name = scan.next();
Data.users[Data.count] = new Data(name);
mainScreen();
break;
case 2:
for(int i =0; i<=Data.count; i++){
System.out.println(Data.users[i].name);
}
break;
}
}
}
Data.java
public class Data {
public static Data[] users = new Data[600];
public static String name;
public static int count = 0;
public Data(String name) {
users[count].name = name;
count++;
}
}
I want that every object will have unique name, id, phone number, etc.. Does anybody have a suggestion for me?
Because name is static field of your Data class like count and users.
Remove static modifier from name field.
One solution is to remove the static modifier from name field in Data:
public static Data[] users = new Data[600];
public static int count = 0;
public String name;
public Data(String name) {
this.name = name;
Data.count++;
}
Also modify your for loop, because you'll get a NullPointerException, remove equals from the condition:
for(int i =0; i<Data.count; i++){
First you need to correct your Object structure
you have defined a class Data which contains a static array of Data Class itself
I prefer to have data class as:
class Data {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
create a array of Data class in your testClass
create new Data Object for each input and assign the name to the newly created Object using setName
maintain the count variable in testClass. Increment it each time when you get a new input and use count variable to assign newly created Object to the Data array

Categories

Resources