Accessing objects in 2D arrays? - java

I want to print out the "weight" of an item in my game.
Class, "Item":
public class Item {
private String name;
private double weight;
public Item(String n, double w)
{
this.name = n;
this.weight = w;
}
}
In the main class I have this bit of code:
public static Item[][] items = {{new Item("Dagger", 1), new Item("Sword", 5), new Item("Bullet(s)", 0), new Item("Pistol", 15)},
{new Item("Torch", 2), new Item("Shovel", 5), new Item("Pickaxe", 10)},
{new Item("Gold", 0), new Item("Potion(s)", 1)}};
How could I print the weight of dagger, for example?

Unless I'm missing something,
System.out.println(items[0][0].getWeight());
Of course, your Item class will need to be modified to include accessors since the fields are private (which is the recommended approach). I suggest you also make your fields final so the class instances are immutable. I would also override toString() like
public class Item {
private final String name;
private final double weight;
public Item(String n, double w) {
this.name = n;
this.weight = w;
}
public String getName() {
return name;
}
public double getWeight() {
return weight;
}
#Override
public String toString() {
return String.format("%s %.3f", name, weight);
}
}
The advantage of overriding toString() is you could also use Arrays.deepToString(Object[]) like
System.out.println(Arrays.deepToString(items));
and get meaningful results printing the entire array.

First of all you need a getter in your Item class for weight since weight is declared private. So if you added the following method to Item:
Public Double GetWeight()
{
return this.weight;
}
Then you could access Daggar like the following:
Double weight = items[0][0].GetWeight();
system.out.println(weight);

Related

New to java: I'm not sure how to store the objects in the arrays after it is created. The program gets rid of it, making it null

The main objective was to have a lake and add fish objects to it, which have details about their weight etc. But however, every time a new fish is created, the previous object appears as null instead of its location, which I could use my getName to get the name.
package com. company;
public class Main {
public static void main(String[] args) {
Lake l = new Lake("jersey", 1, 2, 3,4 );
l.addFish("carp", 20, 1);
l.addFish("josh",20,1);
Lake n = new Lake("york",1,2,4,20);
n.addFish("catfish",20,30);
n.addFish("tot",20,30);
n.addFish("salmon",20,30);
n.addFish("shrimp",20,30);
n.addFish("swordfish",20,30);
}
}
package com. company;
import java.lang.reflect.Array;
import java.util.Arrays;
public class Lake {
private String name;
private double length;
private double width;
private double depth;
private final int amountOfFish;
private int currentFishAmount = 0 ;
Lake(String name, double length, double width, double depth, int amountOfFish)
{
this.name = name;
this.length = length;
this.width = width;
this.depth = depth;
this.amountOfFish = amountOfFish;
}
public void addFish (String name, double length, double weight)
{
Fish fishInLake [] = new Fish[amountOfFish];
fishInLake[currentFishAmount]= new Fish(name, length, weight);
System.out.println("Lake: " + this.name + "|" + "Fish:" + ""+ fishInLake[currentFishAmount].getName() + fishInLake[currentFishAmount].getLength());
System.out.println(currentFishAmount);
currentFishAmount++;
System.out.println(Arrays.toString(fishInLake));
}
}
package com.company;
import java.lang.reflect.Array;
public class Fish {
private String name;
private double length;
private double weight;
Fish (String name, double length, double weight){
this.name = name;
this.length = length;
this.weight = weight;
}
public String getName(){
return this.name;
}
public double getLength(){
return this.length;
}
public double getWeight(){
return this.weight;
}
}
The main objective was to have a lake and add fish objects to it, which have details about their weight etc. But however, every time a new fish is created, the previous object appears as null instead of its location, which I could use my getName to get the name.
First off, to make your output a bit more readable, add a toString() method in your Fish class:
public String toString(){
return this.name;
}
Next, since you want the array to be saved every time a new fish is added to the lake, we want to make the array a private instance variable, and then initialize it in our constructor:
package com. company;
import java.lang.reflect.Array;
import java.util.Arrays;
public class Lake {
private String name;
private double length;
private double width;
private double depth;
private final int amountOfFish;
private int currentFishAmount = 0 ;
private Fish[] fishInLake;
Lake(String name, double length, double width, double depth, int amountOfFish)
{
this.name = name;
this.length = length;
this.width = width;
this.depth = depth;
this.amountOfFish = amountOfFish;
this.fishInLake = new Fish[amountOfFish];
}
public void addFish (String name, double length, double weight)
{
fishInLake[currentFishAmount]= new Fish(name, length, weight);
System.out.println("Lake: " + this.name + "|" + "Fish:" + ""+ fishInLake[currentFishAmount].getName() + fishInLake[currentFishAmount].getLength());
System.out.println(currentFishAmount);
currentFishAmount++;
System.out.println(Arrays.toString(fishInLake));
}
}
better to create a static method or a static Array, otherwise every time that tries to insert data, the previous data will be disappearing, with a static Array the whole data will be there until program execution finish.

Java interfaces and objects

Over here i'm trying to make use of an interface called "Measurable" with one method called getMeasure. The problem is, I'm trying to get the average height of all the people in my program, by accessing the method in my interface. One of the problems I can't access the getMeasure method for some reason, and at last get the average height of all the people in the array. How can I solve this problem?
class Main {
public static void main(String args[]) {
Person[] people = new Person[4];
people[0] = new Person("Larry", 65);
people[1] = new Person("Susan", 45);
people[2] = new Person("Joe", -45);
people[3] = new Person("", 0);
double averageHeight = average(people);
}
public static double average(Person[] objects)
{
if (objects.length == 0) { return 0; }
double sum = 0;
for (Person obj : objects)
{
double measure = obj.getMeasure();
sum = sum + measure;
}
double result = sum / objects.length;
return result;
}
}
interface Measurable {
double getMeasure();
}
public class Person {
private String name;
private Integer height;
public Person(String name, Integer height)
{
this.name = name;
this.height = height;
}
public double getMeasure() {
return height;
}
}
The Person class should implement Measurable:
public class Person implements Measurable {
...
}
Then if you want to make your average function reusable (I guess this is your desired outcome), you should replace the Person instance with Measurable:
public static double average(Measurable[] objects) {
...
for (Measurable obj : objects){
...
}
}
This way you could have different Measurable implementations to calculate the average.
public class Person implements Measurable {
private String name;
private Integer height;
public Person(String name, Integer height)
{
this.name = name;
this.height = height;
}
#Override
public double getMeasure() {
return height;
}
You have to implement the to use it. If the Interface also implements the method, you have to add the #Override modifier.

Pass values to parameters

when i trying to do this i got the problem said
Constructor Product in class Product cannot be applied to given types;
required: java.lang.String,int,double; found: java.lang.String;
reason: actual and formal arguments lists differ in length
And i have 2 classes:
import java.text.*
public class Product {
private String name;
private int stock;
private double price;
public Product(String name, int stock, double price) {
this.name = name;
this.stock = stock;
this.price = price;
}
public double sell(int n) {
stock = n;
return stock;
}
public void restock(int n) {
}
#Override
public String toString() {
return stock + name + "at $"+price;
}
}
public class Store {
public static void main(String[] args) {
new Store().use();
}
private Product product;
private Product cashRegister;
public Store() {
product = new Product("Sticky tape");
cashRegister = new Product("Cash register");
}
public void use() {
}
private void sell() {
}
private void restock() {
}
private void viewStock() {
}
private void viewCash() {
}
private void help() {
System.out.println("Menu options");
System.out.println("s = sell");
System.out.println("r = restock");
System.out.println("v = view stock");
System.out.println("c = view cash");
System.out.println("x = exit");
}
}
I understand that i have to declare for Product constructor. But i think i have done it. If anyone know where i got wrong please explain. Thank you!
you do not have constructor with one param, so you can not using this form
product = new Product("Sticky tape");
decare one more constructor with one param or fill all param
product = new Product("Sticky tape", 10, 20.0);
You need to:
overload the constructor
public Product(String name){...}
or create instances of Product using the right and only one constructor uor have:
public Product(String name, int stock, double price)
if you overload then something like this should happen
public Product(String name){
this(name, 0, 0.0);
}
so you call a constructor from the other constructor
This is the time to learn constructor overloading. Overloading comes from OOP.
You can use Overloading to methods and constructors. Overloading means for a same method name you can implement that method
several time with different parameters(number of parameters)
. Actualy not only that,
you can use different data types for parameter.
also can change order of parameter.
keep remember method name must be same.
For the constructor also same thing. If you use for constructor you can add parameters like:
//constructor with one parameter
public Product(String name) {
this.name = name;
this.stock = 0;//or whatever your default value
this.price = 0;//or whatever your default value
}
//constructor with two parameter
public Product(String name, , int stock) {
this.name = name;
this.stock = stock;
this.price = 0;//or whatever your default value
}
public Product(String name, int stock, double price) {
this.name = name;
this.stock = stock;
this.price = price;
}
Like that you can add as many as you want.
Or you can use one constructor and pass argument to match with the implementation of the constructor when creating object. Like below:
product = new Product("Sticky tape", 0, 0);
this is not complete description you can read this to learn more
You have no constructor In Product class that takes single String argument. Create it like so:
public Product(String name) {
this.name = name;
}
In import statement you forgot semicolon:
import java.text.*;
your program is having 3 coding error which include
you forgot the " ; " after " import java.text.* " actually it is not required in your code, you can remove it, nothing will change.
you cannot make class Product as public , because you've made "Store" as your Primary class having main method.So remove public keyword from the Product class.
You didn't create a parameterized constructor
which should be like
public Product(String name){ this.name = name;}
in your product class.
your code will be like after correcting
class Product {
private String name;
private int stock;
private double price;
public Product(String name, int stock, double price) {
this.name = name;
this.stock = stock;
this.price = price;
}
public Product(String name) {
this.name = name;
}
public double sell(int n) {
stock = n;
return stock;
}
public void restock(int n) {
}
#Override
public String toString() {
return stock + name + "at $"+price;
}
}
public class Store {
public static void main(String[] args) {
Store s = new Store();
System.out.println(s.product);
System.out.println(s.cashRegister);
}
private Product product;
private Product cashRegister;
public Store() {
product = new Product("Sticky tape");
cashRegister = new Product("Cash register");
}
}
The errors are in these lines of code:
product = new Product("Sticky tape");
cashRegister = new Product("Cash register");
The Product constructor defined expects:
public Product(String name, int stock, double price)

Return type required/ Cannot return a value from a method with a void result type

Im a beginner, can you tell me what am i doing wrong? Why can't i use those methods properly?
IDE shows: Return type required/ Cannot return a value from a method with a void result type
` public class Human
{
public int Age = 0;
public int Weight = 0;
public int Height = 0;
private String name = "";
boolean isMale;
}
public getAge()
{
return Age;
}
public getWeight()
{
return Weight;
}
public getHeight()
{
return Height;
}
public Human(int Age, int Weight, int Height, String name, boolean
isMale)
{
} `
Great job so far, you're just missing the return type statements for your methods. Your methods should be written as follows:
class Human {
private int Age = 0;
private int Weight = 0;
private int Height = 0;
private String name = "";
private boolean isMale;
public int getAge() {
return Age;
}
public int getWeight() {
return Weight;
}
public int getHeight() {
return Height;
}
public Human(int Age, int Weight, int Height, String name, boolean isMale) {
this.Age = Age;
this.Weight = Weight;
this.Height = Height;
this.name = name;
this.isMale = isMale;
//returns nothing
}
}
Notice that each method has some sort of return type. Since getAge() returns Age (which you have specified above as type int), you need to explicitly put in the method declaration statement that you are returning an int. Same holds true if you were to return a String or a Boolean, etc.
The last method (Human()), however, is a constructor function that gets called when you instantiate a new Human object:
Human myHuman = new Human(31, 155, 68, "Bob", true);
Notice how in the codeblock above, I am passing values in the order that I have them in the constructor function and the constructor function sets the attributes of the object based on what is being passed. The big takeaway here, per your question, is that it does not return anything (with the exception of a new object...discussion for another time).
Generally speaking, if you are not returning anything, put void in the return type. Just as you do in the Main function.
Last thing that I would like to point out, is the use of public vs. private for your attributes and methods. Generally speaking, you would set your attributes to private and then make your public get/set methods to return or alter these attributes. Just something to look out for in the future.
Hope that helps! Feel free to message me if you have another question or need some clarification.
You need to have a return type for each function from where you want to return a value.
ex:
public int getAge()
{
return Age;
}
public int getWeight()
{
return Weight;
}
public int getHeight()
{
return Height;
}
You need to specify a return value after each method modifier.
For example,
public int getAge() {
return age;}

Why can't I accesses the properties of an object stored in a element of a ArrayList?

I have two packages lets give them the name package 1 and package 2.
Class A and Class B is in package1. Class A contains an ArrayList called PTable. Class B contains a function called query() that filters through PTable,in Class A, based on a certain conditions and returns an ArrayList called result that contains all the elements from PTable that meet that condition.
I now have package2 that contains Class C. Class C imports Class B from package 1; Class C is a subclass of HttpServlet. I create an object of Class B in class C and initializer it.
I then call the function query() and assign it to a variable called results. When I try and get the properties of an element at a certain index, I can't see the properties of the original objects stored in the ArrayList PTable.[This is what appears when I try and access the properties of the objects. My aim is to see the second image ][1]
Nice to ask questions but first spend sometime studying Java. Read a book or online and you will learn about casting very quickly. Also about classes, super classes etc
Your storing the objects in a variable of type Element (your results array list).
Cast the object back to the type it belongs too and then you will see the variables.
Code design note : storing different types of classesin the same array list is legal and possible but bug prone. Try to avoid it. If you change the order of storing variables into the list, you need to change all the access code too. Anyway happy learning.
There are free online Java tutorials study them -> https://www.google.co.in/search?q=java+tutorial+beginner
Sample class, in the main method try to get the object at position 1 and cast it to a Person :
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
class Person {
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
super();
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class Car {
private String manufacturer;
private String model;
private double price;
private int yearOfMfr;
private Date dateBought;
private String licenceNumber;
public Car() {
super();
}
public Car(String manufacturer, String model, double price, int yearOfMfr, Date dateBought, String licenceNumber) {
super();
this.manufacturer = manufacturer;
this.model = model;
this.price = price;
this.yearOfMfr = yearOfMfr;
this.dateBought = dateBought;
this.licenceNumber = licenceNumber;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getYearOfMfr() {
return yearOfMfr;
}
public void setYearOfMfr(int yearOfMfr) {
this.yearOfMfr = yearOfMfr;
}
public Date getDateBought() {
return dateBought;
}
public void setDateBought(Date dateBought) {
this.dateBought = dateBought;
}
public String getLicenceNumber() {
return licenceNumber;
}
public void setLicenceNumber(String licenceNumber) {
this.licenceNumber = licenceNumber;
}
}
public class DemoApp {
public static void main(String[] args) {
List<Object> results = new ArrayList<>();
DemoApp app = new DemoApp();
app.fillItUp(results);
Car acar = (Car) results.get(0);
acar.setLicenceNumber("Flying Duck");
}
private void fillItUp(List<Object> results) {
Car car = new Car("sel2in", "electric_VTOL", 540923, 2018, new Date(2018, 3, 32), "Skyprog");
results.add(car);
results.add(new Person("tushar", 39));
}
}

Categories