I m currently trying to code a Calender with java.
I created 3 classes:
1. Date( includes year, month....)
2. Event(includes people, place, the class Date ... + an option to create dates )
3. Mainclass My mainclass that contains the menu.
My problem is that I don't know how the user is able to create his own date, because I have to create the object Termin myself... So, can somebody help me fix this? Thx in advance!
public class Event {
private String mDescription, mPlace, mNames;
private Date mStart, mEnd;
Termin(String description, String place, String names, Date start, Date end) {
mBetreff = description;
mOrt = place;
mNamen = names;
mBeginn = start;
mEnde = end;
}
public void create() {
Scanner read = new Scanner(System.in);
System.out.println("Enter 1. description 2. place 3. names 4. start 5. end ein");
mDescription = read.nextLine();
mPlace = read.nextLine();
mNames = read.nextLine();
}
public String toString() {
return "Description : " + mDescription + "\nPlace: " + mPlace + "\nNames: " + mNames + "\nIts starts at " + mStart
+ " and ends at " + mEnd;
}
}
public class Date {
private int year, day, month, hours, minutes;
Datum(int year, int month, int day, int hours, int minutes) {
this.day= day;
this.year= year;
this.month= month;
this.hours= hours;
this.minutes= minutes;
}
public String toString() {
return "\n" + day + "." + month + "." + year + " um " + hours+ ":" + minutes;
}
public void enterDate() {
}
}
EDIT:
I asked this question 2 years ago, back when I just started coding and had no idea of oop and encapsulation ...
To answer my own question, for every newbie that also tries to create a terminal calender:
Date needs the following methos:
public setDate() {
this.year = read.nextLine();
...
}
for every member.
Event takes the resulting object Date, either in the constructor or in a setter like method.
Creating an instance-method to create an appointment is kind of... strange since one needs to create an appointment (called Termin in your case) to create an appointment. One possibility would be the builder pattern. By having a public static inner builder class, you can set the constructor(s) private and enforce the use of that builder:
public class Main {
private int value;
private Main(int value) {
this.value = value;
}
public int getValue() {
return (this.value);
}
public static class MainBuilder {
boolean valueWasSet;
int value;
public MainBuilder() {
this.valueWasSet = false;
this.value = -1;
}
public void setValue(int value) {
this.value = value;
this.valueWasSet = true;
}
public Main build() {
if (!this.valueWasSet) {
throw new IllegalStateException("value must be set before a Main can be build.");
}
return (new Main(this.value));
}
}
}
(this is a simplified sketch to show the core mechanism on how to assert that certain values are set before constructing a Main through MainBuilder.
The process of constructing a Main would be:
MainBuilder builder = new MainBuilder();
builder.setValue(100);
// all following Main's will have a value of 100
Main mainOne = builder.build();
Main mainTwo = builder.build();
builder.setValue(200);
// all following Main's will have a value of 200
Main mainThree = builder.build();
Main mainFour = builder.build();
Related
This question already has answers here:
Having inheritance and polymorphism issues with Java
(2 answers)
Closed 6 years ago.
I am trying to output calclatefee of $2 per day after 3 days. I have switched things around and I am left at this which looks a little sloppy. This Array is also making me take the confusing way.
public class Movie {
String rating;
String title;
int id;
int rentTime;
public String setrating() {
return rating;
}
public void rating(String getrating) {
rating = getrating;
}
public int setid() {
return id;
}
public void id(int agetid) {
id = agetid;
}
public String settitle() {
return title;
}
public void title(String gettitle) {
title = gettitle;
}
public int setfees() {
return rentTime;
}
public void fees(int getrentTime) {
rentTime = getrentTime;
}
public Movie() {
title = " ";
rating = " ";
id = 0;
rentTime = 0;
System.out.println("default constructor");
}
public Movie(String title, String rating, int id, int rentTime) {
title = " not overridden ";
rating = " NR ";
id = 0;
rentTime = 0;
System.out.println("Overloaded -" + title + rating + id + rentTime);
}
public static void main(String[] args) {
Movie[] Array = {
new Action(" The 100", " pg-13", 105, 7, 3),
new Comedy(" Supernatural", " pg-13", 5, 2, 0),
new Drama(" Lost 2", " R", 9, 2, 0) };
for (int x = 0; x < Array.length; x++) {
// System.out.println(x);
System.out.println(Array[x].toString());
}
}
}
public abstract class Action extends Movie {
protected double latecost;
protected double latefees = 3;
public Action(String gettitle, String getrating, int getid, int getrentTime, double latecost) {
super(gettitle, getrating, getid, getrentTime);
title = gettitle;
rating = getrating;
id = getid;
rentTime = getrentTime;
latecost = latefees;
System.out.println("Overridden " + title + rating + " " + id + " " + " " + rentTime + " "
+ latecost);
}
public double calclatefees(double latecost, double rentTime) {
if (rentTime > 3)
latefees = ((rentTime - 3) * latecost);
return latefees;
}
#Override
public String toString() {
String x = "\nMovie: " + title + " is rated " + rating + "\nMovie ID number: " + id
+ " and the late fee for action movies is $" + latecost + "\n";
return x;
}
protected void finalize() throws Throwable {
try {
System.out.println("Finalize method");
} finally {
super.finalize();
}
}
public void dispose() {
System.out.println(" dispose method");
}
}
Problems:
There's no calclatefee method to override in the parent class. If you want a child class to override method, it must be present in the parent class, at least as an abstract method (if the parent is abstract or is an interface).
You never call your calclatefee method anywhere, so you shouldn't expect to ever see its result in your output.
Your child class, Action, is abstract -- isn't that backwards? Most often its the parent class that's abstract, so why are you structuring it this way? And as written your main method shouldn't compile since you seem to be trying to create an instance of an abstract class.
Your class overrides the finalize() method, something that is generally not recommended. Fortunately your override doesn't really do anything other than output to the standard out and then call the super's method, but still, why risk it?
Side issues
Your code does not follow Java naming conventions. Variable names should all begin with a lower letter while class names with an upper case letter. Learning this and following this will allow us to better understand your code, and would allow you to better understand the code of others.
You will want to try to improve the formatting of your code that you post in here and your code in general. Good formatting including using an indentation style that is uniform and consistent will help others (us!) to better understand your code, and more importantly, it will help you to better understand your code and thus fix your own bugs. Also it shows that you're willing to put in extra effort to make it easier for the volunteers here to help you, and that effort is much appreciated. I took the liberty of trying to fix this for you.
I have a class, right now I am changing the setter to throw an exception if an invalid value pass in.
It requires:
A. (The dueDay must be between 1 and 31, and the dueMonth must be between 1 and 12.) The exception show not be handled in the setter methods.
B. Change the main method of TodoItem so that it asks the user for the task, due day, and due month, and stores this information as a new TodoItem.
C. Change the constructor so that is called your new setter methods. If an exception is thrown, it should be handled in the main method. The user should be told they entered an invalid day or month, and asked for the correct one.
My class is:
( I already changed setter to throw an exception, however, it doesn't work, I think I should change the main function's constructor, however I don't know how to do it.)
public class TodoItem {
private String task;
private int dueMonth;
private int dueDay;
private boolean isDone;
// class variables
private static int numItems;
private static int numDone;
// constructor
public TodoItem(String taks,int day,int month) {
this.task = task;
dueDay = day;
dueMonth = month;
isDone = false;
numItems++;
}
// second constructor
public TodoItem(String task) {
this.task = task;
isDone = false;
numItems++;
}
public static void WriteToFile(String a){
a="toString.txt";
String task;
int dueMonth;
int dueDay;
boolean isDone;
}
// toString method
public String toString() {
return a+task + ", due: " + dueMonth + "/" + dueDay + (isDone?", done":", todo");
}
// getters
public int getDueDay() {
return dueDay;
}
public int getDueMonth() {
return dueMonth;
}
// setters
public void setDueDay(int day) throws Exception {
if (day >= 1 && day <=31) {
dueDay = day;
}
else {
throw new Exception ("Error: invalid due day");
}
}
public void setDueMonth(int month) throws Exception{
if (month >= 1 && month <= 12) {
dueMonth = month;
}
else {
throw new Exception("Error: invalid due month");
}
}
// Checks off an item as being done.
// If the item was already marked as done, don't increase the counter
// (this was not specified in the problem set instructions).
public void markAsDone() {
if (!isDone) {
isDone = true;
numDone++;
}
}
// returns the percentage of to-do list items completed
public static double percentDone() {
return (double) numDone/numItems*100;
}
/**
* #param args
* #throws Exception
*/
public static void main(String[] args) throws Exception {
// constructor 1
TodoItemDone item1 = new TodoItemDone("Walk dog",12,3);
TodoItemDone item2 = new TodoItemDone("Do 326 project",16,3);
TodoItemDone item3 = new TodoItemDone("Put away winter boots",21,3);
// constructor 2
TodoItemDone item4 = new TodoItemDone("Buy groceries");
TodoItemDone item5 = new TodoItemDone("Clean bathroom");
TodoItemDone item6 = new TodoItemDone("Study for myself");
// toString (and verify constructors)
System.out.println("The 6 items are:");
System.out.println(item1);
System.out.println(item2);
System.out.println(item3);
System.out.println(item4);
System.out.println(item5);
System.out.println(item6);
System.out.println();
System.out.println("Setting due dates and months on the last 3:");
// setDueDay
item4.setDueDay(1);
item5.setDueDay(5);
item6.setDueDay(52);
// setDueMonth
item4.setDueMonth(12);
item5.setDueMonth(6);
item6.setDueMonth(0);
System.out.println("The last 3 items are now:");
System.out.println(item4);
System.out.println(item5);
System.out.println(item6);
// Test percentDone() and markAsDone()
System.out.println();
System.out.println("About to complete some items:");
System.out.println("percent done: " + percentDone());
item1.markAsDone();
System.out.println("Item 1 is now: " + item1);
System.out.println("percent done: " + percentDone());
item1.markAsDone();
System.out.println("Item 1 is now: " + item1);
System.out.println("percent done: " + percentDone());
item2.markAsDone();
System.out.println("Item 2 is now: " + item2);
System.out.println("percent done: " + percentDone());
}
however, it doesn't work,
You define TodoItem class, but in main() you create TodoItemDone. When I change TodoItem to TodoItemDone, I have results:
The 6 items are:
null, due: 3/12, todo
null, due: 3/16, todo
null, due: 3/21, todo
Buy groceries, due: 0/0, todo
Clean bathroom, due: 0/0, todo
Study for myself, due: 0/0, todo
Setting due dates and months on the last 3:
Exception in thread "main" java.lang.Exception: Error: invalid due day
at com.github.vedenin.TodoItemDone.setDueDay(TodoItemDone.java:61)
at com.github.vedenin.TodoItemDone.main(TodoItemDone.java:120)
Exception throw correctly
change this part :
public TodoItem(String taks,int day,int month) {
this.task = task;
dueDay = day;
dueMonth = month;
isDone = false;
numItems++;
}
to this :
public TodoItem(String task,int day,int month) {
this.task = task;
dueDay = day;
dueMonth = month;
isDone = false;
numItems++;
}
you're not setting the this.task to correct input argument taks.
i changing your argument name.
maybe it wasn't the main problem but try to change it.
I am trying to figure out how to write a constructor that calls methods. I have been given the following instructions for a Java project. The emboldened ones are relevant to this step. Step 3 I have completed, but I can't confirm if I completed it correctly. The code for Step 3 is the second Date constructor within the Date class.
Uncomment line 1 from DateTest (don’t forget to delete the “Line 1.” part) and build and run the project. What is the output? Why is this the output?
Create a default constructor for Date which sets the date to 1/1/2000. Build and run the project. What is the output?
Create a constructor that has three int parameters for the month, day, and year and sets the values of these instance variables to the values passed in. Uncomment lines 2 and 3. Build and run the project. What is the output?
Rewrite the constructor from question 3 so that it calls setMonth(), setDay(), and setYear(). Build and run the project. What is the output?
Write a set() method that has three parameters for the month, day, and year. Uncomment lines 4 and 5. Build and run the project. What is the output?
Rewrite the constructor from question 3 so that it calls set (). Build and run the project. What is the output?
Below is the code for Date class and DateTest class.
package datetest;
import java.util.Scanner;
public class Date
{
public Date() {
month = 1;
day = 1;
year = 2000;
}
public Date(int m, int d, int y) {
month = m;
day = d;
year = y;
}
private int month;
private int day;
private int year; //a four digit number.
public void setYear(int newYear)
{
year = newYear;
}
public void setMonth(int newMonth)
{
if ((newMonth <= 0) || (newMonth > 12))
{
month=newMonth;
}
else
month = newMonth;
}
public void setDay(int newDay)
{
if ((newDay <= 0) || (newDay > 31))
{
day=1;
}
else
day = newDay;
}
public int getMonth( )
{
return month;
}
public int getDay( )
{
return day;
}
public int getYear( )
{
return year;
}
public void printDate( )
{
System.out.print(getMonth() + "/" + getDay() + "/" + getYear());
}
public void readInput( )
{
boolean tryAgain = true;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter month, day, and year.");
System.out.println("Do not use a comma.");
month = keyboard.nextInt( );
day = keyboard.nextInt( );
year = keyboard.nextInt( );
}
}
This is the DateTest class.
package datetest;
public class DateTest {
public static void main(String[] args) {
Date today = new Date();
System.out.println("Today’s date is " + today.getMonth() + "/" + today.getDay() + "/" + today.getYear());
//Line 2. today = new Date(55, 55, 2011);
//Line 3. System.out.println("Today’s date is " + today.getMonth() + "/" + today.getDay() + "/" + today.getYear());
//Line 4. today.set(10, 5, 2011);
//Line 5. System.out.println("Today’s date is " + today.getMonth() + "/" + today.getDay() + "/" + today.getYear());
}
}
I have attempted to write the code to call the methods in step 4. Would the following code be the correct way to write a constructor to call methods?
public Date (int m, int d, int y) {
this.setMonth(month);
this.setDay(day);
this.setYear(year);
}
Would the following code be the correct way to write a constructor to call methods?
public Date (int m, int d, int y) {
this.setMonth(month);
this.setDay(day);
this.setYear(year);
}
Yes, if you used your m, d, and y arguments instead of month, day, and year:
public Date (int m, int d, int y) {
this.setMonth(m);
this.setDay(d);
this.setYear(y);
}
With your code, you're actually just setting the instance members (month and so on) to their existing values (because month in the constructor is automatically resolved to the instance data member month using an implied this.). So I'm guessing when you tried it, you ended up with zeroes and didn't understand why. (int members are auto-initialized to zero before the code in the constructor runs.)
Hey there Stackoverflowers,
I just started programming in Java and encountered a strange problem concerning printing an object. When a new object of type gast is created the user has to enter his or her birthday. This al works fine, however, if I try to print it out I returns 0-0-0. Why is that? By the way, if I create a new datum directly with the parameter constructor it works fine. Wherein lays the problem? I just can't figure it out. I hope you guys can help me out.
Thanks in advance!
public class Datum {
private static String patroon = "\\d{2}-\\d{2}-\\d{4}";
public int dag;
public int maand;
public int jaar;
Datum(int dag, int maand, int jaar) {
System.out.print("constructor: " + dag);
this.dag = dag;
System.out.println(", dag: " + this.dag);
this.maand = maand;
this.jaar = jaar;
}
Datum() {
newDatum();
}
/* */
public static Datum newDatum() {
String input = Opgave5.userInput("Geboortedatum gast");
boolean b = input.matches(patroon);
if (b) {
String[] str = input.split("-");
int dag = Integer.parseInt(str[0]);
int maand = Integer.parseInt(str[1]);
int jaar = Integer.parseInt(str[2]);
Datum datum = new Datum(dag, maand, jaar);
System.out.println(datum);
return datum;
}
else {
return new Datum();
}
}
public String toString() {
return this.dag + "-" + this.maand + "-" + this.jaar;
}
}
Second class:
Gast() {
this.firstName = Opgave5.userInput("Voornaam gast");
this.lastName = Opgave5.userInput("Achternaam gast");
this.geboortedatum = new Datum();
System.out.println("gast: " + this.geboortedatum); // <--- this prints out 0-0-0
}
public String toString() {
return this.firstName + " " + this.lastName + " " + this.geboortedatum;
}
I think you don't understand constructors in Java. You are merely ignoring the result of newDatum() in the constructor. Also, if it did have the expected effect, it might recurse infinitely in the constructor invocation inside newDatum(). Use something like this; allowing newDatum() to edit the instance will work:
Datum() {
newDatum(this);
}
public static void newDatum(Datum instance) {
String input = Opgave5.userInput("Geboortedatum gast");
boolean b = input.matches(patroon);
if (b) {
String[] str = input.split("-");
int dag = Integer.parseInt(str[0]);
int maand = Integer.parseInt(str[1]);
int jaar = Integer.parseInt(str[2]);
instance.dag = dag;
instance.maand = maand;
instance.jaar = jaar;
System.out.println(instance);
}
else {
new Datum();
}
// ^^ Above code may be buggy, see my answer above code
}
This line:
this.geboortedatum = new Datum();
Is using the default constructor. This will set no values. Try to pass the parameters in via constructor like this:
this.geboortedatum = new Datum(1, 2, 3);
If you want to take advantage of the static method you wrote (which is where you ask for user input), then do the following:
this.geboortedatum = Datum.newDatum();
public class CalendarUtil
{
private Calendar cal = null;
public String getRemId()
{
cal = Calendar.getInstance();
return "" + cal.get(Calendar.DATE) + (cal.get(Calendar.MONTH)+1) + cal.get(Calendar.YEAR);
}
}
How can we auto generate ID on a button click that will contain the concatenation of date,month,year and a 3 digit counter starting form 000 and display it in a textfield? for eg:- 28122012001, 28122012002, etc and so on. Code that i have been trying is as above
I think two static fieds can do it.
private static String lastUsedDatePrefix;
private static int counter;
If you want to nenerate a new ID, check if the dateprefix is the same as stored in lastUsedDatePrefix if yes, increment counter else set counter=0 and set lastUsedDatePrefixto actual date.
Untested implementation:
public class CalendarUtil{
private static String lastUsedDatePrefix = "";
private static int counter = 0;
public String getRemId(){
final String datePrefix = new SimpleDateFormat("ddMMyyy").format(new Date());
if (lastUsedDatePrefix.equals(datePrefix)) {
CalendarUtil.counter++;
}
else{
CalendarUtil.lastUsedDatePrefix = datePrefix;
CalendarUtil.counter = 0;
}
final String counterSuffix = ((100 <= CalendarUtil.counter) ? ""
: (10 <= CalendarUtil.counter) ? "0" : "00")
+ CalendarUtil.counter;
return datePrefix + counterSuffix;
}
}