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.
Related
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)
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);
}
Edited the getTypeString method in the Flowers class now I just get the pointer to the object
I'm working on a project for one of my classes. I haven't worked with HashMap before and I need to use one. In this java class I'm trying to print out the full description that I have set. But it wont print the HashMap value from the key. I have tried to use some code from my book, but with no luck.
This is the class that is calling the class that has the HashMap:
public class Garden
{
private Gardener gardener;
private Tools tools;
private Flowers flowers;
/**
* Constructor for objects of class Garden
*/
public Garden()
{
gardener = new Gardener();
tools = new Tools();
Flowers rose;
rose = new Flowers("a beautiful red flower");
rose.setFlower("red", rose);
System.out.println(rose.fullDescription());
}
}
Edited the getTypeString method
This is the class that is using the HashMap:
import java.util.Set;
import java.util.HashMap;
public class Flowers
{
private String fDescription;
private HashMap<String, Flowers> flowers;
/**
* Constructor for objects of class Flowers
*/
public Flowers(String fDescription)
{
this.fDescription = fDescription;
flowers = new HashMap<String, Flowers>();
}
public void setFlower(String color, Flowers type)
{
flowers.put(color, type);
}
public String flowerDescription()
{
return fDescription;
}
public String fullDescription()
{
return "The "+ getTypeString() + " is " + fDescription;
}
private String getTypeString()
{
String des = "";
Collection<Flowers> vals = flowers.values();
for(Flowers f : vals){
des += f;
}
return des;
}
}
The problem, I think, is in the getTypeString() function. Can anyone point me in the right direction?
Edit
I removed the getTypeString method and edited the fullDescription method:
public String fullDescription()
{
return "The "+ type + " is " + fDescription;
}
now I'm trying to get the 'HashMap' to print the objects like so:
"Flower [type= type, description= Description "]"
using thes methods:
public static void printHashMap()
{
System.out.println("hashmap: " + flowers);
}
#Override
public String toString()
{
return "Flower [type=" + type + ", description=" + fDescription ]";
}
From your post, what I have understood is that you want to print the description of flowers. So I think you can try something like:
private String getTypeString(){
String des = "";
Collection<String> vals = flowers.values();
for(String f : vals){
des = des + f.flowerDescription();
}
return des;
}
Override the toString method in your class
Declare a toString method with the following modifiers and return type:
#Override
public String toString() {
return this.fDescription;
}
Implement the method so that it returns a string.
Create and implement a class Person. A Person has a firstName and friends. Store the names of the friends as a String, separated by spaces. Provide a constructor that constructs a Person with a given name (passed through arguments) and no friends. Provide the following methods:
public void befriend(Person p)
public void unfriend(Person p)
public String getFriendNames()
public int getFriendCount()
*Hint - you can use p.name to access the name of the Person passed to a method as an argument.
Include a Tester class to make sure your Person has some friends.
How do I store the names of the friends as a String, separated by spaces. (I have to be able to input the names from the main method). I also have no idea how to get rid of already inputted name using the method "unfriend"
public class Person
{
private String firstName;
private String friendNames;
private int friendCount;
public Person(String name)
{
firstName = name;
friendCount = 0;
}
public String getFriendNames()
{
return friendNames;
}
public double getFriendCount()
{
return friendCount;
}
public void befriend(String name)
{
friendNames = friendNames + " " + name;
friendCount++;
}
public void unfriend(String name)
{
String[] parseNames = friendNames.split(name);
friendNames = parseNames[0] + parseNames[1];
friendCount--;
}
}
Main Method:
public class PersonTester {
public static void main(String[] args) {
Person p = new Person("Alex");
p.befriend("John");
p.befriend("Alice");
p.befriend("Mike");
p.befriend("Annette");
p.unfriend("Alice");
System.out.println(p.getFriendCount());
System.out.println(p.getFriendNames());
}
}
Expected output:
2
John Mike
The problems you are having with the methods using the parameter(Person p) are because you have two different variables: friendName (which exists) and name (which does not). Changing the variable friendName to name will take care of some of the errors you are receiving.
(Also the method getFriendCount() returns friendsCount, but should return friendCount (you have an extra s in there) and your assignment calls for a method called befriend, not bestFriend.)
How to delete friends:
You can delete a friend by parsing the friend out of the friendNames string and then concatenating the two resulting strings back together:
public void unfriend(String name)
{
String[] parseNames = friendNames.split(name);
friendNames = parseNames[0] + parseNames[1];
friendCount--;
}
I would suggest changing befriend and unfriends parameters to accept a String instead of a Person object. Person already has access to its own object and in your main you are trying to pass them Strings anyways. Here is what befriend should look like:
public void befriend(String name) //Changed to "befriend"
{
friendNames = friendNames + " " + name;
friendCount++;
}
Also, you only need one constructor for Person, which should look like this:
public Person(String name)
{
firstName = name;
friendCount = 0;
}
When I run your program (using these changes) I get the following output:
2.0
John Mike
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.