This is probably a bad question, but i have constructed a DVD object in java:
DVD myDVD = new DVD (11.17 , 9 , 120 , " Howl ’s Moving Castle " , " Hayao Miyazaki " );
I have a toString to print the whole object, but I've been asked to print the director (Hayao Miyazaki) of the object without the rest, is there a way to do this?
If you need any more information in order to help, please comment. Thanks
create a get method for the director
public String getDirector(){
return director;
}
System.out.print(myDVD.getDirector());
Assuming your code is Java code, in your DVD class, you can override the toString method in order to print what you want:
public class DVD {
private String director;
//more fields and stuff
#Override
public String toString() {
return director;
}
}
If you already have a toString implementation and need another one, you can add another method to get the director:
public String getDirector(){
return director;
}
and print it:
System.out.print(myDVD.getDirector());
Or you may want a method to do the printing itself:
public void printDirector() {
System.out.println(director);
}
You could make it as simple as writing a new method printDirector() which would do just that, OR...
You could leave the responsibility of printing the information to some other class, and make the DVD object responsible only for providing its information:
public class Movies {
public class DVD {
private director;
public DVD(String director) {
this.director = director;
}
public String getDirector() {
return director;
}
}
public static void main(String... arg) {
DVD howl = new DVD("Miyazaki");
String director = howl.getDirector();
SomePrinterClass.print(director);
}
}
Ultimately that's a design decision, either will produce the same result.
Related
The pet store program should start with the user being able to choose to adopt a pet or give a pet the to the shop. If the user wants to adopt a pet, they should be able to see either all available pets, unless they say they know what type of pet they want, then show only available pets of that type.
The 4 methods that will need to be created for this program should:
add new pets
get a pet adopted
show pets by type
show pets available for adoption
Object Class: Pets.java
import java.util.*;
public class Pets {
public static void main(String[] args){
private double age; // age of the animal (e.g. for 6 months the age would be .5)
private String petName; // name of the animal
private String aType; // the type of the pet (e.g. "bird", "dog", "cat", "fish", etc)
private int collarID; // id number for the pets
private boolean isAdopted = false; // truth of if the pet has been adopted or not
private String newOwner;
private Date adoptionDate;
public double getAge() {
return age;
}
public void setAge(double age) {
this.age = age;
}
public String getPetName() {
return petName;
}
public void setPetName(String petName) {
this.petName = petName;
}
public String getaType() {
return aType;
}
public void setaType(String aType) {
this.aType = aType;
}
public int getCollarId() {
return collarID;
}
public void setCollarId(int collarId) {
this.collarID = collarId;
}
public boolean isAdoptated() {
return isAdopted;
}
public void setAdoptated(boolean isAdoptated) {
this.isAdopted = isAdoptated;
}
public Date getAdoptionDate() {
return adoptionDate;
}
public void setAdoptionDate(Date adoptionDate) {
this.adoptionDate = adoptionDate;
}
#Override
public String toString() {
return "Pets [age=" + age + ", petName=" + petName + ", aType=" + aType + ", collarId=" + collarID
+ ", isAdoptated=" + isAdopted + ", adoptionDate=" + adoptionDate + "]";
}
}
}
You should define the data fields and methods inside the class, but not inside the main()-method. The main()-method is the entry point of your java application and could be used to create an instance of your Pets class.
e.g.:
public static void main(String[] args) {
Pets pet = new Pets();
}
This code is not compiling for 2 main reasons:
You are specifying access modifiers on variables inside a method (in this case main), which is forbidden;
You are writing methods (e.g. getAge) inside another method (main) and trying to return a variable (e.g. age) that is out of that scope, in fact the variable age is not known inside the getAge method, because it's declared in the main method.
You should move the variable declaration to class level, and then have all methods separated using those variables. I'll give you a sketch, not the complete solution:
import java.util.*;
public class Pets {
/* Insert all variable declarations here */
private double age;
/* Constructor if you need it */
public Pets(/* parameters you think you need */) {
// Set attributes when you declare a new Pets()
}
/* Insert all methods you need here */
public double getAge() {
return this.age;
}
The positioning of the main method - for what I've understoon from your description - should be placed outside this class, in another class where the whole application will start to run. The Pet class should serve only for anything concerning pets (the four methods you will need to implement and all getters/setters for retrieving private class variables).
You’ve happened to put about everything — private fields and public methods — inside you main method. That doesn’t make sense. Everything that is in your main, move it outside, right under the line public class Pets {. That should fix your compiler error.
I can't figure out the way to save the supplierName value in a class object. I'm trying to change it in an addItem method using user input, and store it in a class object. It doesn't work. What am I doing wrong? Do I need to change my constructor? Or use a getter method?
Here is my code:
import java.util.Scanner;
public class PurchasedItem extends Item {
private String suppplierName;
public PurchasedItem() {}
#Override
public boolean addItem(Scanner input) {
super.addItem(input);
System.out.print("Enter the name of the supplier: ");
suppplierName = input.next();
return true;
}
#Override
public String toString() {
String str = super.toString();
return str + " Supplier: " + suppplierName;
}
}
A solution is to allow the constructor to take an argument such as:
public PurchasedItem(String constructorArgument){
supplierName = constructorArgument;
}
Then, you can do something like: PurchasedItem item = new PurchasedItem("some supplier");.
Since the class variable is private, you will also need getters/setters.
For instance:
Setter:
public void setSupplierName(String s){
this.supplierName = s;
}
Getter:
public String getSupplierName(){
return this.supplierName
}
Then to manipulate, you'd do something like:
item.setSupplierName("some company");
item.getsupplierName();
Though, you should be conscious of thread safety in regards to utilising setters.
This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 6 years ago.
So in my code, I made a class named Pet, that would have both a default constructor and a non-default constructor that passes in String name, and int age of the pet.
public class Pet
{
// instance variables
private int age;
private String name;
/**
* Constructor for objects of class Pet
*/
public Pet()
{
// initialise instance variables
age = 0;
name = "somePet";
}
public Pet(int age, String name)
{
this.age = age;
this.name = name;
}
}
Then I created a class named petArray that would add to the array and print out the array...
public class PetArray
{
// instance variables
private Pet [] petArray;
/**
* Constructor for objects of class PetArray
*/
public PetArray()
{
// initialise instance variables
petArray = new Pet[5];
}
public void addPets()
{
// put your code here
Pet myPet = new Pet(4, "Spots");
petArray[0] = (myPet);
petArray[1] = new Pet(2, "Lucky");
petArray[2] = new Pet(7, "Joe");
}
public void printPets()
{
for (int i = 0; i < petArray.length; i++)
{
System.out.println(petArray[i]);
}
}
}
But then, I get this in the terminal window when trying to print it out...
Pet#13255e3c
Pet#171ac880
Pet#52185407
null
null
You forgot to override toString() method inherited from Object.
In this case you can use something like this:
#Override
public String toString() {
return (name + age);
}
Java compiler just does not know how to print it, you have to inform it :)
In your addPets() method you are only adding 3 objects to your petArray while there are 2 more spaces you need to fill as you declared that array to be a length of 5.
You could change the length of your array down to 3 or you could add 2 more objects, that should fix your problem.
And as stated above, adding the toString method will get rid of the addressing issues.
class Pet {
...
#Override
public String toString(){
// the string passed from here will be shown in console
}
}
Your output is fine according to your code. You have to override toString() method to print as per your requirement. Add this may be it will help.
#override
public string toString(){
return "your required string"; // i.e : name or name+age
}
I have a problem with an implementation of ArrayLists - I try to print my objects, but right now it only prints the memory adresses. I figure a loop is my savior somehow, but can't for the love of... figure out how to loop through my Course objects to make that happen. What am I missing? It can't be impossible or anything, it's just me being to stupid to figure it out (my forehead has a permanent imprint of my keyboard now).
public class Course{
private String courseID;
private String courseName;
private int ap;
private static ArrayList<Course> courses = new ArrayList<Course>();
public static void main(String[] args) {
Course programmeringGrund = new Course ("725G61", "Programmering Grundkurs", 6);
Course itProjekt = new Course ("725G62", "IT-Projektledning - introduktion", 12);
Course diskretMatematik = new Course ("764G06", "Diskret Matematik och Logik", 6);
Course informatikTeknik = new Course ("725G37", "Informatik, teknik och lärande", 6);
System.out.println(getCourses());
} public Course (String aCourseID, String aCourseName, int anAp){
this.courseID=aCourseID;
this.courseName=aCourseName;
this.ap=anAp;
courses.add(this);
} public static List getCourses(){
return courses;
}
You need to override the toString() method in Course. The "memory address" printed is part of Object's toString() method, and you haven't overridden toString().
public class Course
{
...
#Override
public String toString()
{
return "ID=" + courseID + ", Name=" + courseName;
}
...
}
You have two options:
Traverse the List returned by getCourses() and print out values for each course object. Something like
ArrayList<Course> mycourses = getCourses();
for(Course obj: mycourses)
{
System.out.println("Id is "+obj.courseId);// So on you print everything
}
OR You can override the toString() Method in you Course class as ZouZou mentioned. As you haven't over ridden the toString() method as of now it is printing the memory address for the List
I am a beginner programmer and this is my first question on this forum.
I am writing a simple text adventure game using BlueJ as a compiler, and I am on a Mac. The problem I ran into is that I would like to make my code more self automated, but I cannot call a class with a string. The reason I want call the class and not have it all in an if function is so that I may incorporate more methods.
Here is how it will run currently:
public class textadventure {
public method(String room){
if(room==street){street.enterRoom();}
}
}
public class street{
public enterRoom(){
//do stuff and call other methods
}
}
The if statement tests for every class/room I create. What I would like the code to do is automatically make the string room into a class name that can be called. So it may act like so:
Public method(string room){
Class Room = room;
Room.enterRoom();
}
I have already looked into using Class.forName, but all the examples were too general for me to understand how to use the function. Any help would be greatly appreciated, and if there is any other necessary information (such as more example code) I am happy to provide it.
-Sebastien
Here is the full code:
import java.awt.*;
import javax.swing.*;
public class Player extends JApplet{
public String textOnScreen;
public void start(){
room("street1");
}
public void room(String room){
if(room=="street1"){
textOnScreen=street1.enterRoom();
repaint();
}
if(room=="street2"){
textOnScreen=street2.enterRoom();
repaint();
}
}
public void paint(Graphics g){
g.drawString(textOnScreen,5,15);
}
}
public abstract class street1
{
private static String textToScreen;
public static String enterRoom(){
textToScreen = "You are on a street running from North to South.";
return textToScreen;
}
}
public abstract class street2
{
private static String textToScreen;
public static String enterRoom(){
textToScreen = "You are on another street.";
return textToScreen;
}
}
Seeing as you are rather new to programming, I would recommend starting with some programs that are simpler than a full-fledged adventure game. You still haven't fully grasped some of the fundamentals of the Java syntax. Take, for example, the HelloWorld program:
public class HelloWorld {
public static void main(String[] args) {
String output = "Hello World!"
System.out.println(output);
}
}
Notice that public is lowercased. Public with a capital P is not the same as public.
Also notice that the String class has a capital S.* Again, capitalization matters, so string is not the same as String.
In addition, note that I didn't have to use String string = new String("string"). You can use String string = "string". This syntax runs faster and is easier to read.
When testing for string equality, you need to use String.equals instead of ==. This is because a == b checks for object equality (i.e. a and b occupy the same spot in memory) and stringOne.equals(stringTwo) checks to see if stringOne has the same characters in the same order as stringTwo regardless of where they are in memory.
Now, as for your question, I would recommend using either an Enum or a Map to keep track of which object to use.
For example:
public class Tester {
public enum Location {
ROOM_A("Room A", "You are going into Room A"),
ROOM_B("Room B", "You are going into Room B"),
OUTSIDE("Outside", "You are going outside");
private final String name;
private final String actionText;
private Location(String name, String actionText) {
this.name = name;
this.actionText = actionText;
}
public String getActionText() {
return this.actionText;
}
public String getName() {
return this.name;
}
public static Location findByName(String name) {
name = name.toUpperCase().replaceAll("\\s+", "_");
try {
return Enum.valueOf(Location.class, name);
} catch (IllegalArgumentException e) {
return null;
}
}
}
private Location currentLocation;
public void changeLocation(String locationName) {
Location location = Location.findByName(locationName);
if (location == null) {
System.out.println("Unknown room: " + locationName);
} else if (currentLocation != null && currentLocation.equals(location)) {
System.out.println("Already in room " + location.getName());
} else {
System.out.println(location.getActionText());
currentLocation = location;
}
}
public static void main(String[] args) {
Tester tester = new Tester();
tester.changeLocation("room a");
tester.changeLocation("room b");
tester.changeLocation("room c");
tester.changeLocation("room b");
tester.changeLocation("outside");
}
}
*This is the standard way of formating Java code. Class names are PascalCased while variable names are camelCased.
String className=getClassName();//Get class name from user here
String fnName=getMethodName();//Get function name from user here
Class params[] = {};
Object paramsObj[] = {};
Class thisClass = Class.forName(className);// get the Class
Object inst = thisClass.newInstance();// get an instance
// get the method
Method fn = thisClass.getDeclaredMethod(fnName, params);
// call the method
fn.invoke(inst, paramsObj);
The comments below your question are true - your code is very rough.
Anyway, if you have a method like
public void doSomething(String str) {
if (str.equals("whatever")) {
// do something
}
}
Then call it like
doSomething("whatever");
In Java, many classes have attributes, and you can and will often have multiple instances from the same class.
How would you identify which is which by name?
For example
class Room {
List<Monster> monsters = new ArrayList <Monster> ();
public Room (int monstercount) {
for (int i = 0; i < monstercount; ++i)
monsters.add (new Monster ());
}
// ...
}
Monsters can have attributes, and if one of them is dead, you can identify it more easily if you don't handle everything in Strings.