Problem in arranging contents of Class in JAVA - java

I have some classes and I'm trying to fill the objects of this class. Here is what i've tried. (Question is at the below)
public class Team
{
private String clubName;
private String preName;
private ArrayList<String> branches;
public Team(String clubName, String preName)
{
this.clubName = clubName;
this.preName = preName;
branches = new ArrayList<String>();
}
public Team() {
// TODO Auto-generated constructor stub
}
public String getClubName() { return clubName; }
public String getPreName() { return preName; }
public ArrayList<String> getBranches() { return branches; }
public void setClubName(String clubName) { this.clubName = clubName; }
public void setPreName(String preName) { this.preName = preName; }
public void setBranches(ArrayList<String> branches) { this.branches = branches; }
}
public class Branch
{
private ArrayList<Player> players = new ArrayList<Player>();
String brName;
public Branch() {}
public void setBr(String brName){this.brName = brName;}
public String getBr(){return brName;}
public ArrayList<Player> getPlayers() { return players; }
public void setPlayers(ArrayList<Player> players) { this.players = players; }
}
//TEST CLASS
public class test {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
String a,b,c;
String q = "q";
int brCount = 0, tCount = 0;
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
Team[] teams = new Team[30];
Branch[] myBranch = new Branch[30];
for(int z = 0 ; z <30 ;z++)
{
teams[z] = new Team();
myBranch[z] = new Branch();
}
ArrayList<String> tmp = new ArrayList<String>();
int k = 0;
int secim = Integer.parseInt(input.readLine());
while(secim != 0)
{
if(k!=0)
secim = Integer.parseInt(input.readLine());
k++;
switch(secim)
{
case 1 :
brCount = 0;
a = input.readLine();
teams[tCount].setClubName(a);
b= input.readLine();
teams[tCount].setPreName(b);
c = input.readLine();
while(c.equals(q) == false)
{
if(brCount != 0)
{c = input.readLine();}
if(c.equals(q)== false){
myBranch[brCount].brName = c;
tmp.add(myBranch[brCount].brName);
brCount++;
}
System.out.println(brCount);
}
teams[tCount].setBranches(tmp);
for(int i=0;i<=tCount;i++ ){
System.out.print("a :" + teams[i].getClubName()+ " " + teams[i].getPreName()+ " ");
System.out.println(teams[i].getBranches());}
tCount++;
break;
case 2:
String src = input.readLine();//LATERRRRRRRr
}
}
}
}
The problem is one of my class elements. I have an arraylist as an element of a class.
When i enter:
AAA as preName
BBB as clubName
c
d
e as Branches
Then as a second element
www as preName
GGG as clubName
a
b as branches
The result is coming like:
AAA BBB c,d,e,a,b
GGG www c,d,e,a,b
Which means ArrayList part of the class is putting it on and on. I tried to use clear() method but caused problems. Any ideas.

The problem is that the two Team objects are sharing the same reference to a single ArrayList<String>. There are many ways to solve this, but one way is to let Team manage its own List<Branch>, and it should only expose an add(Branch) instead of setBranches(List<Branch>). This would hide most information from the client, exposing only the most essential functionalities, which is a good thing.
Note also that I use the interface List<Branch> instead of ArrayList<Branch> (or ArrayList<String>). This is in accordance with Effective Java 2nd Edition, Item 52: Refer to objects by their interfaces.
I also recommend using java.util.Scanner for the I/O. Look at the API for examples, and there are many questions on stackoverflow about it as well. It'd make the code much simpler.

You need to copy lists in setters, otherwise you are using the same list (tmp) everywhere, so no wonder it has the same contents:
public void setBranches(List<String> branches) {
this.branches = new ArrayList<String>(branches);
}
public void setPlayers(List<Player> players) {
this.players = new ArrayList<Player>(players);
}
Theoretically, you also need to copy or wrap it in getters, but that's another story.

Related

How can I use the indexOf() function to find an object with a certain property

I have an object, Pet, and one of the functions is to retrieve its name.
public class pet{
private String petName;
private int petAge;
public pet(String name, int age){
petName = name;
petAge = age;
}
public String getName(){
return petName;
}
public int getAge(){
return petAge;
}
}
I then have an ArrayList which holds a collection of pets as shown in the code below:
import java.util.ArrayList;
pet Dog = new pet("Orio", 2);
pet Cat = new pet("Kathy", 4);
pet Lion = new pet("Usumba", 6);
ArrayList<pet> pets = new ArrayList<>();
pets.add(Dog);
pets.add(Cat);
pets.add(Lion;
I was wondering how I could retrieve the index in the ArrayList or the object that has the name I need. So if I wanted to find out how old Usumba was, how would I do this?
Note: This is not my actual piece of code, it's just used so that I can better explain my problem.
Edit 1
So far, I have the following but I was wondering if there was a better or more efficient way
public int getPetAge(String petName){
int petAge= 0;
for (pet currentPet : pets) {
if (currentPet.getName() == petName){
petAge = currentPet.getAge();
break;
}
}
return petAge;
}
You can't use indexOf() for this purpose, unless you abuse the purpose of the equals() method.
Use a for loop over an int variable that iterates from 0 to the length of the List.
Inside the loop, compare the name if the ith element, and if it's equal to you search term, you've found it.
Something like this:
int index = -1;
for (int i = 0; i < pets.length; i++) {
if (pets.get(i).getName().equals(searchName)) {
index = i;
break;
}
}
// index now holds the found index, or -1 if not found
If you just want to find the object, you don't need the index:
pet found = null;
for (pet p : pets) {
if (p.getName().equals(searchName)) {
found = p;
break;
}
}
// found is now something or null if not found
As the others already stated, you cannot use indexOf() for this directly. It would be possible in certain situations (lambdas, rewriting hashCode/equals etc), but that is usually a bad idea because it would abuse another concept.
Here's a few examples of how we can do that in modern Java:
(as the index topic has already been answered quite well, this only handles direct Object return)
package stackoverflow.filterstuff;
import java.util.ArrayList;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.Predicate;
public class FilterStuff {
public static void main(final String[] args) {
final Pet dog = new Pet("Orio", 2); // again, naming conventions: variable names start with lowercase letters
final Pet cat = new Pet("Kathy", 4);
final Pet lion = new Pet("Usumba", 6);
final ArrayList<Pet> pets = new ArrayList<>();
pets.add(dog);
pets.add(cat);
pets.add(lion);
try {
simpleOldLoop(pets);
} catch (final Exception e) {
e.printStackTrace(System.out);
}
try {
simpleLoopWithLambda(pets);
} catch (final Exception e) {
e.printStackTrace(System.out);
}
try {
filterStreams(pets);
} catch (final Exception e) {
e.printStackTrace(System.out);
}
try {
filterStreamsWithLambda(pets);
} catch (final Exception e) {
e.printStackTrace(System.out);
}
}
private static void simpleOldLoop(final ArrayList<Pet> pPets) {
System.out.println("\nFilterStuff.simpleOldLoop()");
System.out.println("Pet named 'Kathy': " + filterPet_simpleOldLoop(pPets, "Kathy"));
System.out.println("Pet named 'Hans': " + filterPet_simpleOldLoop(pPets, "Hans"));
}
private static Pet filterPet_simpleOldLoop(final ArrayList<Pet> pPets, final String pName) {
if (pPets == null) return null;
for (final Pet pet : pPets) {
if (pet == null) continue;
if (Objects.equals(pet.getName(), pName)) return pet;
}
return null;
}
private static void simpleLoopWithLambda(final ArrayList<Pet> pPets) {
System.out.println("\nFilterStuff.simpleLoopWithLambda()");
System.out.println("Pet named 'Kathy': " + filterPet_simpleLoopWithLambda(pPets, (pet) -> Boolean.valueOf(Objects.equals(pet.getName(), "Kathy"))));
System.out.println("Pet named 'Hans': " + filterPet_simpleLoopWithLambda(pPets, (pet) -> Boolean.valueOf(Objects.equals(pet.getName(), "Hans"))));
}
private static Pet filterPet_simpleLoopWithLambda(final ArrayList<Pet> pPets, final Function<Pet, Boolean> pLambda) {
if (pPets == null) return null;
for (final Pet pet : pPets) {
if (pet == null) continue;
final Boolean result = pLambda.apply(pet);
if (result == Boolean.TRUE) return pet;
}
return null;
}
private static void filterStreams(final ArrayList<Pet> pPets) {
System.out.println("\nFilterStuff.filterStreams()");
System.out.println("Pet named 'Kathy': " + filterPet_filterStreams(pPets, "Kathy"));
System.out.println("Pet named 'Hans': " + filterPet_filterStreams(pPets, "Hans"));
}
private static Pet filterPet_filterStreams(final ArrayList<Pet> pPets, final String pName) {
return pPets.stream().filter(p -> Objects.equals(p.getName(), pName)).findAny().get();
}
private static void filterStreamsWithLambda(final ArrayList<Pet> pPets) {
System.out.println("\nFilterStuff.filterStreamsWithLambda()");
System.out.println("Pet named 'Kathy': " + filterPet_filterStreams(pPets, p -> Objects.equals(p.getName(), "Kathy")));
final Predicate<Pet> pdctHans = p -> Objects.equals(p.getName(), "Hans"); // we can also have 'lambda expressions' stored in variables
System.out.println("Pet named 'Hans': " + filterPet_filterStreams(pPets, pdctHans));
}
private static Pet filterPet_filterStreams(final ArrayList<Pet> pPets, final Predicate<Pet> pLambdaPredicate) {
return pPets.stream().filter(pLambdaPredicate).findAny().get();
}
}
Along with your Pet class, extended by toString():
package stackoverflow.filterstuff;
public class Pet { // please stick to naming conventions: classes start with uppercase letters!
private final String petName;
private final int petAge;
public Pet(final String name, final int age) {
petName = name;
petAge = age;
}
public String getName() {
return petName;
}
public int getAge() {
return petAge;
}
#Override public String toString() {
return "Pet [Name=" + petName + ", Age=" + petAge + "]";
}
}

How can i print a void method that iterates through a LinkedList

I'm creating a class that monitors the price, address and number of bedrooms within a house. I'm trying to call the result for my twoBeds method. Pretty sure my Sysout is completely wrong but I dont know where to start.
public class House {
int price;
int bedrooms;
String address;
public House(int a, int b, String c) {
price = a;
bedrooms = b;
address = c;
}
static List<House> agency = new LinkedList<House>();
public static int noHouse() {
return agency.size();
}
public static void twoBeds() {
for (ListIterator<House> it = agency.listIterator(); it.hasNext(); ) {
House h = it.next();
if (h.bedrooms == 2) {
System.out.println(h.address);
}
}
}
public static void main(String[] args) {
House h1 = new House(12, 2, "address");
agency.add(h1);
System.out.println(twoBeds());
}
}
System.out.println() accepts a parameter, void return type means that there is nothing to return.
You need to return something to print it.
Option 1: Do not pass void function in System.out:
public static void main(String[] args) {
House h1 = new House(12, 2, "address");
agency.add(h1);
twoBeds();
}
Option 2: Change return type of twoBeds():
public static List<String> twoBeds() {
List<String> matchedAddresses = new ArrayList<>();
for (ListIterator<House> it = agency.listIterator(); it.hasNext(); ) {
House h = it.next();
if (h.bedrooms == 2) {
matchedAddresses.add(h.address);
}
}
return matchedAddresses;
}

Arraylist not adding java

I am doing a simple sch program to add friends, which is to add objects into an arraylist. I followed everything but my method befriend() doesn't seem to work.
When i manually test using the .add() in the main, it works. Where am i doing wrongly?
import java.util.*;
public class NetworkFriends {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Person me = new Person("Aloysius", 1);
ArrayList<Person> myList = new ArrayList<Person>(Arrays.asList(me.getFriendList()));
Person p1 = new Person("Gorgon", 2);
Person p2 = new Person("Eddy", 3);
me.befriend(p1);
for(Person i : myList) {
System.out.println("Name: " + i.getName());
}
}
}
class Person
{
private int id;
private String name;
private ArrayList<Person> friendList;
private static int runningNum = 0;
private static int friendsLimit = 5;
private String degree;
private int degreeNum;
/* Constructor - 1 param */
public Person(String name, int degreeNum)
{
//Implement your code here..
//Initialize all necessary variable(s)
this.name = name;
friendList = new ArrayList<Person>(5);
this.degree = degree;
this.degreeNum = degreeNum;
}
public void befriend(Person p){
//Implement your code here..
ArrayList<Person> anotherList = new ArrayList<Person>(Arrays.asList(p.getFriendList()));
for(Person i : friendList) {
if(!isFriend(this) && friendList.size() < 5) {
friendList.add(p);
anotherList.add(this);
}
else if(!isFriend(this) && friendList.size() == 5) {
System.out.println("Friends limit reached");
}
else {
System.out.println("Already in friend list");
}
}
}
}
public boolean isFriend(Person p){
//Implement your code here..
boolean isItAFriend = true;
for(Person i : friendList) {
if(friendList.contains(p)) {
isItAFriend = true;
}
else {
isItAFriend = false;
}
}
return isItAFriend;
}
The problem is with the foreach loop in your befriend method. You are creating a new Person with the constructor that creates a empty friend list with an initial size of 5, but is still empty.
In your befriend method, you then are looping for each friend in this empty list. So the code within the loop will not be executed and the friend is never added to a list.
I suspect you want to do something like this: (and as this looks like homework I will only give you pseudo-code)
Is the person already a friend
Yes - nothing needs to be done or give feedback and return
No - Continue
Have they reached their friend limit
Yes - display feedback and return
No - Continue
Add the friend

Java Class - main not compiling when i read to departments

I wrote the two departments and when I try to read to the class from the chief and I have a problem compiling and I can not understand what the problem is, I'd love to help.
in main the error is on the line : 5.
Main:
public class main {
public static void main(String[]args){
Lecturer LecturerObject = new Lecturer("Dani",3,"Banana",1001);
The error is here >>Lecturer[] L1 = new Lecturer("Dani",2,"Banana",1001);
College FirstCollege = new College("Hmpson",2, L1);
}
}
First Class:
public class Lecturer {
public String nameOfLecturer = "";
public int numOfTimesPenFalls = 0;
public String favoriteIceCream = "";
public int numAuto = 1000;
//constructors, same name like class
public Lecturer(String name, int TimesPenFalls, String IceCream,
int num) {
nameOfLecturer = name;
numOfTimesPenFalls = TimesPenFalls;
favoriteIceCream = IceCream;
numAuto = num;
int maxLecturer=10;
}
//Copy constructor
public Lecturer(Lecturer other){
nameOfLecturer = other.nameOfLecturer;
numOfTimesPenFalls = other.numOfTimesPenFalls;
favoriteIceCream = other.favoriteIceCream;
numAuto = other.numAuto;
}
}
Secoand Class:
public class College {
public String CollegeName = "";
public int numOfLecturers = 0;
public Lecturer[] allLecturers;
// constructors, same name like class
public College(String name, int numLecturers, Lecturer[] dataBase) {
CollegeName = name;
numOfLecturers = numLecturers;
allLecturers = dataBase;
int maxLecturer = 10;
}
// getter, only private
public String getCollegeName() {
return CollegeName;
}
// setter, only private
public void setCollegeName(String newcollegeName) {
CollegeName = newcollegeName;
}
public boolean newLecturer(Lecturer addNewLecturer, int maxLecturer) {
if (numOfLecturers < maxLecturer || numOfLecturers == maxLecturer) {
numOfLecturers += 1;
return true;
} else {
System.out.print("Sorry, Max Lecturer!");
return false;
}
}
public void sortLecturer(Lecturer[] arrAllLecturers) {
int numOfTimesPenFalls = 0;
}
}
I'm first started with java I would be happy for a detailed explanation where is the problem, thank you very much.
This statement here
Lecturer[] L1 = new Lecturer("Dani",2,"Banana",1001); is wrong because you have defined L1 as an array but you are initializing it as a simple Object....
in some IDEs like eclipse, the compiler will complain with a message like
Type mismatch: cannot convert from Lecturer to Lecturer[]
Ergo: you need to init L1 as it is, as an array:
do this:
Lecturer[] L1 = new Lecturer[]{new Lecturer("Dani",2,"Banana",1001)};
now you have an array with one Lecturer object inside..
You are trying to assign array Lecture object to array, which can be done in following manner correctly.
Lecturer[] L1 = new Lecturer[] {new Lecturer("Dani",2,"Banana",1001)};

Read from a txt file and assign the value of lines to class fields

if anyone can help please ,
i have an issue assign the values from a text file to the class fields.
i have created a class called process and it has a fields like
private String agent;
private String request_type;
private String class_type;
private String num_of_seats;
private String arrivaltime;
my motive is to assign 1block in the file to agent separated by space another block to request type and so on...
say Agent3 R F 10 1 here Agent3 is going to be assign to agent and R going to assign to request_type F to class_type, 10 to num_of_seats,1 to arrivaltime
i am using arraylist to saveinput file (not compulsory i know this only thats y) and another arraylist to save the objects of my class.i am using substring method to assign the values manually is there any way instead of that so that i can simply take block which is seprated by space and do my job.
The input file(input.txt is )
Agent1 R F 2 0
Agent3 R F 10 1
Agent1 C F 1 4
Agent2 C B 2 1
Agent2 R B 10 0
................................................................................
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* #author Navdeep
*
*/
class Process
{
private String agent;
private String request_type;
private String class_type;
private String num_of_seats;
private String arrivaltime;
public Process()
{
setProcess("0", null, null, "0", "0");
}
public Process(String a, String b,String c,String d,String e)
{
setProcess(a,b,c,d,e);
}
public void setProcess(String a, String b,String c,String d,String e)
{
setAgent(a);
setRequest_type(b);
setClass_type(c);
setNum_of_seats(d);
setArrivaltime(e);
}
public void setAgent(String a){
agent = a;
}
public void setRequest_type(String b){
request_type = b;
}
public void setClass_type(String c)
{
class_type = c;
}
public void setNum_of_seats(String d) {
num_of_seats = d;
}
public void setArrivaltime(String e)
{
arrivaltime=e;
}
public String getAgent(){
return agent;
}
public String getRequest_type(){
return request_type ;
}
public String getClass_type()
{
return class_type;
}
public String getNum_of_seats() {
return num_of_seats ;
}
public String getArrivaltime()
{
return arrivaltime;
}
#Override
public String toString() {
return String.format("%s,%s,%s,%s,%s",getAgent(),getRequest_type(),getClass_type(),getNum_of_seats(),getArrivaltime());
}
}
public class main
{
public static void main(String[] args) throws FileNotFoundException
{
File temp = new File(args[0]);
Scanner sc = new Scanner(temp);
ArrayList<String> input = new ArrayList<String>();
while(sc.hasNext())
{
input.add(sc.nextLine());
}
List<Process> mylist = new ArrayList<Process>();
for (int i= 0; i <input.size();i++)
{
Process processobject = new Process();
processobject.setAgent(input.get(i).substring(0, 6));
processobject.setRequest_type(input.get(i).substring(7,8));
processobject.setClass_type(input.get(i).substring(9,10));
if(input.get(i).length() == 15)
{
processobject.setNum_of_seats(input.get(i).substring(11,13));
processobject.setArrivaltime(input.get(i).substring(14,15));
}
if(input.get(i).length() == 14)
{
processobject.setNum_of_seats(input.get(i).substring(11,12));
processobject.setArrivaltime(input.get(i).substring(13,14));
}
mylist.add(processobject); // fill arraylist with objects of my class
}
System.out.println("array list of the input from the file" + input);
System.out.println("\n \nobjects in my list"+ mylist);
}
}
the overall motive of my project is to sort the objects according to the field priorities.
If your objective is to create Process class instance then you can use the following code:
while(sc.hasNext())
{
String line = sc.nextLine();
String elements[] = line.split(" ");
Process processobject = new Process();
processobject.setProcess(elements[0],elements[1],elements[2],elements[3],elements[4]);
}
You can improve the your setProcess method by setting accessing directly class attributes with this reference. Also you can pass the same parameters to Process class constructor then you won't need setProcess method. Check the below code.
public Process(String agent, String request_type, String class_type, String num_of_seats, String arrivaltime) {
this.agent = agent;
this.request_type = request_type;
this.class_type = class_type;
this.num_of_seats = num_of_seats;
this.arrivaltime = arrivaltime;
}
Try this:
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource(configFileName).getFile());
input = new FileInputStream(someFilePath);
prop.load(input);
String someString=prop.getProperty("someString");
int someintValue=new Integer(prop.getProperty("someintValue"));

Categories

Resources