Still new to java, but I'm having an issue adding multiple new elements to my arraylist.
The idea for this method is to look and see if a name is already in the list, and if so return false, and if not then add the name and person's score to the arraylist.
I keep getting an error when I try to add it in. The add will work if it's just the name portion I add in, but once I also include the scoreOn1st it gives me an error.
public boolean addGolfer(String name, int scoreOn1st)
{
// check if the golfer is already in the collection
for (int i = 0; i < board.size(); i++)
{
if (board.get(i).equals(name))
{
return false;
}
}
// otherwise
board.add(new ScoreCard(name, scoreOn1st));
return true;
}
This is the constructor class already created for the arraylist:
public ScoreBoard(String tourneyName)
{
// initialize instance varable
this.tournament = tourneyName;
ArrayList<ScoreCard> board = new ArrayList<ScoreCard>();
}
The board should be declared outside. You can new it inside the constructor. The get !method returns a ScoreCard object on which you cannot directly call equals name.
public class ScoreBoard {
List<ScoreCard> board;
public ScoreBoard(String tourneyName)
{
this.tournament = tourneyName;
this.board = new ArrayList<ScoreCard>();
}
ScoreCard should be something like this:
class ScoreCard {
ScoreCard(String name) {//definition } //1st Constructor
ScoreCard(String name, int score) { //definition } //2nd Constructor
In the constructor the board variable is a method variable not a field.
public ScoreBoard(String tourneyName)
{
// initialize instance varable
this.tournament = tourneyName;
this.board = new ArrayList<ScoreCard>(); // I assume you have declared this field.
}
Related
I have looked through other questions but cant seem to find the answer I am looking for.
I am having trouble figuring out how to create a loop that adds a class object to an ArrayList only if it its name is not used in the list already.
This is the class I have.
package myPackage;
public class Cube {
private int length;
private String name;
public Cube(int initLength, String initName) {
this.length = initLength;
this.name = initName;
}
I would like to create new cubes and add them to a list. Here is the code I am trying to do this with.
In the while loop I can't figure out how to determine if the name has been used or not
package myPackage;
import java.util.ArrayList;
import java.util.Scanner;
public class PartFive {
public static void main(String[] args) {
ArrayList<Cube> cubelist = new ArrayList<>();
Cube oshea = new Cube (13, "oshea");
Cube mike = new Cube (7, "tony");
cubelist.add(oshea);
cubelist.add(mike);
Scanner reader = new Scanner(System.in);
while (true) {
System.out.println("enter cube name (blank quits): ");
String name = reader.nextLine();
if (name.equals("")){
break;
}
System.out.println("enter side length: ");
int length = Integer.valueOf(reader.nextLine());
Cube newcube = new Cube(length, name);
if(cubelist.contains(newcube.name)) {
// dont add to list
}
else {
cubelist.add(newcube);
}
}
reader.close();
System.out.println(cubelist);
}
}
Any constructive criticisms and suggestions are welcomed.
Replace
if(cubelist.contains(newcube.name)) {
dont add to list
}
else {
cubelist.add(newcube);
}
with
boolean found = false;
for(Cube cube: cubelist){
if(cube.getName().equals(name)) {
found = true;
break;
}
}
if(!found) {
cubelist.add(newcube);
}
The idea is to use a boolean variable to track if a cube with the same name as that of the input name already exists in the list. For this, iterate cubelist and if a cube with the same name as that of the input name is found, change the state of the boolean variable and break the loop. If the state of the boolean variable does not change throughout the loop, add the cube to the list.
From the code in your question:
if(cubelist.contains(newcube.name)) {
// don't add to list
}
else {
cubelist.add(newcube);
}
Method contains in class java.utilArrayList is the way to go but you need to be aware that method contains [eventually] calls method equals of its element type. In your case, the element type is Cube. Therefore you need to add a equals method to class Cube. I don't know what determines whether two Cube objects are equal, but I'll guess, according to your question, that they are equal if they have the same name, even when they have different lengths. I will further assume that name cannot be null. Based on those assumptions, here is a equals method. You should add this method to class Cube.
public boolean equals(Object obj) {
boolean areEqual = false;
if (this == obj) {
areEqual = true;
}
else {
if (obj instanceof Cube) {
Cube other = (Cube) obj;
areEqual = name.equals(other.name);
}
}
return areEqual;
}
Now, in method main of class PartFive you can use the following if to add a Cube to the list.
if (!cubelist.contains(newcube)) {
cubelist.add(newcube);
}
You can check for duplicate names in the cubelist array using lambda expressions (for better readability):
boolean isNameAlreadyExisting = cubelist.stream()
.anyMatch(cube -> cube.getName().equals(newcube.getName())); // this is returning true if any of the cubelist element's name is equal with the newcube's name, meaning that the name is already existing in the cubelist
if (!isNameAlreadyExisting) {
cubelist.add(newcube);
}
One thing that you should do is to remove the while(true) instruction which causes an infinite loop.
Another suggestion is to display the name of objects contained by cubelist, to see that indeed the names are not duplicated:
cubelist.stream()
.map(Cube::getName)
.forEach(System.out::println);
I'm sitting on an assignment for university and I'm at a point, where I fear I haven't really understood something fundamental in the concecpt of Java or OOP altogether. I'll try to make it as short as possible (maybe it's sufficient to just look at the 3rd code segment, but I just wanted to make sure, I included enough detail). I am to write a little employee management. One class within this project is the employeeManagement itself and this class should possess a method for sorting employees by first letter via bubblesort.
I have written 3 classes for this: The first one is "Employee", which contains a name and an ID (a running number) , getter and setter methods and one method for checking whether the first letter of one employee is smaller (lower in the alphabet) than the other. It looks like this:
static boolean isSmaller(Employee source, Employee target) {
char[] sourceArray = new char[source.name.length()];
char[] targetArray = new char[target.name.length()];
sourceArray = source.name.toCharArray();
targetArray = target.name.toCharArray();
if(sourceArray[0] < targetArray[0])
return true;
else
return false;
}
I tested it and it seems to work for my case. Now there's another class called EmployeeList and it manages the employees via an array of employees ("Employee" objects). The size of this array is determined via constructor. My code looks like this:
public class EmployeeList {
/*attributes*/
private int size;
private Employee[] employeeArray;
/* constructor */
public EmployeeList(int size) {
this.employeeArray = new Employee[size];
}
/* methods */
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
/* adds employee to end of the list. Returns false, if list is too small */
boolean add(Employee m) {
int id = m.getID();
if (id > employeeArray.length) {
return false;
} else {
employeeArray[id] = m;
return true;
}
}
/* returns employee at certain position */
Employee get(int index) {
return employeeArray[index];
}
/* Sets employee at certain position. Returns null, if position doesn't exist. Else returns old value. */
Employee set(int index, Employee m) {
if (employeeArray[index] == null) {
return null;
} else {
Employee before = employeeArray[index];
employeeArray[index] = m;
return before;
}
}
Now comes my real problem: In a third class called "employeeManagement" I am supposed to implement the sorting algorithm. The class looks like this:
public class EmployeeManagement {
private EmployeeList ml = new EmployeeList(3);
public boolean addEmployee(Employee e) {
return ml.add(e);
}
public void sortEmployee() {
System.out.println(ml.getSize()); // I wrote this for debugging, exactly here lies my problem
for (int n = ml.getSize(); n > 1; n--) {
for (int i = 0; i < n - 1; i++) {
if (Employee.isSmaller(ml.get(i), ml.get(i + 1)) == false) {
Employee old = ml.set(i, ml.get(i + 1));
ml.set(i+1, old);
}
}
}
}
The "println" before my comment returns "0" in console... I am expecting "3" as this is the size I gave the "EmployeeList" as parameter of the constructor within my "EmployeeManagement" class. Where is my mistake ? And how can I access the size of the object I created in the "EmployeeManagement" class (the "3") ? I'm really looking forward to your answers!
Thanks,
Phreneticus
You are not storing size in your constructor. Something like,
public EmployeeList(int size) {
this.employeeArray = new Employee[size];
this.size = size; // <-- add this.
}
Also, setSize isn't going to automatically copy (and grow) the array. You will need to copy the array, because Java arrays have a fixed length. Finally, you don't really need size here since employeeArray has a length.
The size variable you are calling is the class field. If you take a quick look at your code, the getter is getting the field (which is initialized as zero when created). The size you are using it. The good way of doing it would be to get the size of the array in the getter like this:
public int getSize() {
return employeeArray.length;
}
This would return the size of the array in the object.
First i add new Popotnik in List popotnik depending on how big it is, which is working fine - function prostaMesta. Then i want to go through list popotnik and set popotnik value depending on where it is in for, but value of i will always be 0 everytime it is being called. Also i have break there as i only want to set one popotnik at the time. How should i increment (i) while having some sort of break in there?
Also if(popotnik.get(i) == null){} is not being called, but values inside popotnik are null(s)
private List<Popotnik> popotnik = new ArrayList<Popotnik>();
public void prostaMesta(List<Popotnik> popotnik, int sedez){
stanovanje.setPostle(sedez);
for(int i=0; i<stanovanje.getPostle(); i++){
popotnik.add(new Popotnik());
}
System.out.println(popotnik);
}
public void dodajPotnika(List<Popotnik> popotnik, Popotnik popotnik2){
for(int i=0; i<popotnik.size(); i++){
if(popotnik.get(i) == null){
setPopotnik(popotnik, i);
popotnik.set(i, popotnik2);
break;
}
}
System.out.println(getPopotnik());
}
public void setPopotnik(List<Popotnik> popotnik, int i){
this.popotnik = popotnik;
}
public List<Popotnik> getPopotnik(){
return popotnik;
}
Main class:
List<Popotnik> alPopotnik = new ArrayList<Popotnik>();
if(x.equals("p")){ //inside of a loop when prostaMesta() is being called
potovanje.prostaMesta(alPopotnik, sedez);
}
`if(x.equals("d")){` //inside of a loop when dodajPotnika() is being called
System.out.println("Vnesi ime: ");
String ime = skener.next();
Popotnik popotnik = new Popotnik(ime);
potovanje.dodajPotnika(alPopotnik, popotnik);
}
The if(popotnik.get(i) == null) is never true because objects on the list are not null. You initialize them in the for loop in prostaMesta.
If you have some fields inside the Popotnik class then they are null, but object itself is not.
You would need to do something like popotnik.get(i).getName() == null.
Besides, if you only want to add a number at the end of popotnik's name then it isn't necessary to initialize a list with empty objects.
You could just add objects to list using a different constructor.
For example popotnik.add(new Popotnik("Popotnik"+(popotnik.size()+1))).
It's not pretty but I think initialization like this here is not necessary.
I'm attempting to have an array (fishWeights) be set to the values that are found using a method. Except that when I try to compile this:
public class GoFishEdited {
public static void main(String[] args) {
System.out.println("\nProject 1, Stage 3\n");
Habitat h1 = new Habitat();
Habitat h2 = new Habitat();
int[] fishWeights = stockUp();
System.out.println("Start with some weights:");
for (int i : fishWeights) {
System.out.print(i + " ");
}
System.out.println("\n\nMake fish of those weights.\n");
Fish[] fishGroup = new Fish[fishWeights.length]; // array of Fish
for (int i=0; i < fishWeights.length; i++) {
fishGroup[i] = new Fish(fishWeights[i]); // make fish
}
}
}
It states that that the symbol stockUp() cannot be found. It is in this file:
public class Habitat {
ArrayList stringer = new ArrayList();
public int maxCount=25;
public int minCount=9;
public int maxWeight=10;
public int minWeight=1;
public int catchProbability=30; //0.3
public void stockUp(int[] fishArr){
int numofF = minCount + (int)(Math.random() * ((maxCount - minCount) + 1));
for(int i = 0; i<numofF; i++){
fishArr[i] = minWeight + (int)(Math.random() * ((maxWeight - minWeight) + 1));
}
}
public Habitat(){
}
public void addFish(Fish f) {
stringer.add(f);
}
public void removeFish(Fish f){
stringer.remove(f);
}
public void printFish(){
System.out.println(stringer);
}
}
So stockUp exists, I just can't seem to make getFishEdited to find it.
In java everything in an object.
So if you want to call method form a class should use
Habitat habitat = new Habitat();
habitat.stockUp();
stockUp() is an instance method of the Habitat class, so you need to create an instance of Habitat in your GoFishEdited class's main method in order to call it from GoFishEdited. You could call it on either instance of Habitat created, h1 or h2 Like this:
h1.stockUp();
Note that in the code you posted, you need to pass an array of integers as an argument to stockUp(), but it looks like in your code you are expecting stockUp() to return an int[]. If stockUp() is supposed to return an array of integers, then you need to change the method signature to look something like:
public int[] stockUp() {
//do whatever you want this method to do
return arrayOfInts;
}
You need to either create an instance of habitat using new Habitat to call the method in, or you need to make the method stockUp static and call it in the Habitat class using Habitat.stockUp.
Since you've created instances of Habitat in h1 and h2, call
h1.stockUp(fishArray)
Or
h2.stockUp(fishArray)
depending on what you mean to do. You declared the stockUp() method to accept an int[], so you'll need to pass it one--I called it fishArray, since you seem representing fish. Also, you've declare stockUp() as returning void, so don't expect it to return some value that you can assign to fishWeights. At some point you may find it's a good idea to introduce a Fish class to wrap that concept up better.
In my java class I declare a class as array and in a function I assign values to the array of class but out of the function in the class it retrun null. How to access the class array.
The declared class of array variable is inbuild final class in java(https://developers.google.com/maps/documentation/android/reference/com/google/android/gms/maps/model/Marker)
Code sample:
public class Sample{
Marker redMarker[]; // Marker is the public final class
// https://developers.google.com/maps/documentation/android/reference/com/google/android/gms/maps/model/Marker
void function1(){
for(int i=0;i<array.length;i++){
redMarker[i] = map.addMarker(.......);
}
}
void function2(){
if(condition){
if(redMarker!=null){
for(int i=0;i<array.length;i++){
redMarker[i].setVisible(false);
}
}
else{
// here I get redMarker is Null.
}
}
}
}
You need to first initialize the array
Marker redMarker[];
Something like
Marker redMarker[] = new Marker[someSize];
Then add values
for (int i = 0; i < someSize; i++){
redMarker[i] = new Marker();
}
redMarker is a data member, it's value defaults to null unless you initialize it in a constructor or inline.
E.g.:
public class Sample{
Marker redMarker[];
public Sample(int numOfMarkers) {
redMarker = new Marker[numOfMarkers];
}
You should declare the Marker redMarker[]; array size
Modify your function2() like below.
void function1(){
if(condition){
if(redMarker!=null){
}
else{
redMarker = new Marker[array.length]; // added this line of code.
}
}
}
Modify your function1() like below.
void function1(){
if(redMarker ==null){
redMarker = new Marker[array.length]; // added this line of code.
}
for(int i=0;i<array.length;i++){
redMarker[i] = map.addMarker(.......);
}
}
Since your methods aren't static, you will need a constructor doing the following:
public Sample() {
redMarker = new Marker[<put the length in here];
}
If You are testing if(redMarker!=null), then it is quite obvious that the else block is executed only if redMarker actually is null.
Everything is working as it should, the fault is probably in Your logic.
check on function1 is it still null?
if so then you have not initialized your redMarker