Trying to create a class that contains objects from another class - java

I have created a class called Album, which is this one:
public class Album {
private String Titulo;
private int temas;
private int ano;
public Album(String Titulo2, int temas2, int ano2) {
this.Titulo = Titulo2;
this.temas = temas2;
this.ano = ano2;
}
public Album(String Titulo2, int temas2) {
this.Titulo = Titulo2;
this.temas = temas2;
}
public int getAno() {
return this.ano;
}
public int getTemas() {
return this.temas;
}
public String getTitulo() {
return this.Titulo;
}
public void setAno(int ano) {
this.ano = ano;
}
public boolean foiEditadoNesteSeculo() {
if (this.ano > 2000) {
return true;
} else {
return false;
}
}
public void adicionaTemasBonus(int x) {
this.temas += x;
}
public void mostraAlbum() {
System.out.println(this.Titulo + " (editado em " + this.ano + "; tem " + this.temas + " temas)");
}
}
It works fine. The problem is that the teacher asked me to create a new class called Band and it has to have an array of Albums. The Band object should be declared with an int that represents the limit of the number of albums (the length of the array). I already have some idea on how to work with arrays, but I have no idea on how to create a type of array that contains objects from another class, and after how to use the attributes of the objects to return something. I think I can figure out the rest after I'm able to properly create the class, though.
Apologies, as it has been described in Portuguese and I don't have much experience in translating.

In my opinion this would be easier to manage with a List so you can add as many Albums as you want at any time, however, since the problem statement required Array I made an example of a Band class.
I also included main method to test the program at the bottom of the Band class:
public class Band {
private int totalAlbums;
private Album[] albums;
private int currentNumberOfAlbums;
public Band(int totalAlbums) {
this.totalAlbums = totalAlbums;
this.albums = new Album[totalAlbums];
this.currentNumberOfAlbums = 0;
}
public Band(Album[] albums) {
this.totalAlbums = albums.length;
this.albums = albums;
this.currentNumberOfAlbums = this.totalAlbums;
}
public void addNewAlbum(String titulo, int temas, int ano) {
if (this.currentNumberOfAlbums == totalAlbums) {
System.out.println("Warning: Cannot add any more albums, limit reached.");
return;
}
this.albums[this.currentNumberOfAlbums++] = new Album(titulo, temas, ano);
}
public void printAlbums() {
for (Album a : this.albums) {
a.mostraAlbum();
}
}
public static void main(String [] args) {
Band b = new Band(3);
b.addNewAlbum("The First", 4, 2001);
b.addNewAlbum("The Second", 98, 2055);
b.addNewAlbum("The Finale", 12, 2011);
b.addNewAlbum("The Extra", 12, 2111);
b.printAlbums();
}
}
There are a few things to look for in this code.
First, to address your direct question, you can simply use a custom class as an array like any other class/primitive with Album[].
Secondly, you will require a Band constructor that instantiates the array of Album based on an integer passed to it, so you know how many albums are the limit. You can see this with the this.albums = new Album[totalAlbums]; line.
Next, you need a way to add a new Album into the array of Album[]. This can be done a few different ways, but the way I chose was to create a method addNewAlbum(String, int, int) to do it for this example which will also increase currentNumberOfAlbums by 1 every time a new album is added. This is useful so you know when an Album is attempted to be added even though the totalAlbums are already full! This will prevent an ArrayIndexOutOfBoundsException in your code if addNewAlbum is called too many time.
Lastly, in addNewAlbum you need to call your Album constructor with new Album(titulo, temas, ano).
In my example main, a Band with limit of 3 albums is created, and 4 albums are attempted to be added into it, with the first 3 adding successfully, and the 4th not being added, but instead printing a warning for being outside the limit.
I also added a printAlbums() method which will use your mostraAlbum() to print each Album in the albums array.
Output:
Warning: Cannot add any more albums, limit reached.
The First (editado em 2001; tem 4 temas)
The Second (editado em 2055; tem 98 temas)
The Finale (editado em 2011; tem 12 temas)
EDIT:
I added the Band(Album[] albums) constructor, you can call this with:
Album[] albums = new Album[3];
//Add your albums into this variable
Band b = new Band(albums);

public class Band {
private Album[] albums;
private numberOfAlbums;
//...
// create an empty constructor
Band(){
albums = new Album[];
numberOfAlbums = 0;
}
// constructor that receives the albums
Band(Album[] albums){
this.albums = albums;
this.numberOfAlbums = albums.length;
}
// constructor that receives the number of albums
Band(int numOfAlbums){
this.numberOfAlbums = numOfAlbums;
this.albums = new Album[numOfAlbums];
}
// add getters and setters
// example of adding a new album
public void addNewAlbum(Album album){
if(this.numOfAlbums == this.albums.length){
// you need to create a new array with a bigger size, copy the existing data and insert the album
// or whatever you'd like
} else {
this.albums[this.numOfAlbums] = album;
// increment the numOfAlbums
this.numOfAlbums++;
}
}
}
private class Album {
//...
}

You just need to add [] to define that the field is an array.
public class Band {
private int totalAlbums;
private Album[] albums;
//...
}
private class Album {
//...
}

I hope this example helps you.
private Album[] albums; // array of album
private int albumLimit; // limit for album
public Band(int albumLimit) {
this.albumLimit = albumLimit; // initialize limit
this.albums = new Album[albumLimit]; // set limit of album array
}
// here it creates a new Album every time the loop runs
// you can fill the array in other ways too
public void fillAlbum() {
for (int i = 0; i < albumLimit; i++) {
String name = "name_" + i;
int team = i;
albums[i] = new Album(name, team);
}
}
public void printAlbum() {
for (int i = 0; i < albumLimit; i++) {
System.out.println("Name :" + albums[i].getTitulo());
System.out.println("Team :" + albums[i].getTemas());
System.out.println();
}
}
}

Related

My super class variables are null when accessing them from childclass

I am having a problem when trying to print my ticket(child class) which is all my superclass variables are null or zero not initialized.
this is my superclass:-
public class movie {
protected int movieID;
protected String movieTitle;
movie(){};
movie(int movieID , String movieTitle ){
this.movieID = movieID;
this.movieTitle = movieTitle;
}
}
this is my childclass
public class ticket extends movie{
private int Number_of_ticket;
private int show_number ;
ticket(int Number_of_ticket , int show_number){
this.Number_of_ticket = Number_of_ticket;
this.show_number = show_number;
}
public void print_the_tacket(){
System.out.println("movie id is " + super.movieID);
System.out.println("movie name is " + super.movieTitle);
System.out.println("number of the ticket is " + Number_of_ticket);
System.out.println("show number is " + show_number);
}
}
the main
public class Main {
public static void main(String[] args) {
movie MyMovie = new movie(1234, "spiderman");
ticket myticket = new ticket(34 , 334);
myticket.print_the_tacket();
}
}
my output is
movie id is 0
movie name is null
number of the ticket is 34
show number is 334
I expect when I print my ticket the movie information why I am getting null values What is wrong here? thank you in advance.
When you reference super in the child class, it not bound to the Movie object you created in the main(). That is why you are getting a null value. Look here when I debug the code.
If you want to access the Movie object you created in main(), you can pass it and that will work.
To explain..
Note 1: There are 2 constructors created here. One is movie() without arguments, the other is with 2 arguments. What you extend and call is #1 not #2
public class movie {
protected int movieID;
protected String movieTitle;
movie() { //#1 - no args, so movieID=null, movieTitle=null
//you can debug by adding this line.
this.movieID = 1;
this.movieTitle = "I should not be printing this";
}
movie(int movieID , String movieTitle ){ //#2 - has args.
this.movieID = movieID;
this.movieTitle = movieTitle;
}
}
Note 2: Your problem is in ticket, when you do not write super(..) with args you are passing nothing, hence it is calling movie() without parameters. So if you are calling movie(), you get non declared variables. If you see sample above for debug you should see 1 and "I should not print this" instead to explain the scenario.
public class ticket extends movie{
private int Number_of_ticket;
private int show_number ;
ticket(int Number_of_ticket , int show_number){
//Not visible, but actually triggers super() and calling movie #1, not super(arg1, args2)
//super(1,"movie")
this.Number_of_ticket = Number_of_ticket;
this.show_number = show_number;
}
}
Note 3: You are making 2 different objects, object #1 is movie, and object #2 is ticket. To me it seems you only want 1 object which is ticket that extends movie. What happens here is that the codes are 2 different/seperated objects and they are not tied together.
public class Main {
public static void main(String[] args) {
movie MyMovie = new movie(1234, "spiderman"); //#Object 1
ticket myticket = new ticket(34 , 334); //#Object 2
myticket.print_the_tacket();
}
}
Approach: You may want the codes to be the following way where you create movie and ticket together in ticket call. This means when you create ticket your movie must be created. In a nutshell no movie created, no tickets to issue.
public class Movie { //Class name should always be captialized
protected int movieID; //you can declare final
protected String movieTitle;
Movie(int movieID , String movieTitle ){ //Only this
this.movieID = movieID;
this.movieTitle = movieTitle;
}
}
public class Ticket extends Movie { //Captialize class
private int Number_of_ticket; //should avoid _ and use Snakecase
private int show_number ;
Ticket(int Number_of_ticket , int show_number, int movieID, String movieTitle){
super(movieId, movieTitle); //always and must create movie object
this.Number_of_ticket = Number_of_ticket;
this.show_number = show_number;
}
public void print_the_tacket(){ //should use snake case printTheTacket
System.out.println("movie id is " + super.movieID);
System.out.println("movie name is " + super.movieTitle);
System.out.println("number of the ticket is " + Number_of_ticket);
System.out.println("show number is " + show_number);
}
}
public class Main {
public static void main(String[] args) {
Ticket myticket = new Ticket(34 , 334, 1234, "spiderman");
myticket.print_the_tacket();
}
}
Much ideal is that movie is created in ticket instead of passing 2 arguments or extending. In this case both are separated and tied and incase in future movie has also things like PG-13, GA parameters you can expand it. But i guess it's for school understanding on inheritance, your example fits for now.
public class Ticket {
private int numberOfTickets;
private int showNumber ;
private Movie movie;
Ticket(int numberOfTickets , int showNumber, Movie movie){
this.numberOfTickets = numberOfTickets;
this.showNumber = showNumber;
this.movie = movie
}
public void printTheTacket(){
System.out.println("movie id is " + movie.movieID);
System.out.println("movie name is " + movie.movieTitle);
System.out.println("number of the ticket is " + numberOfTickets);
System.out.println("show number is " + showNumber);
}
}

Issue with referncing objects that do not have a name

I´m new to programming and I have this task to implement a simple booking System for bus tickets.
We´re supposed to implement a method that adds new bus routes using the attributes: busNumber, start, destination, price, currency. To save the bus routes I´m using an arraylist and save new objects like this:
Booking.add(new Booking(1, "France", "Latvia", 2.05, Currency.EUR))
My issue now is working with those objects since they don´t have a name. I don't know the exact number of objects, so I have to do it this way (i think so at least). Where the issue occurred is at the method "remove", that is supposed to remove a bus route. I thought I could use an Iterator to iterate through the ArrayList and compare the busNumbers but it´s not working.
Another issue I have is, that when I want to print all the objects in my Array list it just prints the last object as many times as there are objects in my ArrayList. Also, my method and attributes are all static now otherwise I wouldn´t know how to use them in another class.
Does anybody has some advice for a newbie please?
My Code is below:
import java.util.ArrayList;
import java.util.Iterator;
public class Booking {
static int busNumber;
static int customerID = 1; //First customerID starts with 1
static String name;
static double price;
static int invoiceNumber = 1; //First invoicenumber starts with 1.
static String start;
static String destination;
static Currency currency;
static ArrayList<Booking> bookable = new ArrayList<Booking>();
//Constructor
public Booking(int busNumber, String start, String destination, double price, Currency currency) {
this.busNumber = busNumber;
this.start = start;
this.destination = destination;
this.price = price;
this.currency = currency;
}
public int getBusNumber() {
return busNumber;
}
public static void add(Booking add) { // add-method. Adds the bus routes to the booking system
bookable.add(add);
}
public static void remove(int busNumber) { // Here´s one of my issues. That´s what i have.
Iterator<Booking> it = bookable.iterator();
if ( == busNumber) {
bookable.remove(it);
}
}
public static void listRoute() {
for (Booking element : bookable) {
Terminal.printLine(toString(element));
}
}
public static String toString(Booking element) {
return "000" + busNumber + " " + start + " " + destination + " " + price + " " + currency;
}
}
My second class which is later supposed to be the UI:
public class Input {
public static void main(String[] args) {
Booking.add(new Booking(1, "Mannheim", "Karlsruhe", 2.05, Currency.EUR));
Booking.add(new Booking(2, "Heidelberg", "Karlsruhe", 3.05, Currency.JPY));
Booking.add(new Booking(3, "Germersheim", "Karlsruhe", 4.05, Currency.USD));
Booking.listRoute();
}
}
The Output is: "0003, "Germersheim", "Karlsruhe", 4.05, Currency.USD" 3 times..

Adding objects to ArrayList [duplicate]

This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
(5 answers)
Closed 6 years ago.
This if my first question on stackoverflow. I can usually find answers myself but I'm having trouble with this one. I've got 2 objects, "Book", and "Periodical". These are subclasses to a class "Publication". Now, I'm trying to add 3 instances of "Book" and 3 instances of "Periodical" to an ArrayList. I'm having trouble figuring out how to do this.
With this current code, I get an error "no suitable method found for add(Book,Book,Book,Periodical,Periodical,Periodical).
Here is the current code:
import java.util.ArrayList;
import java.util.Date;
public class DriverProgram {
public static void main(String[] args) {
// Instantiate 3 instances of each object.
Book book1 = new Book(1234, 1, "James", 100, "Hello", "Berkwood Inc.", new java.util.Date(), "History");
Book book2 = new Book(2345, 2, "Ralph", 200, "Goodbye", "Shackles Co.", new java.util.Date(), "English");
Book book3 = new Book(3456, 3, "Julia", 300, "Hello Again", "Trustin Inc.", new java.util.Date(), "History");
Periodical periodical1 = new Periodical("Daily", "Dylan", "History 101", "History Inc.", new java.util.Date(), "History");
Periodical periodical2 = new Periodical("Weekly", "Jannette", "Mathematics 101", "Mathematics Inc.", new java.util.Date(), "Mathematics");
Periodical periodical3 = new Periodical("Monthly", "Patricia", "Science 101", "Science Inc.", new java.util.Date(), "Science");
// Create an array list of the Publication class type, and add the objects to it.
ArrayList <Publication> publications = new ArrayList<Publication>();
publications.add(book1, book2, book3, periodical1, periodical2, periodical3);
// Pass the array list to a method to loop through it and display the toString methods.
displayObjects(publications);
} // End of main
static void displayObjects (ArrayList<Publication> publications) {
// Loop through array list and display the objects using the toString methods.
for (Publication p : publications) {
System.out.print(p.toString());
} // End of for each loop
} // End of displayObjects
} // End of DriverProgram class
I've also tried changing:
publications.add(book1, book2, book3, periodical1, periodical2, periodical3);
To this:
publications.add(book1);
publications.add(book2);
publications.add(book3);
publications.add(periodical1);
publications.add(periodical2);
publications.add(periodical3);
Which rids my program of the compiler error, but then it just prints the "periodical3" object, 6 times. I'm not sure what I'm doing wrong. Any suggestions? Thank you in advance! :)
EDIT:
Here is my Book class:
public class Book extends Publication{
private static int isbn = 0;
private static int libraryOfCongressNbr = 0;
private static String author = "";
private static int nbrOfPages = 0;
// Constructor for Book class with parameters for each attribute.
public Book(int newISBN, int newLibraryOfCongressNbr, String newAuthor, int newNbrOfPages, String newTitle, String newPublisher, java.util.Date newPublicationDate, String newSubject) {
super(newTitle, newPublisher, newPublicationDate, newSubject);
isbn = newISBN;
libraryOfCongressNbr = newLibraryOfCongressNbr;
author = newAuthor;
nbrOfPages = newNbrOfPages;
}
/////////////////////////////////////////////////////// Getters ///////////////////////////////////////////////////////
int getISBN() {
return isbn;
}
int getLibraryOfCongressNbr() {
return libraryOfCongressNbr;
}
String getAuthor() {
return author;
}
int getNbrOfPages() {
return nbrOfPages;
}
/////////////////////////////////////////////////////// Setters ///////////////////////////////////////////////////////
void setISBN(int newISBN) {
isbn = newISBN;
}
void setLibraryOfCongressNbr(int newLibraryOfCongressNbr) {
libraryOfCongressNbr = newLibraryOfCongressNbr;
}
void setAuthor(String newAuthor) {
author = newAuthor;
}
void setNbrOfPages(int newNbrOfPages) {
nbrOfPages = newNbrOfPages;
}
//toString method for Book class
public String toString () {
StringBuilder result = new StringBuilder();
result.append("\nISBN: " + isbn + "\n");
result.append("\nPublisher: " + libraryOfCongressNbr + "\n");
result.append("\nAuthor: " + author + "\n");
result.append("\nNumber of Pages: " + nbrOfPages + "\n");
result.append("--------------------------------------------------------- ");
return super.toString() + result.toString();
} // End of toString
} // End of Book class
My Periodical class is identical, but here is my Publication class:
import java.util.Date;
public abstract class Publication {
// Data fields.
private static String title = "";
private static String publisher = "";
private static java.util.Date publicationDate;
private static String subject = "";
// Constructor for Publication class with parameters for each attribute.
public Publication(String newTitle, String newPublisher, java.util.Date newPublicationDate, String newSubject){
title = newTitle;
publisher = newPublisher;
publicationDate = newPublicationDate;
subject = newSubject;
}
/////////////////////////////////////////////////////// Getters ///////////////////////////////////////////////////////
String getTitle() {
return title;
}
String getPublisher() {
return publisher;
}
java.util.Date getPublicationDate() {
return publicationDate;
}
String getSubject() {
return subject;
}
/////////////////////////////////////////////////////// Setters ///////////////////////////////////////////////////////
void setTitle(String newTitle) {
title = newTitle;
}
void setPublisher(String newPublisher) {
publisher = newPublisher;
}
void setPublicationDate(java.util.Date newPublicationDate) {
publicationDate = newPublicationDate;
}
void setSubject(String newSubject) {
subject = newSubject;
}
//toString method for Publication class
public String toString () {
StringBuilder result = new StringBuilder();
result.append("\nTitle: " + title + "\n");
result.append("\nPublisher: " + publisher + "\n");
result.append("\nPublication Date: " + publicationDate + "\n");
result.append("\nSubject: " + subject + "\n");
return result.toString();
} // End of toString
} // End of Publication class
Let me know if you need anything else!
EDIT x2: Sorry, I realize my post is getting quite long.
So I've gotten rid of all "static" keywords from my class variables, or "data fields" as I've called them in my code. I then changed my code back to this code:
ArrayList <Publication> publications = new ArrayList<Publication>();
publications.add(book1);
publications.add(book2);
publications.add(book3);
publications.add(periodical1);
publications.add(periodical2);
publications.add(periodical3);
And it works! It executes as it should! I just one question though, since this code doesn't seem to work:
publications.add(book1, book2, book3, periodical1, periodical2, periodical3);
Is there a shorter way to add all of the objects to the ArrayList with out doing it one by one?
If I understand the problem correctly, you have 6 Publication objects, and you are only seeing the values of the most recently created one.
That would likely be caused because you have static class variables instead of instance variables.
For example
class A {
static int x; // class variable
int y; // instance variable
public A(int val) {
x = val; // All 'A' classes now have x = val;
y = val; // Only 'this' class has y = val;
}
}
If I were to run this
A a1 = new A(4);
A a2 = new A(5);
System.out.println(a1.x);
Then I would see it print 5 and not 4, which describes the scenario you are seeing because you have assigned all variables in the Publication class to those that you use during the last call of new Periodical.
The solution is to not use static variables if you want to have multiple instances of a class with their own values.

Storing object into an array - Java

I am relatively new to Java and I have taken some light courses on it. I am trying to emulate an exercise that I had a while back and I am having some trouble.
I have two classes. One is taking in data and the other is storing it.
public class Car{
public Car(String name, String color)
{
this.name = name,
this.color = color
}
How can I store this into the array (not an array list) that I created in this class:
public class CarDatabase {
Car[] carList = new Car[100];
public CarDatabase()
{
// System.out.println("test");
}
public void createAccount(String name, String color)
{
// this is where I am having trouble
for (int i = 0; i < carList.length; i++)
{
System.out.println("Successfully created: " + name +
"." + "Color of car: " + color);
break;
}
}
I don't have a main method yet but I will need one later on to for example, PRINT out this array and that is what I can't wrap my head around - how do I store DATA/OBJECTS into the "CarDatabase" array so I can call methods with it later (instead of just being able to print it)?
Any help would be appreciated.
Thanks!
Not really sure what you are trying to achieve but I'll give it a go.
You could modify your CarDatabase class like so -
public class CarDatabase {
Car[] carList = new Car[100];
int carsStored;
// No need for a constructor since we don't need any initialization.
// The default constructor will do it's job.
public void createAccount(String name, String color) {
carList[carsStored++] = new Car(name, color);
}
}
And your main method could look like -
public static void main(String[] args) {
CarDatabase database = new CarDatabase();
database.createAccount("Lambo", "Red");
database.createAccount("Punto", "White");
// To loop through your database, you can then do
for(int i = 0; i < database.carList.length; i++) {
Car car = database.carList[i];
// Now you can call methods on car object.
}
}
Hope that helps.

Creating multiple objects within a class

I am trying to create a class. Let's call it Questionnaire. In Questionnaire, I want to instantiate a number of classes called Question. The constructor for Questionnaire accepts a string array of words, and for each word, there should be a Question class to accept it as an argument for its constructor. In other words, for every string that is passed as an argument, I want to create a Question.
I need to be able to put Questionnaire within a bigger class and still call the methods of the Question classes. The size of the array passed to Questionnaire varies as well. I don't know how I can put multiple classes within another class when I don't know how many classes there will be, and how to reference them from an outer class. If the array was a fixed length I'd just create Questions as question1, question2, question3... but since this is not the case I am not sure anymore. I do know there is a maximum number of Question classes I want to create though.
edit: I'm using J2ME CDLC 1.1 MIDP 2.0 for this (it's part of a mobile phone app) so my solutions are constrained by what it offers.
You don't want to have a separate variable per question - use a List<Question> to have one variable which refers to a collection of questions:
public class Questionnaire
{
private final List<Question> questions;
public Questionnaire(String[] words)
{
questions = new ArrayList<Question>();
for (String word : words)
{
questions.add(new Question(word));
}
}
// Use questions here
}
EDIT: If you're in an environment without generics, you could use the non-generic form, like this:
private final List questions;
public Questionnaire(String[] words)
{
questions = new ArrayList();
for (String word : words)
{
questions.add(new Question(word));
}
}
or like this if you don't have List/ArrayList:
private final Vector questions;
public Questionnaire(String[] words)
{
questions = new Vector();
for (String word : words)
{
questions.add(new Question(word));
}
}
In either case you'll need to cast on every access. Alternatively, you could use an array:
private final Question[] questions;
public Questionnaire(String[] words)
{
questions = new Question[words.length];
for (int i = 0; i < words.length; i++)
{
questions[i] = new Question(word);
}
}
As J2ME API lacks the Collections API, your best bet is to grab a Vector.
Vector questions = new Vector();
for (int i = 0; i < words.length; i++) {
questions.addElement(new Question(words[i]));
}
You probably want to go with a Set of questions rather than List. Try :
private final Set<Question> questions;
This will prevent duplicate questions. Everything else will be the same as JonSkeet's answer.
Why don't you use a List on the questionaire and for each question you add you add one to the List, for example.
public class Questionnaire
{
public List<Question> myQuestions {get; private set;}
public Questionnaire(string[] questions)
{
myQuestions = new List<Questions>();
foreach(string q in questions)
{
myQuestions.Add(new Question {questionText = g});
}
}
}
public class Question
{
public string questionText {get; set;}
}
Then you will be able to check the questions from outside... this is what you want?
Hope this helps
EDIT: ohh is Java, but you got the idea right?
import java.util.*;
public class Questionnaire implements Iterable<Question> {
private final List<Question> questions;
public Questionnaire(String ...words) {
questions = new ArrayList<Question>(words.length);
for(String word : words) {
questions.add(new Question(word));
}
}
// allows you to use a Questionnaire object in a for-each loop
public Iterator<Question> iterator() { return questions.iterator(); }
#Override
public String toString() { return questions.toString(); }
}
You could add many more goodies to your class to make it more useful. An example of using the class above follows:
public class QuestionnaireTest {
public static void main(String[] words) {
Questionnaire questionnaire = new Questionnaire(words);
for(Question q : questionnaire) {
System.out.println("You asked: " + q);
}
}
}
You could also use it as follows:
public class QuestionnaireTest3 {
public static void main(String[] words) {
// because I declared the constructor to accept "String ...words", I can specify as many questions as I want using simple syntax
Questionnaire questionnaire = new Questionnaire("How deep the ocean?", "How high the moon?");
for(Question q : questionnaire) {
System.out.println("I asked: " + q);
}
}
}
Even though I did so in my first example above, you should really accept an array of String objects as questions. Here's a better design:
public class Questionnaire implements Iterable<Question> {
private List<Question> questions = new ArrayList<Question>();
public void add(Question q) {
if(q == null) throw new IllegalArgumentException("can't add null question!");
questions.add(q);
}
public Question get(int index) {
if(index < 0 || index >= questions.size()) throw new IndexOutOfBoundsException("invalid question index: " + index);
return questions.get(index);
}
// allows you to use a Questionnaire object in a for-each loop
public Iterator<Question> iterator() {
return Collections.unmodifiableList(questions).iterator();
}
#Override
public String toString() { return questions.toString(); }
}
public abstract class Question {
public String getText();
public String getAnswer();
public String getOptions();
// ...
}
public class YesNoQuestion extends Question {
private final String text;
private final String answer;
public YesNoQuestion(String text, boolean answer) {
if(!(text.startsWith("Is"))) throw new IllegalArgumentException("Must start with is: " + text);
this.text = text;
this.answer = answer ? "Yes" : "No"; // if answer == true, the "Yes",...
}
#Override
public String getText() { return text; }
public String getAnswer() { return answer; }
public String getOptions() { return "Yes or No ?"; }
}
And now you can use it as follows:
public class QuestionnaireTest4 {
public static void main(String[] words) {
Questionnaire test = new Questionnaire();
test.add(new YesNoQuestion("Is dogs animals?", false));
test.add(new YesNoQuestion("Is me has cheezburgers?", true));
for(Question q : questionnaire) {
System.out.println(q);
System.out.println(q.getOptions());
String input = null; // you need to code this part
if(q.getAnswer().equals(input))
System.out.println("CORRECT!");
else
System.out.println("YOU IS STUPID!!!!");
}
}
}

Categories