I'm a bit confused
I created a class called person, that has an age and name attributes (and get set methods).
Then in another class I want to create an array of persons , where each person has a different age and name.
But some how in the end all of my persons end up with the last name and age.
If I manually create them then it is ok, but with a for loop I've got that problem.
What should I do to get different persons?
Here is the code of the person class:
public class person {
static String name;
static int age;
public person() {
name="name";
age=0;
}
public static String getName() {
return name;
}
public static void setName(String name) {
person.name = name;
}
public static int getAge() {
return age;
}
public static void setAge(int age) {
person.age = age;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
And here is the code where I want to create my array/matrix:
public class array {
static person[][] a;
public static void main(String[] args) {
a=new person[3][3];
//manual created person
person first=new person();
person second=new person();
person third=new person();
first.setAge(12);
first.setName("first");
second.setAge(20);
second.setName("second");
third.setAge(40);
third.setName("third");
//automatic (here I get the disired effect)
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length; j++) {
a[i][j]=new person();
a[i][j].setAge(10+j);
a[i][j].setName("Alia"+i);
System.out.println(i+" "+j+" "+a[i][j].getName()+" "+a[i][j].getAge());
}
}
// a[0][0]=first;
// a[0][1]=second;
// a[1][2]=third;
// System.out.println(a[0][0].getName()+" "+a[0][0].getAge());
//for checking , and it doesnt work anymore
System.out.println(a[0][0].getName()+" "+a[0][0].getAge());
// for (int i = 0; i < a.length; i++) {
// for (int j = 0; j < a.length; j++) {
// System.out.println(i+" "+j+" "+a[i][j].getName()+" "+a[i][j].getAge());
// }
//
// }
getname();
}
private static void getname() {
System.err.println("get name function");
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length; j++) {
System.out.println(a[i][j].getName());
}
}
}
}
Remove the static keyword from the persons attributes. If it is static it is used by all instances (all person objects).
But I would do it like this:
public class Person {
public final String name;
public final int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return name + " (" + age + ")";
}
public static void main(String... args) {
List<Person> people = new LinkedList<Person>();
people.add(new Person("David", 28));
people.add(new Person("Andreas", 27));
System.out.println(people);
}
}
Yes, your attributes are declared static. A static attribute "belongs" to the class, not the instances, so all instances see the same String and int. You should be fine just removing the static from everything but main(). Then, new Person() will allocate new separate variables for everybody.
Problem is the static fields. Last values assigned to them would be reflected in all the object.
Related
import java.util.ArrayList;
class BryanList{
public static void main (String [] args)
{
ArrayList<String> alist=new ArrayList<String>();
alist.add("Bryan");
alist.add("18");
alist.add("Chicken Rice");
for (int i = 0; i <= alist.size(); i++) {
System.out.println ("My Name: "+alist.get(i));
System.out.println ("Age: "+alist.get(i));
System.out.println ("Favourite food: "+alist.get(i));
}
}
}
How come its not just displaying just one output instead there's 3 of the same output? Does anyone have any solution for this? Thanks.
If you want one time output then use generics class structure.
Create one class which you want to save records.
class Menu {
public int age;
public String name;
public String favFood;
}
You can create getter/setter method if you need. Otherwise just declare variables with public keyword.
Create one ArrayList which will store object of Menu class.
ArrayList<Menu> alist = new ArrayList<Menu>();
Menu menu = new Menu();
menu.name = "Bryan";
menu.age = 18;
menu.favFood = "Chicken Rice";
alist.add(menu);
Print output
for (int i = 0; i <= alist.size(); i++) {
Menu menu = alist.get(i);
System.out.println("My Name: " + menu.name);
System.out.println("Age: " + menu.age);
System.out.println("Favourite food: " + menu.favFood);
}
I updated your class with your requirement, please check.
class BryanList {
public static void main(String[] args) {
ArrayList<Menu> alist = new ArrayList<Menu>();
Menu menu = new Menu();
menu.name = "Bryan";
menu.age = 18;
menu.favFood = "Chicken Rice";
alist.add(menu);
for (int i = 0; i <= alist.size(); i++) {
Menu menu = alist.get(i);
System.out.println("My Name: " + menu.name);
System.out.println("Age: " + menu.age);
System.out.println("Favourite food: " + menu.favFood);
}
}
}
class Menu {
public int age;
public String name;
public String favFood;
}
Happy coding :)
Your loop check is happening on alist.size() which is in your case 3.
Now, in each iteration, it's printing alist.get(i) 3 times.
Suggestion:
Use POJO and add it to your list.
public class Person{
String name;
int age;
String favFood;
public getName(){
return name;
}
public getAge(){
return age;
}
public getFavFood(){
return favFood;
}
public setName(String name){
this.name = name;
}
public setName(int age){
this.age = age;
}
public setName(String favFood){
this.favFood = favFood;
}
}
And now, your code will work with simple modification.
public static void main (String [] args){
ArrayList<String> alist=new ArrayList<String>();
Person person = new Person();
person.setName("Bryan");
person.setAge(18);
person.setFavFood("Chicken Rice");
// If you want multiple person to add, you need to use loops, and that way you can keep creating person objects and add them to list.
// Suggesting, use separate method for that logic.
alist.add(person);
for (int i = 0; i <= alist.size(); i++) {
Person p = alist.get(i);
System.out.println ("My Name: "+ p.getName());
System.out.println ("Age: "+ p.getAge());
System.out.println ("Favourite food: "+ p.getFavFood());
}
}
Because your printing codes in a For loop. And loop is running 3 three times
alist.size()
means 3, you have 3 item in that list.
This can be your object class:
public class Table {
int age;
String name;
String food;
public Table(int age, String name, String food) {
this.age = age;
this.name = name;
this.food = food;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getFood() {
return food;
}
public void setFood(String food) {
this.food = food;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And fill arraylist with your object:
public static void main(String[] args) {
ArrayList<Table> alist = new ArrayList<>();
// this is how you fill
alist.add(new Table(18, "Bryan", "Rice");
for (int i = 0; i <= alist.size(); i++) {
System.out.println("AGE: " + alist.get(i).age);
//other stuff
}
}
import java.util.ArrayList;
public class HelloWorld {
public static void main(String []args) {
ArrayList<String> alist_name=new ArrayList<String>();
ArrayList<String> alist_value=new ArrayList<String>();
alist_name.add("My Name: ");
alist_name.add("Age: ");
alist_name.add("Favourite food: ");
alist_value.add("Bryan");
alist_value.add("18");
alist_value.add("Chicken Rice");
for (int i = 0; i < alist_name.size(); i++) {
System.out.println (alist_name.get(i)+alist_value.get(i));
}
}
}
I have an arraylist of person ArrayList<Person>. Each person get it's name and age in random. In that ArrayList of Person I filtered out those age 18 using a lambda expression.
My question is how can I create a Thread for each filtered Person of the Arraylist.
My code:
public class Person implements Runnable
{
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void run() {
// to fill up later
}
}
public class Main {
private static int nameCount = 1;
public static List<Person> list;
public static void main(String[] args) {
list = new ArrayList<Person>();
for (int i = 0; i < 5; i++) {
list.add(new Person(getPersonName(), getPersonAge());
}
list.removeIf(p -> p.getage().equals(18));
for (Person person : list) {
System.out.println(persion);
}
}
public static String getPersonName() {
String nameto = "PERSON" + String.valueOf(nameCount);
nameCount++;
return nameto;
}
public static int getPersonAge() {
Random ran = new Random();
int ageperson = ran.nextInt(25) + 1;
return ageperson;
}
//how to make an instance of Thread after filtering the person
}
I agree with James Large that the idea of Person implements Runnable sounds very strange.
But any way to implement some logic for each item in the list You can use StreamAPI and method foreach, I also recommend to use method filter
So the result will be the next:
list.stream()
.filter(person -> person.getage() == 18)
.forEach(person -> new Thread(person).start());
I am trying to write a program where I ask to the user how many persons he wants to implement in this world. Afterwards, I would like as many person objects as the user answered. I defined a person class with a person constructor containing all person variables ( + getters/setters). After this, I tried to create a loop to assign values to my variables (most of them happen random). Currently, I set the number of instances I want to create to 20 (arbitrary).
This is my person class
public class Person implements Item {
public static final int MAX_AGE = 70;
public static final int MAX_SEX_APPEAL = 10;
public static final int MAX_AGRESSION_LEVEL = 10;
public static final int MAX_STRENGTH = 10;
private int id;
private int age;
private boolean gender;
private int sexAppeal;
private int agressionLevel;
private int strength;
private boolean isAlive;
public Person (int id, int age, boolean gender, int sexAppeal, int agressionLevel, int strength, boolean isAlive){
this.setId(id);
this.setAge(age);
this.setGender(gender);
this.setSexAppeal(sexAppeal);
this.setAgressionLevel(agressionLevel);
this.setStrength(strength);
this.setAlive(isAlive);
}
void getBorn () {
isAlive = true;
age = 0;
// a new people is born
// age = 0
// other variables: random
}
void die () {
isAlive = false;
// people die when they reach the max age
// people die when being on the same cell as vulcanos
// people can be murdered
// setAlive = false
}
void murder () {
// when 2 people with min agression level on the same land ==> weakest one dies
}
void move () {
// method to make people move
// random (only to adjucant fields)
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isGender() {
return gender;
}
public void setGender(boolean gender) {
this.gender = gender;
}
public int getSexAppeal() {
return sexAppeal;
}
public void setSexAppeal(int sexAppeal) {
this.sexAppeal = sexAppeal;
}
public int getAgressionLevel() {
return agressionLevel;
}
public void setAgressionLevel(int agressionLevel) {
this.agressionLevel = agressionLevel;
}
public int getStrength() {
return strength;
}
public void setStrength(int strength) {
this.strength = strength;
}
public boolean isAlive() {
return isAlive;
}
public void setAlive(boolean isAlive) {
this.isAlive = isAlive;
}
}
And this is my "test class" where I try to create 20 instances :
import java.util.concurrent.ThreadLocalRandom;
public class test {
public static void main(String[] args) {
for (int i = 0; i < 20; i ++) {
Person person(i) = new Person();
person.setId(i);
person.setAge(ThreadLocalRandom.current().nextInt(0, Person.MAX_AGE + 1));
person.setGender((Math.random() < 0.5));
person.setSexAppeal(ThreadLocalRandom.current().nextInt(0, Person.MAX_SEX_APPEAL + 1));
person.setAgressionLevel(ThreadLocalRandom.current().nextInt(0, Person.MAX_SEX_APPEAL + 1));
person.setStrength(ThreadLocalRandom.current().nextInt(0, Person.MAX_SEX_APPEAL + 1));
person.setAlive(true);
}
}
}
However, I am getting the following error at this line
Person person(i) = new Person();
The constructor Person () is undefined
Type mismatch: cannot convert from Person to int
I understand those errors but I don't know another way to become to the result I want to achieve
You should make a list and just add the created persons to it.
public class test {
public static void main(String[] args) {
List<Person> persons = new ArrayList<>(); // create a list to store the generated persons
for (int i = 0; i < 20; i++) {
Person person = new Person(); // generate a person
person.setId(i);
person.setAge(ThreadLocalRandom.current().nextInt(0, Person.MAX_AGE + 1));
person.setGender((Math.random() < 0.5));
person.setSexAppeal(ThreadLocalRandom.current().nextInt(0, Person.MAX_SEX_APPEAL + 1));
person.setAgressionLevel(ThreadLocalRandom.current().nextInt(0, Person.MAX_SEX_APPEAL + 1));
person.setStrength(ThreadLocalRandom.current().nextInt(0, Person.MAX_SEX_APPEAL + 1));
person.setAlive(true);
persons.add(person); /// add the generated person to the list
}
}
}
Also if you want to call the Person constructor without parameters the class must have a constructor that takes no parameters.
public Person() {}
In my code below, I am experiencing a problem I am unable to get around... when I add a class Person object to an array, it appears to add fine, however when I attempt to print out that object value form a specified array position, it outputs "null."
Here is the code
import java.util.Scanner;
import java.util.Arrays;
import java.lang.String;
public class Main
{
public static void main(String[] args)
{
int ARRAY_LENGTH = 2;
Scanner in = new Scanner(System.in);
Person[] Persons;
Persons = new Person[ARRAY_LENGTH];
for (int i = 0; i < ARRAY_LENGTH; i++)
{
System.out.println("Enter a name to add to the array: ");
Persons[i] = new Person(in.next());
System.out.println(Persons[i]);
}
Arrays.sort(Persons);
for (int i = 0; i < ARRAY_LENGTH; i++)
{
System.out.println(Persons[i]);
}
}
}
&
public class Person implements Comparable<Person>
{
private String name;
public Person (String aName)
{
String name = aName;
}
public String getName()
{
return name;
}
public int compareTo(Person o)
{
Person other = (Person) o;
if (this.name.equals(o.name))
{
return 0;
}
if (this.name.compareTo(o.name) < 0)
{
return -1;
}
return 1;
}
#Override
public String toString()
{
return name;
}
}
No, it hasn't added null to the array. It's put a reference to a Person object in the array, and when you call toString() on that Person object, it's returning the value of the name field... which is always null, because of this constructor:
public Person (String aName)
{
String name = aName;
}
That isn't assigning a value to the name field - it's declaring a local variable called name. (I'd expect a decent IDE to issue a warning about that.)
You want:
public Person (String aName)
{
name = aName;
}
The constructor
public Person (String aName)
{
String name = aName;
}
stores the name in a local variable.
Change this to
public Person (String aName)
{
this.name = aName;
}
The constructor is wrong
public Person (String aName)
{
String name = aName;
}
it is creating a new variable instead of assigning the field properly.
Try removing the type declaration:
public Person (String aName)
{
name = aName;
}
here is my code. i keep getting a nullpointerexception in my sort and print method, it starts on the line with the for loop with allAnimals.length. I think the array allAnimal in the class, isnt filled in getData as it should. allAnimal in getData method isnt being treated as allAnimal in the class. Basically all other methods still think allAnimal is null. I am no master in java so if someone could please tell me how to fix this error, or give me tips on how to avoid it I would greatly appreciate it.
public class Animal {
//data fields
private String name;
private int birthYear;
private String species;
private float balance;
private String ownersName;
static Animal[] allAnimal;
public Animal(){
//no-arg constructor
}
public Animal(String name, int birthYear, String species, float balance, String ownersName){
// constructor builds animal template
this.name = name;
this.birthYear = birthYear;
this.species = species;
this.balance = balance;
this.ownersName = ownersName;
}
//set and get for name
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
//set and get for birth year
public int getBirthYear() {
return birthYear;
}
public void setBirthYear(int birthYear) {
this.birthYear = birthYear;
}
//set and get for species
public String getSpecies() {
return species;
}
public void setSpecies(String species) {
this.species = species;
}
//set and get for balance
public float getBalance() {
return balance;
}
public void setBalance(float balance) {
this.balance = balance;
}
//set and get for owner
public String getOwnersName() {
return ownersName;
}
public void setOwnersName(String ownersName) {
this.ownersName = ownersName;
}
public static void getData(){
System.out.println("How many animals are in this report? ");
Scanner kb = new Scanner(System.in);
int length = kb.nextInt();
Animal[] allAnimal = new Animal[length];
System.out.println("input: animal name, birth year, species, bill balance and owner's name.");
//fill array of objects with data
int i;
for(i = 0; i < allAnimal.length; i++){
allAnimal[i] = new Animal(kb.next(), kb.nextInt(), kb.next(), kb.nextFloat(), kb.next());
}
}//end getData
public static void sortData(Animal[] allAnimal){
Animal temp;
int i,j;
for(i = 0; i < allAnimal.length; i++){
for(j = i + 1; j < allAnimal.length; j++){
if(allAnimal[i].getBalance() > allAnimal[j].getBalance() ){ //swap big with small
temp = allAnimal[j];
allAnimal[j] = allAnimal[i];
allAnimal[i] = temp;
}
}
}
}//end sortData
public static void printData(Animal[] allAnimal){
int i;
for(i = 0; i < allAnimal.length; i++){
System.out.println("Pet Name: " + allAnimal[i].getName() + " Birth year: " +
allAnimal[i].getBirthYear() + " Species: " + allAnimal[i].getSpecies() +
" Balance due: " + allAnimal[i].getBalance() + " Owner: " + allAnimal[i].getOwnersName());
}
}
public static void main(String[] args){
getData();
sortData(allAnimal);
printData(allAnimal);
}//end main
}//end class
You have two variables named allAnimal:
static Animal[] allAnimal;
Animal[] allAnimal = new Animal[length];
You initialize one and then use the other (which is still null).
In getData(), change
Animal[] allAnimal = new Animal[length];
to
allAnimal = new Animal[length];
There could be other problems, I didn't look too closely.
You are creating local variable Animal[] allAnimal within getData() method that caused the problem.
Problem here
public static void getData(){
Animal[] allAnimal = new Animal[length]; //here is the problem
}
fix it like below.
public static void getData(){
allAnimal = new Animal[length]; //here is the fix
}
You have only declared AllAnimal at the class level :
static Animal[] allAnimal;
Now, in your method getData() you have declared and initialized a local variable allAnimal. Note that it has nothing to do with the one at class level.
Animal[] allAnimal = new Animal[length];
In other methods you are trying to use class level allAnimal which will throw a null pointer inless it is initiatlized.
for(i = 0; i < allAnimal.length; i++){