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.
Related
I'm having trouble understanding what exactly I would put in one of my classes to create the add method for 3 Arrays of the same Type. Here are the generic arrays in the main class
ArrayContainer<Integer> numberContainer = new ArrayContainer<>();
ArrayContainer<String> wordContainer = new ArrayContainer<>();
ArrayContainer<Pokemon> pokedex = new ArrayContainer<>();
My constructor for ArrayContainer is
public ArrayContainer(){
container = (T[]) new Object[defaultSize];
numItems = 0;
}
In my separate class, I'm confused what to put for my
public void add (T item){}
and I'm confused as what to return within my toString. I know you add to an array by putting
arrayName[index] = whatever;
But what would I put in that add method that would add to whatever array I call the method on? Would it be container[index] = item;?
What should I return that would return the element in the array?
Since the number of items in your ArrayContainer is not known beforehand, you should use a dynamic array, also known as List.
The numItems then becomes redundant since you can get it by calling list.size()
Your add function will only need to call list.add. As noted in the comments, it seems you're re-writing/wrapping List
In your toString method, you can return a string that concatenates all results of toString of the items included. StringBuilder can help you create a "format" that suits you. Of course this means that the objects you're putting in the container need to implement toString
Combining all the things will give you something like this:
ArrayContainer
public class ArrayContainer<T> {
private List<T> items;
public ArrayContainer() {
items = new ArrayList<>();
}
public void add(T item) {
items.add(item);
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[ ");
for (T it: items)
sb.append(it.toString()).append(' ');
sb.append(']');
return sb.toString();
}
}
Main
public class Main {
public static void main(String[] args) {
ArrayContainer<String> stringArrayContainer = new ArrayContainer<>();
stringArrayContainer.add("hello");
stringArrayContainer.add("world");
System.out.println(stringArrayContainer);
// Outputs: [hello world]
}
}
Good morning,
I have one little problem.
I created one class named Map(). In this class there in one method that generate an Array. Then i created other two classes (Top and Bottom) that extend Map. Then I created 2 objects. One of Top and one of Bottom. I want to get the same array for the Top's object and for the Bottom's object. Here is the code Source:
public class Map{
public Map(){}
public int [] yTopValues()
{
int [] arrayTopY = new int[100];
for(int i=0;i<100;i++)
arrayTopY[i]=randomInt(-50,50);//it puts in i-th position an int between 50 and -50
return arrayTopY;
}
public int [] yBottomValues()
{
int [] arrayBottomY = yTopValues;
for(int i=0;i<100;i++)
arrayBottomY[i]=arrayBottomY[i]-250;
return arrayBottomY;
}
public int [] xValues()
{
int [] arrayX = new int[100];
for(int i=0;i<100;i++)
arrayX[i]=randomInt(0,50);//it puts in i-th position an int between 0 and 50
return arrayX;
}
//other stuff
}
public class TopMap extends Map{
public TopMap(){
this.area=new Area(new Polygon(
this.xValues,
this.yTopValues,
200)
);
}
public class BottomMap extends Map{
public BottomMap(){
this.area=new Area(new Polygon(
this.xValues,
this.yBottomValues,
200)
);
}
In the View class I created two objects one of TopMap and one of BottomMap then I drew the areas with g2.draw(topMap.area) and g2.draw(bottomMap.area)
I need the 2 polygons to be similar, but both of them are different because the method is executed twice. What should I do?
Thank you very much!!
The class Map does not hold the array. It is local only to the xValues() method. If you want the other classes to get that exact array do this:
/*
* Since this is a variable in the CLASS field, this object will
* be accessible to the child class.
*/
private int[] arrayX = new int[100];
public Map(){
createArrayX(); // This makes sure that the array is created, or else
// every value inside of it will be 0.
}
public void createArrayX(){ // Exact same thing as xValues(), but without the return type
for(int i=0;i<100;i++){
arrayX[i]=randomInt(0,50);
}
}
public int[] getArrayX(){ // The method that gets the array.
return arrayX;
}
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.
}
I am trying to add object of type Shoe into the fixed array of type Shoe, but I have a problem with it.
In the addShoe method I am trying to add reference of type Shoe to the sh array like this: sh.add(s);
when I trie to run it I get this error:
Cannot invoke add(Shoe) on the array type Shoe[]
Eclipse recommends me to change it to 'length' and it doesn't make sens
I am also thinking I could write an else part of the addShoes method like this:
public void addShoe(Shoe s) throws ShoeException
{
if(s.getId() < 0) {
throw new ShoeException(s);
}
else {
if(numShoes<=10){
sh = Arrays.add(s, numShoes);
numShoes++;
}
}
}
It is just one of the ideas. Is it the correct way to do it?
public class TestShoe {
public static void main(String[] args) {
ShoeProcessor s = new Shoe();
Shoe s1 = new Shoe(7, "Black");
Shoe s2 = new Shoe(10, "Red");
try {
s.addShoe(s1);
s.addShoe(s2);
}catch(ShoeException bex){
System.out.println("Shoe Exception: " + bex);
}
}
}
public class ShoeProcessor
{
private Shoe [] sh;
private int numShoes=0;
private ShoeComparator<Shoe> sc;
public ShoeProcessor()
{
sh = new Shoe [10];
sc=new ShoeComparator<Shoe>();
}
public void addShoe(Shoe s) throws ShoeException
{
if(s.getId() < 0) {
throw new ShoeException(s);
}
else {
sh.add(s);
numShoes++;
}
}
}
Thank you for your help
I want to add I need to use array Shoe of fixed size.
I also want to add that I don't want to extend the array sh. I can add max 10 references of type Shoe to it. This is why I am also counting number of shoes added.
Probably I'm missing something: do you want replace sh.add(s); with sh[numShoes]= s; ?
Arrays in Java have a fixed size. You have two options:
Switch to using a List. This can dynamically grow when you add more items to it. For implementation you can use an ArrayList or LinkedList.
Try using System.arraycopy to resize your array each time you need to add to it. I don't recommend this. Internally, this is actually something that ArrayList does, but you are free to do it manually if you so choose.
edit: Just saw your edit. You can do something like:
public void addToList(Shoe shoe) {
if(shoeList.size() < 10) {
shoeList.add(shoe);
}
}
shoeArrayCount = 0;
public void addToArray(Shoe shoe) {
if(shoeArrayCount < 10) {
shoeArray[shoeArrayCount] = shoe;
shoeArrayCount++;
}
}
Depending on which method you choose to inplement.
I have a method which takes an array as a parameter from another class:
public void memPass(Memory[] memLocList) {
memList = memLocList;
for (int i = 0; i < 10; i++) {
System.out.println(memList[i].getSomething());
}
}
-EDIT-
The above prints out 10 values (integers) but if I try the same in the other method with an integer between 0 & 10 I get an NPE.
Can anyone tell me how to access the elements of this array from another method, which also takes in a parameter from another class?
I'm trying to do something along these lines:
public void accessArray(int mem) {
int someInt = memList[mem].getSomething();
}
-EDIT- Sorry, I should add that this gives a NullPointerException.
-NEW EDIT-
OK, I've now edited the code so that all I have in the class is:
public class PLoop {
// instance variable
public Memory[] memlist;
// method 1
public void memPass(Memory[] memLocList) {
memList = memLocList;
System.out.println(memList.length);
}
// method 2
public void accessArray(int mem) {
System.out.println(memList.length);
}
}
The first method prints an integer representing the length of "memList" and the second gives an NPE.
If I'm understanding you right, you want to be able to store memLocList then access it later? If so, I can't see what creating an instance variable wouldn't work.
public class Test {
public Memory[] memlist;
public void memPass(Memory[] memLocList) {
memList = memLocList;
}
public void accessArray(int mem) {
int someInt = memList[mem].getSomething();
}
}
Of course, I don't work in Java enough any more, so it might not be possible to create and assign an instance variable like that. But you could always store the elements in another container.
public class Test {
public List<Memory> memlist;
public void memPass(Memory[] memLocList) {
memlist = new ArrayList<Memory>(Arrays.asList(memLocList));
}
public void accessArray(int mem) {
int someInt = memList.get(mem).getSomething();
}
}
Sorry if I have any syntax errors. But you get the main idea.
If memList is an instance variable of that class and this is the same class in both situations (both methods) then this is obviously a null value at some index of memList.
private static class Memory {
private static int index = 0;
public int getSomething() {
return index++;
}
}
private static class Test {
public Memory[] memlist;
public void memPass(Memory[] memLocList) {
memlist = memLocList;
}
public void accessArray(int mem) {
int someInt = memlist[mem].getSomething();
System.out.println(someInt);
}
}
public static void main(String args[]) {
Test t = new Test();
Memory[] memList = new Memory[4];
memList[0] = new Memory();
memList[1] = null;
t.memPass(memList);
t.accessArray(0);
t.accessArray(0);
t.accessArray(1); //NPE thrown because null value in array
//or
Test t2 = new Test();
t2.accessArray(0); //NPE thrown because array is null (different instance)
}
In your implementation, you are already assuming that the array being passed to the method has 10 elements and that each of these array items has a value, hence, at some point you encounter a NullPointerException. This is dangerous especially when you are just processing an array that is passed as an argument to the method. To ensure that you are only accessing the elements that are available in the array, you need to check what the length of the array is. Also, you need to ensure that whenever you call the methods of an element in an array, (or do anything with it), check first whether it is actually there. For your for loop, you can do something like this:
if (memList != null) {
for (int i = 0; i < memList.length; i++) {
if (memList[i] != null) {
System.out.println(memList[i].getSomething());
}
}
}
That way it is safe from nullpointer exceptions. Using the same concept, you can also apply it to your method like this:
public void accessArray(int mem) {
if (mem > -1 && memList != null && memList.length > mem && memList[mem] != null){
int someInt = memList[mem].getSomething();
}
}
Of course this is assuming that the method with the for loop and the accessArray method are in the same class (or parent-child class) and memList is an instance variable.
And to save the elements of the array as a deep copy of memLocList, you can use what #GJK has suggested which is Arrays.asList to an instance variable and apply the same concept of nullpointer checking that I mentioned above.