I'm a newbie to Java and I attempt to achieve Polymorphism with the requirements of using the following:
super keyword
overriding
having more than two classes
getting the user's input
using do-while
creating objects
It doesn't have any errors but I doubt if it still makes any sense.
Does it follow Polymorphism still? If not, How can I improve it?
Here is my code:
public class Sample Code {
public static void main(String[] args) {
//declare variables
String name, fSong;
int aNum;
fSong = " ";
Zayn a1 = new Zayn();
a1.makeMusic();
Songs a2 = new Songs();
a2.setName("Zayn");
a2.displayName();
a2.makeMusic();
Lyrics a3 = new Lyrics();
a2.displayName();
a3.makeMusic();
//get values
Scanner in = new Scanner (System.in);
do{
System.out.print("Enter Your Name (2-20 characters): ");
name = in.nextLine();
}while(name.length() < 2 || name.length() > 20);
System.out.print("\nCHOOSE YOUR FAVORITE SONG :\n\n");
System.out.print("[1] Pillowtalk \n");
System.out.print("[2] Dusk Till Dawn\n");
do{
System.out.print("\nEnter Your Choice (1-2): ");
aNum = in.nextInt();
}while(aNum < 1 || aNum > 2);
//determine aNum
if(aNum == 1) {
fSong = "Pillowtalk";
}else if(aNum == 2){
fSong = "Dusk Till Dawn";
}
//Display output
System.out.print("\n[OUTPUT]\n\n");
System.out.printf("Your Name: %s\n", name);
System.out.printf("Your Favorite song of Zayn is: %s.\n", fSong);
}
}
class Zayn{
String name;
Zayn(){
this.name = this.name;
}
void makeMusic(){
System.out.println("Zayn makes music");
}
}
//superclass
class Songs extends Zayn{
Songs(){
super();
}
void makeMusic(){
System.out.println("Pillowtalk Lyrics: Pillowtalk, my enemy, my ally\n");
}
public void setName (String newName){
this.name = newName;
}
void displayName(){
System.out.println("\nName of Artist: " + this.name);
}
}
class Lyrics extends Zayn{
#Override
void makeMusic(){
System.out.println("Dusk Till Down Lyrics: I'll be with you from dusk till dawn\n");
}
}
So I don't think that will compile: public class Sample Code { as an example.
Does it follow Polymorphism
It sorta demonstrates it, but it doesn't look like a clear application of the principle.
What's a Zayn, and why is a Song a Zayn and a Lyric is a Zayn?
Polymorphism is to represent a hierarchical typing of your objects. E.g. you could have Animal as base class, with Mammal and Reptile extending. This can be further extrapolated to have Dog and Cat extend from Mammal, while Lizard and Snake extend from Reptile.
Bear in mind that if class Foo extends class Bar then any instance of Foo is also a Bar. This is sometimes called a "is-a" relationship, because in this scenario, a Foo is a Bar.
Related
I am trying to make a to do list that asks you to enter your tasks one by one then display them in order (as in 1. task1, 2. task 2, 3. task 3 etc). But when it displays the tasks it comes back as "0. null" one time instead of listing any of the tasks entered. Here is the script I am using:
1st class
package todolist;
import java.util.ArrayList;
public class ToDoList1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<ToDoList2> list = new ArrayList<ToDoList2>();
System.out.println("Time to make a digital to-do list!");
ToDoList2 n = new ToDoList2();
list.add(n);
System.out.println(ToDoList2.name + "'s to-do list");
System.out.println(ToDoList2.i + ". " + ToDoList2.l);
for(ToDoList2 enhanced : list)
{
System.out.println(ToDoList2.i + ". " + ToDoList2.m);
}
}
}
2nd class
package todolist;
import java.util.Scanner;
public class ToDoList2 {
public static String name;
public static int i;
public static String l;
public static String m;
{
Scanner s = new Scanner(System.in);
System.out.println("First type your name to identify your list in case you lose it");
name = s.nextLine();
System.out.println("Make sure to type \"end\" when you are finished");
System.out.println("Type in the first item on your to-do list");
String l = s.nextLine();
}
public ToDoList2()
{
Scanner s = new Scanner(System.in);
for(int i = 1; i == i; i++)
{
System.out.println("Type in the next item for your to-do list");
String m = s.nextLine();
if("end".equals(m))
{
break;
}
}
}
}
Your code is not correct. ToDoList2 scanning item list from standard input but not storing it. You should do as follow
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class TodoList {
public static String name;
List<String> tasks;
public TodoList(String name) {
this.name = name;
this.tasks = new ArrayList<>();
}
public void addTask(String task) {
this.tasks.add(task);
}
public String toString() {
int i = 1;
StringBuilder stringBuilder = new StringBuilder();
for (String task : tasks) {
stringBuilder.append(i + ". " + task);
stringBuilder.append("\n");
i++;
}
return stringBuilder.toString();
}
}
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("First type your name to identify your list in case you lose it");
String name = s.nextLine();
System.out.println("Make sure to type \"end\" when you are finished");
System.out.println("Type in the first item on your to-do list");
TodoList todoList = new TodoList(name);
String task = null;
while (!(task = s.nextLine()).equals("end")) {
todoList.addTask(task);
System.out.println("Type in the next item for your to-do list");
}
System.out.println(todoList);
}
}
a) Given that each ToDoList2 object is a separate task, I'm not sure why you've made the object class members static?
b) In your ToDoList2 constructor, you've got a for loop that introduces a local variable i which hides the ToDoList2 member variable i. You'd do well to change one of the variable names.
c) In your ToDoList2 constructor, you've got a for loop which is assigning a string returned by the Scanner to a local variable m. Are you sure you want m to be a local variable or do you actually want to assign the returned string to the member variable, m? I'm thinking the latter since the member variable m is never being assigned a value which explains why the code is printing out null.
d) When writing code, it is good practice to use meaningful variable names. Using names like i is OK as an index in a loop but in all other circumstances, you should go for something more descriptive that tells the reader what the variable is storing.
e) Consider making all your ToDoList2 member variables private (and final if possible). Add a print function to the ToDoList2 class to print out the task details. A key principle is Object Oriented Programming is to hide the internals of a class.
I'm finding it hard to use my methods even if I correctly instantiated my objects. Any ideas on where I went wrong?
example: I tried compiling the java file but the error I get is
"incompatible types: String cannot be converted to Books"
I think the problem is my instantiated object is being forced into a string but the problem is I used the correct syntax to call on a string. However, it still doesn't read it as a string and says that the instantiated object cannot be converted to the "Books" class.
I've already searched about it but all they say is the object hasn't been created. However, I checked my code and I already instantiated my object even before putting it into the method parameter.
I even tried to print the object on its own with the specific characteristics and it turned out fine. So I guess it goes right up until it gets put into a method.
One thing I don't understand is that I need that object to be referenced into a method.
Here is my code:
class Books{
String type;
int pages;
Books[] booklist;
int bookcounter = 0;
//Constructor to initialize the object "book"
Books(int input){
if(input == 1){
this.type = "Math";
this.pages = 5;
}
if(input == 2){
this.type = "Physics";
this.pages = 9;
}
if(input == 3){
this.type = "Economics";
this.pages = 20;
}
}
//This method needs to add the instantiated object to the array list
void addbooktype(Books kind){
System.out.println("You chose: " + kind);
System.out.println("Adding to the list...");
booklist[bookcounter++] = kind;
}
void printbooks(){
for(int i = 0; i <= bookcounter; i++){
int y = i+1;
System.out.println("Book #"+ y + "is: " +this.booklist[i].type);
System.out.println("With pages of: " + this.booklist[i].pages);
}
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int bookchoice;
int choice;
String booktype;
int booknum = 0;
do{
System.out.println("===========Menu===========");
System.out.println("[1] - Pick a book \n[2] - Print book list\n[0] - Exit");
System.out.println("==========================");
System.out.print("Choice: ");
choice = sc.nextInt();
switch(choice){
//Selects and adds a book to the list
case 1:
System.out.println("Choose your book: ");
bookchoice = sc.nextInt();
Books book = new Books(bookchoice);
System.out.println(book.type);
booktype = book.type;
book.addbooktype(booktype);
booknum++;
break;
//Prints the book list
case 2:
System.out.println("List of Books: ");
book.printbooks();
break;
case 0:
System.out.println("Exit");
return;
default: System.out.println("Input not found.");
}
}while(choice!=0);
}
}
The errors I get is on the "book.addbooktype(booktype);"
This is where it bugs me, I printed the objected and even put it into a String container but it still rejects it. I don't know where I went wrong. And when it goes into the method it doesn't read the parameter. Any thoughts?
Your method addbooktype requires a parameter of Books type whereas you wanted a String parameter there
void addbooktype(Books kind){
Your code would work if you would make this slight change:
void addbooktype(String kind){
Edit: As per the comments, it seems I misunderstood the code. That being said, here's what you can do:
Replace
book.addbooktype(booktype);
with
book.addbooktype();
and replace
void addbooktype(Books kind){
System.out.println("You chose: " + kind);
System.out.println("Adding to the list...");
booklist[bookcounter++] = kind;
}
with
void addbooktype(){
System.out.println("You chose: " + this.kind);
System.out.println("Adding to the list...");
booklist[bookcounter++] = this;
}
This would add the currently calling object to your array and allow you to use it later.
The issue is that your method accepts Object of Class Book only. However when you are calling that function
book.addbooktype(booktype);
You are giving it type String (In your book class type is String variable). To fix that you either need to pass book object or change the method itself
Passing the book object:
Books book = new Books(bookchoice);
book.addbooktype(book);
and in function you can do something like this
void addbooktype(Books book) {
System.out.println("You chose: " + book.type);
System.out.println("Adding to the list...");
booklist[bookcounter++] = book;
}
(Added Later) Using This:
This approach also utilizes the object however it is better than the approach described above. Instead of passing the object as a parameter which is redundant you can use java word this.
According to java docs Using the this Keyword
Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.
So when you call function
book.addbooktype(book);
^ and ^ are same
| |
Inside the method addbooktype
void addbooktype(Books book) {
this and book would also be same.
}
so instead you could do this
book.addbooktype();
and addbooktype would be
void addbooktype() {
System.out.println("You chose: " + this.type);
System.out.println("Adding to the list...");
booklist[bookcounter++] = this;
}
An example where passing object and this would be useful is when you have to compare objects. Lets say you have two objects book1 and book2. You would do something like this
int compareResult = book1.compareTo(book2);
Your method would be
public int compareTo(Book book) {
Now here this would be book1
and book would be book2
Also keep in mind this.type would be same as type. type and this.type are both
referring to same object i.e who we called function on (book1).
}
Changing the function:
or you can just change you function like this though I suggest you pass the object itself. If you just pass the String you won't be able to store it in Books[] booklist
void addbooktype(String type) {
System.out.println("You chose: " + type);
System.out.println("Adding to the list...");
// The line below will give error unless you change Books[] booklist;
// to String[] booklist;
booklist[bookcounter++] = kind;
}
So I'm new to coding/Java and I'm working on this project. My assignment is to create 3 different classes (which I have here) and make a them cooperate. I've successfully made my FishTankManagerApp class retrieve a new Fish object and I'm trying to figure out how to put it in a FishTank object.
My FishTank class only is only there to create an array object which can hold 5 fish (I think I've done this correctly). In my FishTankManagerApp class, I've created an array of 10 of these FishTank Objects.
My question which I cant figure out for the life of me is how do I place the Fish objects into a specfic FishTank object after they've been created (I've made a note at the end of the code where I've ran into a problem).
Essentially I know I'm trying to put an object I've created inside of and array which contains another array where fish objects can be stored... I think....
Any help would be much appreciated! Thank you!
import java.util.Scanner;
public class Fish {
private static Scanner stdin = new Scanner(System.in);
private String userInput;
private int userInput2;
public boolean mean;
public String name;
public Fish(){
System.out.println("What is your fishes name?");
userInput = stdin.next();
this.name = userInput;
System.out.println("Is this fish aggressive?\n"+
"(1)Yes\n(2)No");
userInput2 = stdin.nextInt();
if (userInput2 == 1)
this.mean = true;
else
this.mean = false;
}
}
public class FishTank {
public FishTank(){
Fish[] tank = new Fish[5];
}
}
import java.util.Scanner;
public class FishTankManager {
private static Scanner stdin = new Scanner(System.in);
private static int userInput;
private static FishTank[] tanks = new FishTank[10];
public static void main (String[] args) {
while (true){
System.out.println("Welcome to your new fish tank manager!\n"+
"What would you like to do?\n"+
"(1)Add a Fish\n(2)Move a Fish\n"+
"(3)Check a tank");
userInput = stdin.nextInt();
if (userInput == 1){
Fish fish = new Fish();
System.out.println(fish.name);
System.out.println(fish.mean);
changeTank(fish);
}
else if(userInput ==2){
}
else{
}
}
}
private static void changeTank(Fish fish){
System.out.println("Which tank would you like to put this fish in? (1-10)");
userInput = stdin.nextInt();
tanks[userInput] = fish;
// This last line is where I'm confused on how to put the fish() object into a tank which I've created.
}
}
I'd recommend adding a method to your FishTank to make adding the fish easy. Maybe something like this:
public FishTank(){
private Fish[] tank = new Fish[5];
public boolean addFish(Fish fish) {
// ... add code here to put the fish to the tank array
// return true if there was room in the tank, false otherwise
}
}
Note that the tank variable is now private. It's generally a good idea to keep member variables private in Java, and use methods to access them.
Then, where you've got the comment you mentioned, you can just call the new method:
boolean addedSuccessfully = tanks[userInput].addFish(fish);
You may not need to return the boolean as I'm showing, but it might be handy if you need to check whether the array (i.e. the tank) had room for the new fish.
Currently, what you're doing is setting the FishTank object equal to a Fish instance - not adding it to the tank variable inside of FishTank.
Right now, you have no way of accessing the tank variable inside of the FishTank class. What you need to do is make it a global variable and provide accessor/modifier methods. For example:
public class FishTank {
private Fish[] tank;
private int numFish;
public FishTank(){
this.tank = new Fish[5];
this.numFish = 0;
}
public void add(Fish f){
if(this.numFish >= 5){
//handle "tank is full" case
}
else{
numFish++;
this.tank[numFish] = f;
}
}
}
Then invoke add on the desired FishTank object:
tanks[userInput].add(fish);
I am running into some issues with my Java program. We have to create a library, which contains the title(halo, lotr) , the format (xbox, dvd etc), the date loaned (if it is ever loaned), and the person it is loaned to (if it is ever loaned).
I am not complete with my code, however I am testing it out as I go along instead of just compiling the entire finished code after 5 hours of coding. I am running into a problem. Whenever I set a public string variable to a value, it saves in the method I declared it in, but it will display "null" when system.out.print'd in other methods.
heres my code. First class is Library.
package p1;
import java.util.Scanner;
public class Library {
// \/ FIELDS
private String[] mediaItemTitle = new String[100];
public String[] mediaItemFormat = new String[100];
public String[] mediaItemLoanedTo = new String[100];
public String[] mediaItemOnLoan = new String[100];
public String[] mediaItemDateLoaned = new String[100];
public String today = "3/9/2015";
public int numberOfItems;
// /\ FIELDS
// \/ METHODS
public static void main(String[] brad){
Scanner input = new Scanner(System.in);
MediaItem main;
main = new MediaItem();
String title;
String format;
String date;
String name;
for ( int i = 0; i != 5; ){
i = displayMenu();
if (i == 1){
System.out.println("What is the title? ");
title = input.nextLine();
System.out.println("What is the format? ");
format = input.nextLine();
main.MediaItem(title,format);
}else if (i == 2){
System.out.println("Which Item (Enter the title? ");
title = input.nextLine();
System.out.println("Who are you loaning it to? ");
name = input.nextLine();
System.out.println("When did you loan it to them? ");
date = input.nextLine();
}else if (i == 3){
main.MediaItem();
}else if (i == 4){
System.out.print("Which item? (enter the title) ");
title = input.nextLine();
main.markReturned(title);
}else if (i == 5){ // DONE
System.out.print("Goodbye!");
break;
}
}
}
public static int displayMenu(){ // DONE
Scanner input = new Scanner(System.in);
int choice = 0;
System.out.println("1. Add new item");
System.out.println("2. Mark an item as on loan");
System.out.println("3. List all items");
System.out.println("4. Mark an item as returned");
System.out.println("5. Quit");
choice = input.nextInt();
return choice;
}
public void addNewItem(String title, String format){
this.mediaItemTitle[numberOfItems] = title;
this.mediaItemFormat[numberOfItems] = format;
System.out.print("TEST: " + mediaItemTitle[numberOfItems]);
}
public void incrementNumberOfItems(){
numberOfItems++;
}
public void listAllItems(){
for (int i = 0; i < numberOfItems; i++){
System.out.print(mediaItemTitle[i])
}
}
Here is the second part of code, my second class MediaItem
package p1;
public class MediaItem {
// \/ METHODS
public void MediaItem(){
Library list;
list = new Library();
list.listAllItems();
}
public void MediaItem(String title, String format){
Library call;
call = new Library();
call.addNewItem(title, format);
call.incrementNumberOfItems();
}
// /\ METHODS
}
This is driving me insane. I would love to just have me public variables save their value between methods but its not happening. the console (when 3 is chosen from displayMenu)
0
null
which means numberOfItems and mediaItemTitle[i] are read to be 0, and null. Which I dont understand, because I declared them earlier in the program!!!
I dont understand what Im doing wrong. please help me! Thank you!!
Your main mistake is that you are creating a new instance of Library inside your MediaItem method. That Library object will only live in the scope of MediaItem method. Plus Library is your main static class.
Your design is all wrong in my opinion. It looks like you are learning you way to Java or OOP, which is perfectly fine to have these mistakes.
Separate your data from your main class, create new classes just for your data. Have a look at java POJO (Plain Old Java Objects), like here
For example:
String title;
String format;
String date;
String name;
Should be in a new object, a POJO. Something like:
public class MyDataPOJO {
private String title;
private String format;
private String date;
private String name;
public MyDataPOJO(String title, String format, String date, String name) {
this.title = title;
this.format = format;
this.date = date;
this.name = name;
}
public String getTitle() {return title;}
public String getFormat() {return formate;}
// And the rest of the getter methods for date and name
}
In you Library class you may only need to hold your logic. But even that can be re-factored to another class.
On a side note, please check the java naming convention. Here is a guideline: link. In other words, start you methods name with lower case.
Example, your public void MediaItem(){/** something*/} should be public void mediaItem(){/** something*/ }
Follow the answer above and treat this as a comment, since the persons answer is correct and my statement isn't regarding your primary problem.
In your for-loop, I think you should add another else if statement. If the user enters a number that is not 1-5, they should receive an error. So maybe something like
else if (i < 1 || i > 5)
System.out.println("Error: Enter a choice 1-5\n");
Also, I think you may have forgotten a } to end your listAllItems() method.
But as I was saying, the answer to your real problem has already been handled, so give them the check mark. This is just a minor UI error I noticed.
These are the instructions for this assignment. Any help would be appreciated. I am a rookie when it comes to java and cant seem to figure this out.
This exercise has two classes. The first class is named ObjectsToArrayList. The second class is called just Objects.
Your responsibility is to create the Object class and figure out how the ObjectsToArrayList class works.
The ObjectsToArraylist class will create an ArrayList of objects. It will ask for and populate the data fields of an Object, then add it to the ArrayList. This can be done for as many instances of the Object that the user wants to enter.
Requirements for the Object Class.
2 data fields: int obj_id, String obj_name.
2 Constructors: No-Arg and one that takes both values and assigns them to the data field.
Gets and sets for both data fields
A toString() method that returns output like:
The object ID is 22 and the name is Andrea
Here's my code
import java.util.*;
/**
*
* #author Student
*/
public class ObjectsToArrayList {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList <Object> objectList = new ArrayList();
System.out.println("Please enter information for your favorite object!");
do { // collect an indicator to determine the method to call
Object object = new Object();
System.out.println("Enter a whole number for the ID of your object:\n"
+ "or enter 99 to quit.");
int tmpInt = input.nextInt();
// if 99 is entered exit the loop.
if (tmpInt == 99) {
break;
}
object.setObj_id(tmpInt);
input.nextLine();
// ask for the Object Name
System.out.println("Please enter the name of the Object:");
object.setObj_name(input.nextLine());
objectList.add(object);
} while (true); // this is a contineous loop if the break isn't included.
for(Object object:objectList) {
System.out.println(object.toString());
}
}
}
//****************************************************
//**** Objects Class is below this block **
//****************************************************
class Object {
// enter object code here (This is the part I cannot figure out)
}
Here are examples of constructors:
class Objects{
// This is a constructor with no argument
public Objects(){
}
// This is a constructor with 2 arguments
public Objects(int obj_id, String obj_name){
}
}
You can refer in the link below to learn more about creating constructors and assigning values to fields:
http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html
Note: Do not use Object as a class because Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class.
http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html
Try something like this:
public class ObjectsToArrayList {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList <Object> objectList = new ArrayList();
System.out.println("Please enter information for your favorite object!");
do { // collect an indicator to determine the method to call
Object object = new Object();
System.out.println("Enter a whole number for the ID of your object:\n"
+ "or enter 99 to quit.");
int tmpInt = input.nextInt();
// if 99 is entered exit the loop.
if (tmpInt == 99) {
break;
}
object.setObj_id(tmpInt);//runs the setObj_id method in the Objects class
//for the users input
input.nextLine();
// ask for the Object Name
System.out.println("Please enter the name of the Object:");
object.setObj_name(input.nextLine());//runs the setObj_name method in the Objects class
//for the users input
objectList.add(object);
} while (true); // this is a contineous loop if the break isn't included.
for(Object object:objectList) {
System.out.println(object.toString());//prints out what the toString method returns in
//the Objects class
}
}
}
//****************************************************
//**** Objects Class is below this block **
//****************************************************
public class Objects
{
//add stuff like methods and instance variables
private int ID;
private String name;
public Objects(){//default constructor
}
public Objects(int i, String n){//constructor to change both ID and name at the same time
ID = i;
name = n;
}
public void setObj_id(int i){//constructor to change only ID
ID = i;
}
public void setObj_name(String n){//constructor to change only name
name = n;
}
public String toString(){
return (name + ": " + ID);
}
}
Ok so you want to create your own object soo have 2 classes rather, personProfile and arrayOfProfiles
So class personDetails object note seperate class file not *not in same file
class personProfile{
private int ID = 0;
private String Name = "";
public personProfile(int id,String name){
ID = id;
Name = name;
}
public int getID(){
return ID;
}
public String getName(){
return name;
}
}
now the other class* different file
class arrayOfProfiles{
personProfile profiles[] = new personProfile[0];
public personProfile[] array(){
return profiles;
}
public void addProfileToArray(personProfile profileObject){
personProfile arrayMod = new personProfile[profiles.length+1];
for(int i = 0;i<profiles.length;i++){
arrayMod[i] = profiles[i];
}
arrayMod[arrayMod.length-1] = profileObject;
}
public static void main(String args[]){
arrayOfProfiles profiles = new arrayOfProfiles();
for(int i = 0;i<5;i++){
int id = Integer.parseInt(JOptionPane.showInputDialog("enter ID ");
String name = JOptionPane.showInputDialog("enter name");
profiles.addProfileToArray(new personProfile(id,name));
}
for(int i =0;i<profiles.array().length;i++){
System.out.println("ID :"+profiles[i].getID()+" name - "+profiles[i].getName());
}
}
}