Here are my instructions:
This assignment is already past due and my professor said he would comment on it to help me understand but I think he is too busy & it's irking my soul that I can't get it right so.... here i am... Any help would be wonderful.
ToDo List
You will be handing in 2 classes. ToDoItem.java (defines the data type of a To Do Item) and MyList.java (the driver that allows the user to enter data, create ToDoItems, and manage ToDoItems).
Design a class for a ToDoItem. A ToDoItem keeps track of an item you need to do (as a string), the date it is due (hmmm, what is a good way to do this?), the priority of that item (1 is high, 2 is medium, 3 is low), and if that item is or is not completed.
Sketch-out a rough UML diagram of what this class would look like and what methods you would need for this class. You must include this with your assignment. You may use a CASE tool like ArgoUML or you can simply hand draw the diagram and submit a picture with your assignment.
You must provide a constructor that accepts arguments for this class to set the object's default state.
Write an overloaded method so that a user can set priority by int (1, 2, 3) or String ("high", "medium", "low").
Then, write a simple menu-driven program that allows a user to create ToDo Items, delete them, view them all unsorted, and mark them as completed. Please see the attached file MyList.java for a small framework to help make your menu system more organized.
ToDo Notes & Hints
The attached file MyList.java is a basic framework for a simple command-line driven ToDo list. Use this as the basis for your ToDo assignment. There is a lot missing from this starter file but it will help you get up and running quicker.
import java.util.ArrayList;
import java.util.Scanner;
public class MyList {
public static ArrayList todoItems = new ArrayList();
public static void main(String[] args) {
while(true) {
printMenu();
processInput();
}
}
public static void printMenu() {
System.out.println("[a]dd an item");
System.out.println("[p]rint all");
System.out.println("[q]uit");
}
public static void processInput() {
Scanner s = new Scanner(System.in);
String input = s.next();
if(input.equals("a")) {
//addToDoItem();
}
else if(input.equals("p")) {
//printAll();
}
else if(input.equals("q")) {
System.exit(0);
}
}
// implement rest of processInput methods here
}
Each feature such as create, view, delete, and mark read should be defined as a method so that your code can be easily read.
Your ToDoItem class should have NO code related to user interface in it. Keep your user interface code separate from your data (this advice is based on a pattern called Model-View-Controller or MVC). This means your ToDoItem class might be pretty basic and that your "driver" file with your main method is doing most of the work.
Use an Array or ArrayList to store your ToDoItems. Reference individual ToDoItems by their index in that data structure (print the index of each item when printing all ToDoItems).
Once a ToDoItem is created it can NOT be edited beyond being marked as completed. If the user mistypes a date or incorrectly spells the title that item can only be deleted and then recreated to be fixed. This is to simplify the assignment.
Again, marking an item as complete/incomplete is the only aspect of a ToDoItem that can be edited. Objects that cannot be edited are called immutable.
ToDo Program Thoughts
Here are some things to think about that we will address in a few weeks in this course. I included these items now so you can start to think about them.
What if we wanted to sort our items by date due or by priority or by both? - -Don't write this, just think about how we might do this.
What makes one ToDo -item less than, equal to, or greater than another?
We are writing a lot of code to manage our array of ToDoItems. What, if anyways, might we simplify this?
I have a video of a demo of the program: https://youtu.be/9eWkn7uOLs0
Here are the codes I have written so far. I am stuck and having trouble parsing my date and getting it to print out.
MyList.java
import java.util.Scanner;
import java.util.ArrayList;
import java.io.*;
import java.text.*;
public class MyList {
public static ArrayList<ToDoItem> toDoItems = new ArrayList<>();
public static Scanner k = new Scanner(System.in);
private static String description;
private static String dueDate;
public static void main(String[] args) throws ParseException {
while(true) {
printMenu();
processInput();
}
}
public static void printMenu() {
System.out.println("[a]dd an item");
System.out.println("[d]elete an item");
System.out.println("[t]oggle complete");
System.out.println("[p]rint all");
System.out.println("[q]uit");
}
public static void processInput() throws ParseException{
Scanner s = new Scanner(System.in);
String input = s.next();
if(input.equals("a")) {
addToDoItem();
}
else if(input.equals("d")) {
//deleteToDoItem();
}
else if(input.equals("t")) {
// toggleComplete();
}
else if(input.equals("p")) {
printAll();
}
else if(input.equals("q")) {
System.exit(0);
}
}
public static ToDoItem addToDoItem() throws ParseException {
ToDoItem newItem;
newItem = null;
System.out.print("Enter an item to add to list: ");
String desc = k.nextLine();
if(desc.trim().length()==0) return newItem;
System.out.print("Enter Date (MM/dd/YYYY): ");
String dueDate = k.nextLine();
System.out.print("Enter priority between 1 and 3 (3 being the highest): ");
String prior = k.nextLine();
int p = Integer.parseInt(prior);
if(dueDate.trim().length()==0){
newItem = new ToDoItem(desc);
}
else {
newItem = new ToDoItem(desc, dueDate);
}
newItem.setPriority(p);
return newItem;
//toDoItems.add(new ToDoItem(desc, p, dueDate));
}
public static void printAll() throws ParseException {
ToDoItem item = new ToDoItem();
System.out.println(item);
//ToDoItem task = newItem.get(i);
// ***************
// You should not need to create ToDoItems here
// This method should loop through your array and print out each item
// Since you have a toString() method you can print the objects by passing
// them into like so inside of a loop System.out.println( item.get(i) )
//for(int i = 0; i < newItem.size(); i++) {
// System.out.println(toDoItems.get(i));
// }
// for(ToDoItem myItem : toDoItems) {
//ToDoItem myItem = toDoItems.get(i);
//System.out.println(myItem);
// System.out.println(myItem.getDescription()+" -"+myItem.getPriority()+"- ("+myItem.getDueDate()+")");
}
}
//public static void deleteToDoItem() {
// **********
// You won't need a loop here, you can directly
// delete the item at the given index.
// Prompt for an int, read in the int, then call item.remove(i);
//System.out.print("Enter index of item to delete: ");
//int delete = k.nextInt();
//toDoItems.remove(i);
// }
// public static void toggleComplete() {
/////
// }
//}
ToDoItem.java
import java.text.*;
import java.util.Date;
//import java.lang.NullPointerException;
public class ToDoItem {
private String description;
private Date dueDate;
private int priority;
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
public ToDoItem() {
}
public ToDoItem(String desc) {
description = desc;
dueDate = null;
priority = 0;
}
public ToDoItem(String desccription, String dDate) throws ParseException {
this.description = description;
dueDate = df.parse(dDate.trim());
}
public String toString() {
if(dueDate != null) {
return( description + " -"+priority+"- " + "Date not Set");
}
else {
return( description + " -"+priority+"- " + df.format(dueDate));
}
}
public void setPriority( int prio) {
if(prio<0) this.priority = 0;
else if(prio > 3) this.priority = 3;
else this.priority = prio;
}
public int getPriority() {
return this.priority;
}
public void setDueDate(String date) throws ParseException {
Date d = df.parse(date.trim());
this.dueDate = d;
}
public String getDescription() {
return description;
}
public String getDueDate() {
if(dueDate == null) return "";
return df.format(dueDate);
}
}
If you have a problem with parsing and printing out your Date-type maybe this could help you:
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
String dateString = sdf.format(new Date());
Date date = null;
try {
date = sdf.parse("10/16/2015");
} catch (ParseException objcPException) {
// TODO Auto-generated catch block
objcPException.printStackTrace();
}
System.out.println(date);
System.out.println(dateString);
You have to change this method:
public ToDoItem(String desccription, String dDate) throws ParseException {
this.description = description;
dueDate = df.parse(dDate.trim());
}
to this:
public ToDoItem(String desccription, String dDate) throws ParseException {
this.description = description;
dueDate = sdf.parse(dDate);
}
and switch your DateFormat to SimpleDateFormat like this in my example.
Maybe you have to validate the form of the input first (MM/dd/yyyy) before parsing.
Replace the following code
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
with statement below and try
SimpleDateFormat df = new SimpleDateFormat("MM/dd/YYYY");
So, the constructor will use this dateformat to parse the input.
dueDate = df.parse(dDate.trim());
When user presents date in a format (MM/dd/YYYY) and is read as a string, best way is to parse it using dateformat. Check the following similar example from (stackoverflow). You can run it and check.
String string = "January 2, 2010";
DateFormat format = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH);
Date date = format.parse(string);
System.out.println(date);
Hope it helps.
Related
Good day, is there a more efficient way to do this problem with recursion than using a switch statement. In my courses class I have a recursive association of course and a prerequisite then a set the preReqs in the PreReqs class. How can I print out all of preReqs of a class when a user enter a class which has preReqs? Right now I am in the process of using a switch statement and printing each preReq individually but is there a better way to do this still using recursion?
An example out of this: If the user types that course, all of the preReqs will print out too.
ACS-3947 Algorithm Design
prereq: ACS-2947 Data Structures and Algorithms
ACS-2947 Data Structures and Algorithms
prereq: ACS-1904 Programming Fundamentals II
ACS-1904 Programming Fundamentals II
prereq: ACS-1903 Programming Fundamentals I
ACS-1903 Programming Fundamentals I
no prereq
Course class:
import java.util.*;
public class Course
{
protected String courseNumber;
protected String courseName;
protected Course prerequisite;
public Course(){
courseNumber = courseName = "Unknown";
prerequisite= null;
}
public Course (String cn, String num){
this.courseNumber=num;
this.courseName=cn;
}
public String getCourseNumber(){
return courseNumber;
}
public String getCourseName(){
return courseName;
}
public Course getPreReq(){
return prerequisite;
}
public void setCourseNumber(String courseNumber){
this.courseNumber=courseNumber;
}
public void setCourseName(String courseName){
this.courseName=courseName;
}
public void setPreReq(Course pr){
prerequisite =pr;
}
}
PreReq class:
import java.util.*;
import java.io.*;
public class Prereqs
{
public static void main (String [] args){
Scanner kb = new Scanner (System.in);
Course nineteen03 = new Course ("Programming Fundamentals I","ACS-1903");
Course nineteen04 = new Course ("Programming Fundamentals II"," ACS-1904");
Course two47 = new Course ("Data Structures and Algorithms","ACS-2947 ");
Course three47 = new Course ("Algorithm Design","ACS-3947");
Course two09 = new Course ("Internet Programming","ACS-2909");
Course three09 = new Course ("Advanced Internet Programming ","ACS-3909");
nineteen04.setPreReq(nineteen03);
two47.setPreReq(nineteen04);
three47.setPreReq(two47);
two09.setPreReq(nineteen03);
three09.setPreReq(nineteen03);
System.out.println("Enter course number with the format: AAA-999");
String input = kb.next();
validate(input);
}
public static void course(Course nineteen04, Course nineteen03,Course two47, Course three47, Course two09, Course three09, String input ){
Course c1 = nineteen04.getPreReq();
Course c2 = two47.getPreReq();
Course c3 = three47.getPreReq();
Course c4 = two09.getPreReq();
Course c5 = three09.getPreReq();
switch (input){
case "ACS-1904":
System.out.println(nineteen04.getCourseName()+" "+nineteen04.getCourseNumber());
System.out.println("preReq: " + c1.getCourseName()+ " "+ c1.getCourseNumber());
}
}
public static String validate (String input)
{
String arg = input;
boolean valid = arg.length()==7;
if (!valid){
throw new IllegalArgumentException("Not the correct format: AAA-999");
}
valid = arg.charAt(3) == '-';
if(!valid) {
throw new IllegalArgumentException("Not the correct format: AAA-999");
}
for(int i=0; i < 3 && valid; i++){
valid = ((i == 3 && Character.isLetter(arg.charAt(i))));
}
for(int i=3; i < 3 && valid; i++){
valid = ((i==6 && Character.isDigit(arg.charAt(i))));
}
return arg;
}
}
A recursive method needs to contain a condition which terminates the recursion. Your list of courses and their prerequisites remind me of a linked list where each course points to its prerequisite. The list terminates when we reach a course that has no prerequisite. The below code is your Course class with the addition of a main method (imported from your Prereqs class) and the recursive method which I named requirements(). I also added method toString() to make the display of the list of courses and their prerequisites more "human readable". You can experiment by changing the course passed to the initial invocation of method requirements().
public class Course {
protected String courseNumber;
protected String courseName;
protected Course prerequisite;
public Course(){
courseNumber = courseName = "Unknown";
prerequisite= null;
}
public Course (String cn, String num){
this.courseNumber=num;
this.courseName=cn;
}
public String getCourseNumber(){
return courseNumber;
}
public String getCourseName(){
return courseName;
}
public Course getPreReq(){
return prerequisite;
}
public void setCourseNumber(String courseNumber){
this.courseNumber=courseNumber;
}
public void setCourseName(String courseName){
this.courseName=courseName;
}
public void setPreReq(Course pr){
prerequisite =pr;
}
public String toString() {
return courseNumber + " " + courseName;
}
private static void requirements(Course c) {
if (c == null) {
return;
}
else {
System.out.println(c);
requirements(c.getPreReq());
}
}
public static void main(String[] args) {
Course nineteen03 = new Course ("Programming Fundamentals I","ACS-1903");
Course nineteen04 = new Course ("Programming Fundamentals II"," ACS-1904");
Course two47 = new Course ("Data Structures and Algorithms","ACS-2947 ");
Course three47 = new Course ("Algorithm Design","ACS-3947");
Course two09 = new Course ("Internet Programming","ACS-2909");
Course three09 = new Course ("Advanced Internet Programming ","ACS-3909");
nineteen04.setPreReq(nineteen03);
two47.setPreReq(nineteen04);
three47.setPreReq(two47);
two09.setPreReq(nineteen03);
three09.setPreReq(nineteen03);
requirements(three09);
}
}
Running the above code displays the following:
ACS-3909 Advanced Internet Programming
ACS-1903 Programming Fundamentals I
In my main, I am asking the user 2 questions. Both questions have 2 correct answers, which is choice number 2 and 4. Whenever I run the Code and select option 2(for both questions), it results in false. If I run the program and select option 4, it results in true. Both options 2 and 4 are correct. I feel as if the issue is due to my UpdateChoices method(located in MultiCheck class), but I don't know why. I used an ArrayList to save the correct choices, but the first correct choice (option 2) is not saved, resulting in it displaying false. Is there a reason why the first option isn't saved in the ArrayList? My output window is posted below the code.
This is the code I have: Main
package pa4_pandeyay;
import java.util.Scanner;
public class MyQuestionDemo {
public static void main(String[] args) {
// TODO code application logic here
MultiCheck first = new MultiCheck();
first.setText("Which number below is prime?");
first.UpdateChoices("4", false);
first.UpdateChoices("3", true);
first.UpdateChoices("12", false);
first.UpdateChoices("7", true);
first.UpdateChoices("8", false);
MultiCheck second = new MultiCheck();
second.setText("Which number below multiplied equals to 12?");
second.UpdateChoices("4 * 4", false);
second.UpdateChoices("12 * 1", true);
second.UpdateChoices("12 * 2", false);
second.UpdateChoices("-6 * -2", true);
second.UpdateChoices("0 * 12", false);
presentQuestion(first);
presentQuestion(second);
}
public static void presentQuestion(MultiCheck x){
x.display();
System.out.print("Your answer: ");
Scanner sc = new Scanner(System.in);
String response = sc.nextLine();
System.out.println(x.checkAnswer(response));
}
}
Java class Question.java
package pa4_pandeyay;
public class Question {
private String text;
private String answer;
// Create a constructor
public Question(){
text = "";
answer = "";
}
// Set the question text
public void setText(String questionText){
text = questionText;
}
//Set the answer text
public void setAnswer(String correctAnswer){
answer = correctAnswer;
}
// Check the respond with the actual correct answer
public boolean checkAnswer(String response){
return response.equals(answer);
}
public String getText(){
return text; // since variable text it private, we need to create a get method in order to access the private variable
}
// Diplay question to the user:
public void display(){
System.out.println(text);
}
}
Java class MultiCheck:
package pa4_pandeyay;
import java.util.ArrayList;
public class MultiCheck extends Question{
private ArrayList<String> answerChoices;
public MultiCheck(){
super();
answerChoices = new ArrayList<String>();
}
public void UpdateChoices (String choice, boolean correct){ // check the asnwers and save the 'true' answers
answerChoices.add(choice);
if (correct == true)
{
//convert choices.size() to string
String choiceString = "" + answerChoices.size();
setAnswer(choiceString);
}
}
// when calling display, this method will be called.
#Override
public void display(){
System.out.println(getText());
// Display the answer choices
for( int i =0; i< answerChoices.size(); i++){
int choiceNumber = i + 1;
System.out.println(choiceNumber + " : " + answerChoices.get(i));
}
}
The Question class can only store one correct answer by setAnswer(). If you have multiple correct answers, then they will override each other so that only the last one is finally in memory.
I'm just starting out in programming and for school we have to create an address book as a project.
We have three types of contacts:
Generic which includes day, month, year of birth, name and multiple tags for search.
Basic which includes variables previously mentioned and a phone number, as well as the type of phone it is (home, cell, office, etc).
Business which includes all previous variables but can store multiple phone numbers which are all given a type (home, cell, office, etc.)
For the project it is also mandatory to have 6 different classes.
The main class, the Agenda class which includes the arraylist of contacts, a class for each type of contact and a class for the phone numbers.
Right now I'm stuck on two things, I have no idea how to allow users to input more than one for number, more specifically how to store them properly. I have no clue how to setup my PhoneNumber Class.
Basically I want to know how I can store multiple phone numbers and associate them with one contact, same thing for the keywords. Also these field are optional so one person could have no phone number, like one could have 3. Same goes for the keywords.
In my Agenda Class
case 3:
type = "Commercial";
System.out.print("Nom: ");
nom = entree.readLine();
System.out.print("Nom d'entreprise: ");
nomEntreprise = entree.readLine();
System.out.print("Jour de naissance: ");
jNaissance = entree.readLine();
System.out.print("Mois de naissance: ");
mNaissance = entree.readLine();
System.out.print("Année de naissance: ");
aNaissance = entree.readLine();
dNaissance = jNaissance + "-" + mNaissance + "-" + aNaissance;
date = sdf.parse(dNaissance);
dNaissanceCalendar.setTime(date);
System.out.print("Telephone: ");
telephone = entree.readLine();
System.out.print("Type de telephone: ");
typeTelephone = entree.readLine();
activite = "";
ContactCommercial nouveauComm;
nouveauComm = new ContactCommercial(type, dNaissanceCalendar, nom, nomEntreprise, telephone, activite);
contactlist.add(nouveauComm);
try{
nouveauComm.write();
}catch (Exception e) {
}
break;
In my GenericContact class
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
public class ContactGenerique {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date date;
ArrayList<ArrayList<String>> motCle = new ArrayList<>();
private String type;
private Calendar dNaissanceCalendar;
private String jNaissance;
private String mNaissance;
private String aNaissance;
private String dNaissance;
//private String dnaissance;
private String nom;
//private String motCle;
//private int age = today.get(today.YEAR) - dnaissance.get(YEAR);
public ContactGenerique(String type, String jNaissance, String mNaissance, String aNaissance, String nom) {
super();
this.type = type;
this.jNaissance = jNaissance;
this.mNaissance = mNaissance;
this.aNaissance = aNaissance;
this.nom = nom;
//this.motCle = motCle;
// DateFormat format = new SimpleDateFormat("dd-MM-yyyy");
//Date date = (Date)format.parse(dnaissance);
//this.age = age;
//this.motCle = motCle;
}
public String getAgeString () {
String dNaissance = jNaissance + "-" + mNaissance + "-" + aNaissance;
return dNaissance;
}
public int getAge()throws ParseException {
dNaissance = getAgeString();
date = sdf.parse(dNaissance);
dNaissanceCalendar = Calendar.getInstance();
dNaissanceCalendar.setTime(date);
Calendar ajd = Calendar.getInstance();
int age = ajd.get(Calendar.YEAR) - dNaissanceCalendar.get(Calendar.YEAR);
if (ajd.get(Calendar.DAY_OF_YEAR) < dNaissanceCalendar.get(Calendar.DAY_OF_YEAR))
age--;
return age;
}
public void getDonnees() {
//super.getDonnees();
System.out.println(this.dNaissanceCalendar);
System.out.println(this.nom);
System.out.println(this.motCle);
//System.out.println(this.getAge);
}
public String getNom() {
return this.nom;
}
public String setNom() {
return (this.nom = nom);
}
void write() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
In my ContactCommercial Class
import java.util.Calendar;
public class ContactCommercial extends ContactGenerique{
private String activite;
private String nomEntreprise;
public ContactCommercial(String type, Calendar dNaissanceCalendar, String nom, String telephone, String activite, String nomEntreprise) {
super(type, dNaissanceCalendar, nom);
this.nomEntreprise = nomEntreprise;
}
public String getActivite(){
return activite;
}
public void setActivite(String activite){
this.activite = activite;
}
public String getNomEntreprise(){
return nomEntreprise;
}
public void setNomEntreprise(String nomEntreprise){
this.nomEntreprise = nomEntreprise;
}
public void getDonnees() {
super.getDonnees();
System.out.println(this.getActivite());
System.out.println(this.getNomEntreprise());
}
}
You can created the contact classes in the following way:
The tags field will have a Set with the tags for that contact. It can be empty when no tags has been set. The following classes BasicContact and BusinessContact extends from that class.
The BasicContact class reference only one PhoneNumber object, which holds the type and number of the phone. This reference can be null to indicate that this "basic" contact does not have a phone.
For the BusinessContact the phone numbers for the business are saved in a Set which can be empty. Since it is a Collection (like the tags) you can save more than one phone number in a "business" contact.
Since BasicContact and BusinessContact extends from GenericContact they both also have the fields for the name, birthday and tags.
Btw.: Don't split the birthday into three strings for day, month and year. Save it as one Date object, maybe with the convention that it is saved in UTC (even though only the "date" part will be relevant, the "time" part should be 00:00:00).
I am working on a project ( I had a problem yesterday and so many people helped me!) so I decided to ask for help again.
My code has 3 classes. ProjectMain,Students,Classroom. I created an array of Classroom objects. Right now I have 3 Classroom objects. But I have to assign student objects to these Classroom objects. For example : classarray[0] is an object from Classroom class and studentobject.get(0) , studentobject.get(1) ... will be students objects inside classarray[0] object. But I have failed on this while coding. Here are my classes :
public class Classroom
{
private String classname;
private String word[] = null;
protected ArrayList<Students> studentobject = new ArrayList<Students>(10);
public String[] getWord()
{
return word;
}
public void setWord(String[] word)
{
this.word = word;
}
public ArrayList<Students> getStudentobject()
{
return studentobject;
}
public void setStudentobject(ArrayList<Students> studentobject)
{
this.studentobject = studentobject;
}
public String getClassname()
{
return classname;
}
public void setClassname(String classname)
{
this.classname = classname;
}
public void classroomreader(String filename)
{
// This method gets the name of Classroom
File text = new File("C:/Users/Lab/Desktop/classlists/" + filename
+ ".txt");
Scanner scan;
try
{
scan = new Scanner(text);
String line = scan.nextLine();
word = line.split("\t");
line = scan.nextLine();
word = line.split("\t");
} catch (FileNotFoundException e1)
{
e1.printStackTrace();
}
}
}
This is my student class :
public class Students extends Classroom
{
private String name,id;
private int age;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
And my main class :
public class ProjectMain
{
public static void main(String[] args)
{
Classroom[] classarray = new Classroom[3];
//I got 3 Classroom objects here
classarray[0]=new Classroom();
classarray[1]=new Classroom();
classarray[2]=new Classroom();
classarray[0].classroomreader("class1");
classarray[0].studentobject.get(0).setName(classarray[0].getWord()[1]);
//The problem is in here. When my code comes to the line above,
// at java.util.ArrayList.rangeCheck(Unknown Source) error comes out.
// I tried to get first object in studentobject Arraylist, and tried to set it's name
// to the variable which my text reader reads.
How can I write what I have in my mind?
Your classroomreader method reads the file but don't do much of it... maybe you want to create some instance of Students within it.
scan = new Scanner(text);
String line = scan.nextLine();
word = line.split("\t"); // won't be used
line = scan.nextLine();
word = line.split("\t"); // erased here
There you only have the last line (split) of the file in word attribute.
When creating Classroom instance studentobject list is created empty and it stays that way so you can't access first (or any) object in it.
To populate your list you may add to Classroom method like this:
public void addStudent(Student s)
{
studentobject.add(s);
}
classroom contains the following field declaration
String word[] = null;
the main class, incl the classroomreader does not set a value to this field. Yet you are going to invoke
classarray[0].getWord()[1]
which then must fail.
tip: don't use expressions like this, which can be found in your main class (at least not in early stages of development, or learning)
classarray[0].studentobject.get(0).setName(classarray[0].getWord()[1]);
resolve into variables and several steps. Compilers are smart enough to produce the same code if the context is not disturbed, ie the long expression is resolved into a single block.
Never forget that the purpose of programming languages is to make programs readable for humans. :) Code with abbreviations or "tricks" simply shows some philodoxical attitude (imho)
How do i use the method Loanable to get setDueOn(calendar.getTime) and setLoanedTo(name) to function?
"Your library loan method should use the Loanable item that is passed in to set the due on and the loaned to. You want to call those set methods on that passed in instance of Loanable. "
I am getting the errors
The method setDueOn is undefined for the type library
The method setLoanedTo is undefined for the type library
Sorry for all the code.
package src.edu.htc.java1.library;
import java.util.ArrayList;
import java.util.Calendar;
public class Library {
/* The collection of Media owned by the library */
private ArrayList<Media> collection = new ArrayList<Media>();
public void addToCollection(Media item) {
collection.add(item);
}
public void loan(Loanable item,String name) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH, item.getDaysToLoan()); // Now this is asking the helper how many days to loan for
setDueOn(calendar.getTime());
setLoanedTo(name);
return(setdueOn(Loanable));
}
}
1
package src.edu.htc.java1.library;
import java.util.ArrayList;
/**
*
*/
/**
* This class is used to test our library and media classes.
*
*/
public class MediaTester {
/**
* This is the main test method
* #param args - values passed in by the JVM when running
* the application
*/
public static void main(String[] args) {
Book myBook = new Book();
myBook.setLibraryId(123456L);
myBook.setLocation("Eden Prairie");
myBook.setTitle("My Book Title");
ArrayList<String> authorList = new ArrayList<String>();
authorList.add("Joe Author");
authorList.add("Jane Author");
myBook.setAuthors(authorList);
myBook.setCopyright("1984");
myBook.setFormat("paperback");
myBook.setNumberOfPages(385);
myBook.setPublishers("Some Publisher");
System.out.println(myBook);
Movies myMovie = new Movies();
myMovie.setTitle("Fargo");
myMovie.setReleaseDate(2123);
myMovie.setDirector("Matt Johnson");
myMovie.setActors("Matt");
myMovie.setMPAA_rating("R");
ArrayList<String> actors = new ArrayList<String>();
actors.add("Tom Hanks");
System.out.println(myMovie);
Games myGames = new Games();
myGames.setTitle("Starcraft");
myGames.setConsoleType("wii");
myGames.setEsbnRatings("E");
myGames.setReleaseDate("2012");
myGames.setPublishers("Blizzard");
System.out.println(myGames);
Newspaper myPaper = new Newspaper();
myPaper.setLibraryId(11122233L);
myPaper.setLocation("St. Paul");
myPaper.setTitle("Pioneer Press");
ArrayList<Media> myMediaList = new ArrayList<Media>();
myMediaList.add(myBook);
myMediaList.add(myMovie);
myMediaList.add(myGames);
myMediaList.add(myPaper);
Library myLibrary = new Library();
for (Media item : myMediaList) {
myLibrary.addToCollection(item);
if (item instanceof Loanable) {
myLibrary.loan((Loanable) item, "Mary");
System.out.println(String.format("Item loaned out: %s",item));
} else {
System.out.println(
String.format("Sorry you can't loan out this item: %s", item));
}
}
}
}
2
package src.edu.htc.java1.library;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
*
*/
/**
* This class represents an item in our library's collection.
*
*/
public abstract class Media {
public static final int STANDARD_LOAN_DAYS = 14;
private long libraryId;
private String title;
private String location;
private String loanedTo;
private Date dueOn;
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("{");
builder.append(this.getClass().getSimpleName());
builder.append(": ");
builder.append("[id=").append(libraryId);
builder.append("], [title=").append(title);
builder.append("], [loanedTo=").append(loanedTo);
if (getDueOn() != null) {
builder.append("], [dueOn=");
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
builder.append(formatter.format(getDueOn()));
}
builder.append("]");
builder.append(toStringHelper());
builder.append("}");
return builder.toString();
}
public long getLibraryId() {
return libraryId;
}
public void setLibraryId(long libraryId) {
this.libraryId = libraryId;
}
protected String toStringHelper() {
return " ";
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getLoanedTo() {
return loanedTo;
}
public Date getDueOn() {
return dueOn;
}
public void setDueOn(Date dueOn) {
this.dueOn = dueOn;
}
public void setLoanedTo(String loanedTo) {
this.loanedTo = loanedTo;
}
}
3
Your Media class might need to implement the Loanable interface like pointed out in the comments if the inheriting classes don't, and then this method:
public void loan(Loanable item,String name) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH, item.getDaysToLoan()); // Now this is asking the helper how many days to loan for
setDueOn(calendar.getTime());
setLoanedTo(name);
return(setdueOn(Loanable));
}
has a few errors that need to be fixed:
If you declare a method void it means it can't (and shouldn't) return anything, so don't use any return statement in it.
The method calls setDueOn and setLoanedTo needs to be called on a specific object, in this case item. At the moment you're trying to call methods by that name local to the Library class, where they don't exist.
If you look at the method setDueOn(Date dueOn) you'll note that it expects a date, not a class or interface name...
After corrections the method might look like this:
public void loan(Loanable item,String name) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH, item.getDaysToLoan());
item.setDueOn(calendar.getTime());
item.setLoanedTo(name);
}
There might be other issues, but the code is really a bit too long to browse through...