How to print every element in array in loop if with different types of element? - java

I have this phone class:
public class Phone {
private int id;
private String brand;
private String model;
private int cameraResolution;
public Phone(int id, String brand, String model, int cameraResolution) {
this.id=id;
this.brand=brand;
this.model=model;
this.cameraResolution= cameraResolution;
}
public void showDetails() {
System.out.println("id "+ this.id);
System.out.println("Marka to "+ this.brand);
System.out.println("Model to "+ this.model);
System.out.println("Rozdzielczosc aparatu to " + this.cameraResolution);
}
and this main class
import java.util.ArrayList;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
Phone galaxy= new Phone(1, "Samsung","Galaxy",12);
Phone lumia= new Phone(2, "Nokia","Lumia",13);
Phone pixel= new Phone(3, "Google","Pixel",14);
galaxy.showDetails();
//String[] phones = new String[3];
//phones[0]="galaxy";
//phones[1]="lumia";
//phones[2]="pixel";
Phone[] phones = new Phone[3];
phones[0]= galaxy;
phones[1]= lumia;
phones[2]= pixel;
// dont work System.out.println(Arrays.oString(phones));
}
}
I want to write a loop, that will call the phone.showDetails() method from the phone's array, but I can't find a way to do it. There's a problem with data type conversion or sth.
I want to achieve a loop, that will call:
galaxy.showDetails, then lumia.showDetails() and pixel.showDetails();

You can loop through every element and print its details.
for (Phone phone: phones){
phone.showDetails();
}

Your big issue is your phone class doesn't override toString(), so all youre going to see is memory address space. Do something like this:
#Override
public String toString() {
return "Phone [id=" + id + ", brand=" + brand + ", model=" + model + ", cameraResolution="
+ cameraResolution + "]";
}
As for looping through, there are lots of ways you can do this, but the easiest:
for (Phone phone : phones) {
System.out.println(phone);
}

Related

How to add an object to an arraylist in a method

I want to write a method that adds a Phone to an ArrayList.
Phone class:
public class Phone {
private int id;
private String brand;
private String model;
private int cameraResolution;
public Phone(int id, String brand, String model, int cameraResolution) {
this.id=id;
this.brand=brand;
this.model=model;
this.cameraResolution= cameraResolution;
}
public void showDetails() {
System.out.println("id "+ this.id);
System.out.println("Marka to "+ this.brand);
System.out.println("Model to "+ this.model);
System.out.println("Rozdzielczosc aparatu to " + this.cameraResolution);
}
#Override
public String toString() {
return "Brand: " + this.brand + ", Model: " + this.model + ", Camera Resolution: " + this.cameraResolution + ", Id: " + this.id;
}
}
Shop class:
import java.util.ArrayList;
public class Shop {
private String name;
private ArrayList<Phone> phones;
private ArrayList<Tv> tvs;
public Shop(String name, ArrayList<Phone> phones, ArrayList<Tv> tvs ) {
this.name=name;
this.phones=phones;
this.tvs=tvs;
}
public ArrayList<Phone> addNewPhone(Phone newPhone) {
return phones.add(this.newPhone); // this doesnt work
}
}
Main class:
import java.util.ArrayList;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
Phone galaxy= new Phone(1, "Samsung","galaxy",12);
Phone lumia= new Phone(2, "Nokia","lumia",13);
Phone pixel= new Phone(3, "Google","pixel",14);
Phone[] phones = new Phone[3];
phones[0]= galaxy;
phones[1]= lumia;
phones[2]= pixel;
for (Phone phone: phones) {
phone.showDetails();
}
System.out.println(lumia.toString());
Client client1= new Client(1, "Jan", "Kowalski", null);
Client client2= new Client(1, "Magda", "Nowak", null);
}
}
I know that I need to return an ArrayList<Phone> and I need to receive a type of Phone in this method, then it should return list of new phones, but I don't know why it's not working.
Eclipse shows this error : newPhone cannot be resolved or is not a filed.
You have to problems in your method addNewPhone:
Probably do not want to add the field newPhones of the class Shop (because you don't have that field) but the method parameter of that name.
And none of the ArrayList.add overloads returns the list itself. As I don't see a single call of the addNewPhone method I can't really judge it, but I would think twice if you really need to return that list there
I would write it like this:
public addNewPhone(Phone newPhone) {
phones.add(newPhone);
}
If you need to return the phones list, I would always only use List<Phone> and never ArrayList, and probably also return Collections.unmodifiableList(phones)

Cannot invoke " " because array is null

I need to add information about 2 actors such as their name, address and age and have done so without arrays easily but it's necessary, I keep getting the error
"Cannot invoke "TestActor.setName(String)" because "actors[0]" is null
at TestMain.main(TestMain.java:5)"
This is just a test main I'm using to test it
'''
public class TestMain {
public static void main(String[] args) {
TestActor[] actor = new TestActor[2];
//Actor act1 = new Actor(" ", " ", 0);
actor[0]= ("");
actor[0].setName("Jack Nicholson");
actor[0].setAddress("Miami.");
actor[0].setAge(74);
actor[0].printAct();
}
And this is the actor class I'm using that I need to set the information from
public class TestActor {
private String name;
private String address;
private int age;
public TestActor(String s, String g, int p) {
this.name = s;
this.address = g;
this.age = p;
}
public void setName(String s) {
name = s;
}
public void setAddress(String g) {
address = g;
}
public void printAct() {
System.out.println("The actor's name is " + name + " and age is " + age + ". They live in " + address);
}
public void setAge(int p) {
age = p;
}
public String toString() {
return "The actor's name is " + name + " and age is " + age + ". They live in " + address;
}
}
I know the toString doesn't do anything there the way I have it setup just for the time being. It might be a bit of a mess and I might be in totally the wrong track. I was able to do it relatively easily wihtout using arrays but they've kinda stumped me and I'm not 100% sure on the direction to go in without maybe butchering the whole thing.
Compiler is complaining because you're not initializing TestActor object correctly. You should rather do this:
actor[0] = new TestActor("Jack Nicholson", "Miami.", 74);
actor[0].printAct();
If you don't want to do this and use setters manually, then you need to define a default constructor in TestActor:
public TestActor() { }
then you should be able to use it in your arrays like this:
actor[0] = new TestActor();
actor[0].setName("Jack Nicholson");
actor[0].setAddress("Miami.");
actor[0].setAge(74);
actor[0].printAct();
When you create TestActor[] actor = new TestActor[2];, you are creating an array of a reference type object. So, actor[0] as well as actor[1] refer null. First create TestActor and assign the objects to the array. Like:
TestActor actorOne = new TestActor("s", "g", 0);
actor[0] = actorOne;
OR
TestActor[] actor = new TestActor[2];
actor[0]= new TestActor ("Jack Nicholson", Miami.", 74);
actor[0].printAct();
It seems your problem is with initializing the Actor to an empty string instead of a TestActor object:
actor[0] = ("");
Instead try:
actor[0] = new TestActor("Jack Nicholson", "Miami.", 74);
Each TestActor needs to be instantiated so this will instantiate the TestActors and also populate the fields you want.

How to recursively print hierarchical lists with indents

I have a class that consists of a String name and an ArrayList of other instances of the class, known as attachments. Think of it like a lego that can be attached to infinitely many other legos. I need to display this hierarchy in the console with indents (without passing in any parameters) and I am not sure the best way to do so:
Expected Output:
+ PowerSource
+ Appliance
+ Extension
+ Module
+ Lamp
+ Appliance
+ Module
Current Output:
+ PowerSource
+ Appliance
+ Extension
+ Module
+ Lamp
+ Appliance
+ Module
I have the display() method to the point where I am able to indent once, but then I cannot seem to get attachments of attachments to indent twice. Any help would be appreciated
package components;
import java.util.ArrayList;
import java.util.List;
public class MyTest {
private String name;
private List<MyTest> attachments;
public MyTest(String name) {
this.name = name;
attachments = new ArrayList<MyTest>();
}
public void attach(MyTest newLoad) {
attachments.add(newLoad);
}
public void display() {
System.out.print("+ " + toString() + "\n");
if (attachments.size() > 0) {
for (MyTest load : attachments) {
System.out.print(" ");
load.display();
}
}
}
#Override
public String toString() {
return name;
}
public static void main(String[] args) {
MyTest a = new MyTest("PowerSource");
a.attach(new MyTest("Appliance"));
a.attach(new MyTest("Appliance"));
MyTest l = new MyTest("Lamp");
l.attach(new MyTest("Extension"));
a.attach(l);
a.display();
}
}
its normal. when recursive call made, program doesnt know how much indent it has to made.
its always making one indent. program need to know depth of your list hierarchy.
i mean, when Appliance called its display, it have to indent two times. because their elements need to be double intended. but it dont have that information.
so you can create filed int depth=0; for base object. and edit attach like this.
public void attach(MyTest newLoad) {
newLoad.setDepth(this.depth + 1);
attachments.add(newLoad);
}
then edit display method like this and add indent method.
private void indent(int depth){
if(depth > 0){
System.out.print(" ");
indent(depth-1);
}
}
public void display() {
System.out.print("+ " + toString() + "\n");
for (MyTest load : attachments) {
this.indent(this.depth);
load.display();
}
}
I haven`t test this but you will get the main idea from those examples
Pass the prefix as a parameter:
public void display() {
display("");
}
private void display(String prefix) {
System.out.println(prefix + "+ " + name);
for (MyTest load : attachments) {
load.display(prefix + " ");
}
}
Note that there is no need for if (attachments.size() > 0), since the loop will simply do nothing if attachments is empty.

How to return a private variable

Ok so I'm trying to get a better understanding of how to return a private variable from a class that I have created. I've only provided a small snippet of my main program to explain my question, so if more information is needed please let me know. My goal is to return a string from the class (working great), but also be able to return the private variables individually as needed (example used below is "flight_number").
public class Flights {
private String dest_city, dest_state, departureDate, departureTime;
private int flight_number;
public Flights(String city, String state, String dDate, String dTime, int flightNumber) {
dest_city = city;
dest_state = state;
departureDate = dDate;
departureTime = dTime;
flight_number = flightNumber;
}
public String toString() {
return "Flight number: " + flight_number + " Destination: " + dest_city + "," + dest_state + " Departing on:" + departureDate + " at" + departureTime + ".";
}
}
public class dummy {
public static void main(String[] args) {
// Uses the constructor to set values
Flights flight1 = new Flights("Houston", "Texas", "12/20/2014", "12:40 pm", 100);
System.out.println(flight1);
System.out.println(flight_number); // Error: `flight_number` cannot be resolved to a variable.
}
}
You need to add a public getter in Flights and call it from main:
public class Flights {
// all the private fields
public int getFlightNumber() {
return this.flight_number;
}
}
In Main:
public static void main(String[] args) {
Flights flight1 = new Flights("Houston", "Texas"); //...
System.out.println(flight1);
System.out.println(flight1.getFlightNumber()); // call the getter
}
You should start with an editor like eclipse and that should help you get started quickly. Getters and Setters is what you need, but start with Eclipse and you should do better.

Console Display for System.out.println(refVar name)

How can System.out.println(refVar name) give the output shown by this example's website? I understand why "Simcard object constructed" gets displayed, but why do the remaining fields get displayed in that specific order: "New Sim card constructed for nokia 1100."
My understanding is that fields can't just be outputted by calling a reference name.
(http://www.hubberspot.com/2012/07/how-composition-has-relationship-works.html)
class SimCard {
private String cardNumber;
public SimCard(){
System.out.println("SimCard Object Constructed");
cardNumber = "New SimCard Constructed";
}
#Override
public String toString() {
return cardNumber;
}
}
public class Mobile {
private SimCard sim = new SimCard();
private String mobile = "Nokia";
private int model = 1100;
#Override
public String toString() {
return sim + " for " + mobile + " " + model;
}
public static void main(String[] args) {
Mobile mob = new Mobile();
System.out.println(mob);
}
}
The mobile/model are getting created when you create the new instance
Mobile mob = new Mobile()
They get set to their defaults as specified in the class.
Then when you output the class the overidden String method is called which returns the output to main and it is printed.

Categories

Resources