Android Datepicker date add and display in single digit - java

i am developing an android application in which a datepicker is there to select the date of birth ... I need to display this date in a text view and this date has to be added into a single digit... and display in a textview.. i did code where the date is displyed in a textview but i need to display the total sum of it..
for example if date of birth is 04 02 1984 then 0+4 0+2 1+9+8+4 so answer is 4, 2, 4 and this has to be displayed separate in a textview.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final DatePicker date = (DatePicker) findViewById(R.id.datePicker1);
final TextView tvDate = (TextView) findViewById(R.id.textView2);
date.init(date.getYear(), date.getMonth(), date.getDayOfMonth(),new OnDateChangedListener()
{
#Override
public void onDateChanged(DatePicker arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
int sum = 0;
String date=Integer.toString(arg3);
String month=Integer.toString(arg2);
String year=Integer.toString(arg1);
tvDate.setText(month+date+year);
}
} );
}
}

CALL "sum" function for each of Day,Month and Year variables
int daySum=sum(Integer.parseInt(day));
int monthSum=sum(Integer.parseInt(month));
int yearSum=sum(Integer.parseInt(year));
tvDay.setText(daySum);
tvMonth.setText(monthSum);
tvYear.setText(yearSum);
int sum(int number){
int remainder = number % 9;
if (number == 0) {
return number;
} else {
if (remainder == 0) {
return number;
}else{
return remainder;
}
}
}

First you check the validation:
String day = "";
if (dayOfMonth < 10) {
day = "0" + dayOfMonth;
}else {
day = String.valueOf(dayOfMonth);
}
String month = "";
int get_month = monthOfYear + 1;
if (get_month < 10) {
month = "0" + get_month;
}else {
month = String.valueOf(get_month);
}
String date = day + "-" + month + "-" + year;

If i understand you correctly then what you are looking for is casting the String to ints in your onDateChanged method , so may b something like this :
int i = 0 ;
while(i<2 ) // 2 for day and month 4 for year ... or what ever fits u can also run until the length of the string
dateDigit += Integer.parseInt.subString(i++,i++);
//this is just an idea , havent tested the code or anything
keep on doing that until u have a one digit number ( Link to post for this)
or mayb some recursive method that will keep on doing that until u have only one digit
hope this fits

Related

Is their any simplified Java to find palindome dates between year 0000 and 9999?

import java.util.Arrays;
public class PalindromeDates {
static final int STARTINGYEAR = 0000;
static final int ENDINGYEAR = 9999;
public static void main(String[] args) {
int year, month, date;
int dateArray[];
boolean flag;
System.out.println(" Date --> Array Format\n");
for (year = STARTINGYEAR; year <= ENDINGYEAR; year++) {
for (month = 01; month <= 12; month++) {
for (date = 1; date <= 31; date++) {
if (checkValidDate(year, date, month)) {
dateArray = createDateArray(date, month, year);
flag = checkPalindrome(dateArray);
if (flag) {
System.out.print(year + "." + month + "." + date + " --> ");
System.out.println(Arrays.toString(dateArray));
}
}
}
}
}
}
public static int[] createDateArray(int date, int month, int year) { //Inserting the whole date to an array
int dateArray[] = new int[8];
dateArray[0] = year / 1000;
year = year % 1000;
dateArray[1] = year / 100;
year = year % 100;
dateArray[2] = year / 10;
dateArray[3] = year % 10;
dateArray[4] = month / 10;
dateArray[5] = month % 10;
dateArray[6] = date / 10;
dateArray[7] = date % 10;
return dateArray;
}
public static boolean checkPalindrome(int dateArray[]) {
for (int i = 0; i <= 3; i++) {
if (dateArray[i] == dateArray[7 - i]) {
} else {
return false;
}
}
return true;
}
public static boolean checkValidDate(int year, int month, int date) {
if (month == 2 && date == 30)
return false;
if ((month == 2 || month == 4 || month == 6 || month == 9 || month == 11) && (date == 31)) {
return false;
}
if ((month == 2) && (date == 29))
return (checkLeapYear(year));
return true;
}
public static boolean checkLeapYear(int year) {
if (year % 4 == 0) {
if (year % 100 == 0) {
if (year % 400 == 0)
return true;
else
return false;
} else
return true;
} else {
return false;
}
}
}
This program is written by me to find the palindrome dates since 0000 to 9999. Is their any simplifies program to do this?. What are the modifications for this code? And I want to know whether my leap year finding code is correct.
There is a method called createDateArray(). It is used to put the integer digits in year, month, date to an array. Is there any simple method to do that?
I am inferring from your code that a palindrome date is a date that formatted into yyyyMMdd format is a palindrome string. For example the day before yesterday, February 2, 2020, was a palindrome date because it’s formatted into 20200202, a palindrome.
Is their any simplifies program to do this? …
Yes there is. See below.
… And I want to know whether my leap year finding code is correct.
Yes, it is correct. I have tested its result against the result of Year.of(y).isLeap() for y ranging from 0 through 9999.
And the issue you didn’t ask about: as jrook hinted in a comment, beware of octal numbers.
static final int STARTINGYEAR = 0000;
While this works in this case, it works for reasons that I am afraid that you don’t fully understand. You will get surprises if some day you try 0500 for year 500 and get 320, or you use 0008 for year 8 and get a compile time error. When a Java integer literal begins with 0 (and has more digits following it), it is an octal number, not a number in the decimal number system. So in your code you should use 0 for the year that you want printed as 0000:
static final int STARTINGYEAR = 0;
java.time
On one side Andreas is correct in the other answer that this goes a lot more smoothly when using the date classes that are built into Java. On the other side the Calendar class used in that answer is poorly designed and long outdated. So I recommend we don’t use it and instead present a solution using java.time, the modern Java date and time API.
List<LocalDate> palindromeDates = Arrays.stream(Month.values())
.flatMap(m -> IntStream.rangeClosed(1, m.length(true)).mapToObj(d -> MonthDay.of(m, d)))
.map(md -> md.atYear(reverseStringToInt(md.format(monthDayFormatter))))
.sorted()
.collect(Collectors.toList());
palindromeDates.forEach(ld -> System.out.println(ld.format(dateFormatter)));
This code uses a few auxiliaries:
private static DateTimeFormatter monthDayFormatter = DateTimeFormatter.ofPattern("MMdd");
private static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("uuuuMMdd");
private static int reverseStringToInt(String s) {
StringBuilder buf = new StringBuilder(s);
buf.reverse();
return Integer.parseInt(buf.toString());
}
Excerpt from the output:
01011010
01100110
01111110
01200210
…
20111102
20200202
20211202
…
92800829
92900929
The algorithm idea is stolen from Andreas’ answer since it is so well thought.
Link
Oracle tutorial: Date Time explaining how to use java.time.
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("uuuuMMdd");
for (LocalDate d = LocalDate.of(0, 1, 1); d.isBefore(LocalDate.of(10000, 1, 1)); d = d.plusDays(1)) {
String dateString = dateFormatter.format(d);
if (dateString.equals(new StringBuilder(dateString).reverse().toString())) {
System.out.println(d);
}
}
Since the year can be any 4-digit year, there is no constraint there, so just go through all 3661 MMdd values of a year, reverse it and use as the year.
1) Since the leap date of 0229 reversed is 9220, it is a leap year, and hence a valid palindrome date.
As code, using Calendar, in year order:
List<String> palimdromeDates = new ArrayList<>();
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"/*No DST*/));
cal.clear();
cal.set(2000/*Leap Year*/, Calendar.JANUARY, 1);
for (; cal.get(Calendar.YEAR) == 2000; cal.add(Calendar.DAY_OF_YEAR, 1)) {
int day = cal.get(Calendar.DAY_OF_MONTH);
int month = cal.get(Calendar.MONTH) + 1;
int year = 0; // Calculate: year = reverse(MMdd)
for (int i = 0, n = month * 100 + day; i < 4; i++, n /= 10)
year = year * 10 + n % 10;
palimdromeDates.add(String.format("%04d-%02d-%02d", year, month, day));
}
Collections.sort(palimdromeDates); // Sort by year
for (String date : palimdromeDates)
System.out.println(date);
Note that this code only loops 366 times, and does not create any unnecessary String objects or other type of objects, so it is very fast, and generates minimum garbage.
Output
0101-10-10
0110-01-10
0111-11-10
0120-02-10
0121-12-10
0130-03-10
0140-04-10
0150-05-10
0160-06-10
0170-07-10
0180-08-10
0190-09-10
0201-10-20
0210-01-20
0211-11-20
0220-02-20
0221-12-20
0230-03-20
0240-04-20
0250-05-20
0260-06-20
0270-07-20
0280-08-20
0290-09-20
0301-10-30
0310-01-30
0311-11-30
0321-12-30
0330-03-30
0340-04-30
0350-05-30
0360-06-30
0370-07-30
0380-08-30
0390-09-30
1001-10-01
1010-01-01
1011-11-01
1020-02-01
1021-12-01
1030-03-01
1040-04-01
1050-05-01
1060-06-01
1070-07-01
1080-08-01
1090-09-01
1101-10-11
1110-01-11
1111-11-11
1120-02-11
1121-12-11
1130-03-11
1140-04-11
1150-05-11
1160-06-11
1170-07-11
1180-08-11
1190-09-11
1201-10-21
1210-01-21
1211-11-21
1220-02-21
1221-12-21
1230-03-21
1240-04-21
1250-05-21
1260-06-21
1270-07-21
1280-08-21
1290-09-21
1301-10-31
1310-01-31
1321-12-31
1330-03-31
1350-05-31
1370-07-31
1380-08-31
2001-10-02
2010-01-02
2011-11-02
2020-02-02
2021-12-02
2030-03-02
2040-04-02
2050-05-02
2060-06-02
2070-07-02
2080-08-02
2090-09-02
2101-10-12
2110-01-12
2111-11-12
2120-02-12
2121-12-12
2130-03-12
2140-04-12
2150-05-12
2160-06-12
2170-07-12
2180-08-12
2190-09-12
2201-10-22
2210-01-22
2211-11-22
2220-02-22
2221-12-22
2230-03-22
2240-04-22
2250-05-22
2260-06-22
2270-07-22
2280-08-22
2290-09-22
3001-10-03
3010-01-03
3011-11-03
3020-02-03
3021-12-03
3030-03-03
3040-04-03
3050-05-03
3060-06-03
3070-07-03
3080-08-03
3090-09-03
3101-10-13
3110-01-13
3111-11-13
3120-02-13
3121-12-13
3130-03-13
3140-04-13
3150-05-13
3160-06-13
3170-07-13
3180-08-13
3190-09-13
3201-10-23
3210-01-23
3211-11-23
3220-02-23
3221-12-23
3230-03-23
3240-04-23
3250-05-23
3260-06-23
3270-07-23
3280-08-23
3290-09-23
4001-10-04
4010-01-04
4011-11-04
4020-02-04
4021-12-04
4030-03-04
4040-04-04
4050-05-04
4060-06-04
4070-07-04
4080-08-04
4090-09-04
4101-10-14
4110-01-14
4111-11-14
4120-02-14
4121-12-14
4130-03-14
4140-04-14
4150-05-14
4160-06-14
4170-07-14
4180-08-14
4190-09-14
4201-10-24
4210-01-24
4211-11-24
4220-02-24
4221-12-24
4230-03-24
4240-04-24
4250-05-24
4260-06-24
4270-07-24
4280-08-24
4290-09-24
5001-10-05
5010-01-05
5011-11-05
5020-02-05
5021-12-05
5030-03-05
5040-04-05
5050-05-05
5060-06-05
5070-07-05
5080-08-05
5090-09-05
5101-10-15
5110-01-15
5111-11-15
5120-02-15
5121-12-15
5130-03-15
5140-04-15
5150-05-15
5160-06-15
5170-07-15
5180-08-15
5190-09-15
5201-10-25
5210-01-25
5211-11-25
5220-02-25
5221-12-25
5230-03-25
5240-04-25
5250-05-25
5260-06-25
5270-07-25
5280-08-25
5290-09-25
6001-10-06
6010-01-06
6011-11-06
6020-02-06
6021-12-06
6030-03-06
6040-04-06
6050-05-06
6060-06-06
6070-07-06
6080-08-06
6090-09-06
6101-10-16
6110-01-16
6111-11-16
6120-02-16
6121-12-16
6130-03-16
6140-04-16
6150-05-16
6160-06-16
6170-07-16
6180-08-16
6190-09-16
6201-10-26
6210-01-26
6211-11-26
6220-02-26
6221-12-26
6230-03-26
6240-04-26
6250-05-26
6260-06-26
6270-07-26
6280-08-26
6290-09-26
7001-10-07
7010-01-07
7011-11-07
7020-02-07
7021-12-07
7030-03-07
7040-04-07
7050-05-07
7060-06-07
7070-07-07
7080-08-07
7090-09-07
7101-10-17
7110-01-17
7111-11-17
7120-02-17
7121-12-17
7130-03-17
7140-04-17
7150-05-17
7160-06-17
7170-07-17
7180-08-17
7190-09-17
7201-10-27
7210-01-27
7211-11-27
7220-02-27
7221-12-27
7230-03-27
7240-04-27
7250-05-27
7260-06-27
7270-07-27
7280-08-27
7290-09-27
8001-10-08
8010-01-08
8011-11-08
8020-02-08
8021-12-08
8030-03-08
8040-04-08
8050-05-08
8060-06-08
8070-07-08
8080-08-08
8090-09-08
8101-10-18
8110-01-18
8111-11-18
8120-02-18
8121-12-18
8130-03-18
8140-04-18
8150-05-18
8160-06-18
8170-07-18
8180-08-18
8190-09-18
8201-10-28
8210-01-28
8211-11-28
8220-02-28
8221-12-28
8230-03-28
8240-04-28
8250-05-28
8260-06-28
8270-07-28
8280-08-28
8290-09-28
9001-10-09
9010-01-09
9011-11-09
9020-02-09
9021-12-09
9030-03-09
9040-04-09
9050-05-09
9060-06-09
9070-07-09
9080-08-09
9090-09-09
9101-10-19
9110-01-19
9111-11-19
9120-02-19
9121-12-19
9130-03-19
9140-04-19
9150-05-19
9160-06-19
9170-07-19
9180-08-19
9190-09-19
9201-10-29
9210-01-29
9211-11-29
9220-02-29
9221-12-29
9230-03-29
9240-04-29
9250-05-29
9260-06-29
9270-07-29
9280-08-29
9290-09-29

Can't ParseDouble on some devices

i'm using a NumberTextWatcher for realtime-edit for an EditText and it's working fine for me,
but some users reporting that they got NumberException problem, i think this is because numbers changes in 123,456 in EditText and cant parse to doubles, so i did some change and use Replace("," , "") code but this is not working for some too!
what should i do so this code works for all of my users?
Thanks and Sorry for my Poor English :D
NumberTextWatcher:
public NumberTextWatcher(EditText et)
{
df = new DecimalFormat("#,###");
df.setDecimalSeparatorAlwaysShown(true);
dfnd = new DecimalFormat("#,###");
this.et = et;
hasFractionalPart = false;
}
#SuppressWarnings("unused")
private static final String TAG = "NumberTextWatcher";
#Override
public void afterTextChanged(Editable s)
{
et.removeTextChangedListener(this);
try {
int inilen, endlen;
inilen = et.getText().length();
String v = s.toString().replace(String.valueOf(df.getDecimalFormatSymbols().getGroupingSeparator()), "");
Number n = df.parse(v);
int cp = et.getSelectionStart();
if (hasFractionalPart) {
et.setText(df.format(n));
} else {
et.setText(dfnd.format(n));
}
endlen = et.getText().length();
int sel = (cp + (endlen - inilen));
if (sel > 0 && sel <= et.getText().length()) {
et.setSelection(sel);
} else {
// place cursor at the end?
et.setSelection(et.getText().length() - 1);
}
} catch (NumberFormatException nfe) {
// do nothing?
} catch (ParseException e) {
// do nothing?
}
et.addTextChangedListener(this);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
if (s.toString().contains(String.valueOf(df.getDecimalFormatSymbols().getDecimalSeparator())))
{
hasFractionalPart = true;
} else {
hasFractionalPart = false;
}
}
And Here is MainActivity:
final EditText amount = (EditText) findViewById(R.id.editText1);
final EditText duration = (EditText) findViewById(R.id.editText2);
final EditText interest = (EditText) findViewById(R.id.editText3);
amount.addTextChangedListener(new NumberTextWatcher(amount));
duration.addTextChangedListener(new NumberTextWatcher(duration));
interest.addTextChangedListener(new NumberTextWatcher(interest));
String amount1 = amount.getText().toString().replaceAll(",", "");
String duration1 = duration.getText().toString().replaceAll(",", "");
String interest1 = interest.getText().toString().replaceAll(",", "");
try{
double i = Double.parseDouble(amount1);
double j = Double.parseDouble(duration1);
double z = Double.parseDouble(interest1);
}
catch(NumberFormatException e){
}
Programs store and operate on numbers in a locale-independent way. Before displaying or printing a number, a program must convert it to a String that is in a locale-sensitive format. For example, in France the number 123456.78 should be formatted as 123 456,78, and in Germany it should appear as 123.456,78. So you can't just replace "," and ".".
The following code is an example on how to convert from double and back using the current currency of a user in the United States.
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Currency;
import java.util.Locale;
public class Test
{
public static void main(String[] args)
{
Locale currentLocale = Locale.getDefault();
Currency currentCurrency = Currency.getInstance(currentLocale);
Double currencyAmount = new Double(9876543.21);
NumberFormat currencyFormatter =
NumberFormat.getCurrencyInstance(currentLocale);
System.out.println(NumberFormat.getNumberInstance(currentLocale));
System.out.println(
currentLocale.getDisplayName() + ", " +
currentCurrency.getDisplayName() + ": " +
currencyFormatter.format(currencyAmount));
try
{
System.out.println(currencyFormatter.parseObject("$9,876,543.21"));
}
catch (ParseException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
What else could you do:
* make sure users are entering properly formatted numbers. For example, you should not see any other chars except numbers , . + - $, etc.
* IF you know the user will ALWAYS enter two decimal digits, for example, 10 dollars would be expressed as 10.00 (or 10,00), then you can safely remove all "," and "." and get the original number by dividing it by 100, but remember to also remove spaces (remember France :) )
Also, check the documentation: http://docs.oracle.com/javase/tutorial/i18n/format/numberFormat.html
The problem is probably that other users might be inputting ill-formatted numbers. So you are just replacing the commas with white spaces. Maybe you should replace all non-digit characters?
amount1 = amount.getText().toString().replaceAll("[^\\d]", "");
Or if you want them to leave the decimal points then use the following:
amount1 = amount.getText().toString().replaceAll("[^\\d.]", "");

Constructor not setting values? Get method not working [duplicate]

When I try to run this program, the result is always null, 0 0. Why do the values of monthName, day, and year not show up when the getDay() method is invoked and printed on the screen.
public class Assignment1 {
public static void main(String[] args) {
//creates an array of type Date filled with two LongDate objects
Date [] collectionOfDates = { new LongDate("February",2,1996), new LongDate("February",13,1999) };
// loops through the array and displays output of getDate() for each object
for( int i = 0; i < collectionOfDates.length; i++ ) {
System.out.println( collectionOfDates[i].getDate() );
}
}
}
For your information, the LongDate class is a subclass of the Date class which contains methods editDay() and editYear() along with several others. The LongDate method is listed below.
Any help greatly appreciated, Thanks. Also, feel free to comment if you want more information.
public class LongDate extends Date {
private String monthName;
private int day;
private int year;
public LongDate() {
}
public LongDate(String m, int d, int y) {
super.editday(d);
super.edityear(y);
editMonth(m);
}
public void setDate(String m, int d, int y) {
monthName = m;
day = d;
year = y;
}
public String getDate() {
StringBuilder fullDate = new StringBuilder();
fullDate.append(monthName);
fullDate.append(" ");
fullDate.append(day);
fullDate.append(", ");
fullDate.append(year);
return fullDate.toString();
}
public String getShortDate() {
int month = 0;
if (monthName == "January") {
month = 1;
} else if (monthName == "February") {
month = 2;
} else if (monthName == "March") {
month = 3;
} else if (monthName == "April") {
month = 4;
} else if (monthName == "May") {
month = 5;
} else if (monthName == "June") {
month = 6;
} else if (monthName == "July") {
month = 7;
} else if (monthName == "August") {
month = 8;
} else if (monthName == "September") {
month = 9;
} else if (monthName == "October") {
month = 10;
} else if (monthName == "November") {
month = 11;
} else if (monthName == "December") {
month = 12;
}
StringBuilder shortDate = new StringBuilder();
shortDate.append(month);
shortDate.append("/");
shortDate.append(day);
shortDate.append("/");
shortDate.append(year);
return shortDate.toString();
}
protected String editMonth(String m) {
// asks person to try again if month is not capitalized and spelled properly
if (m != "January" && m != "February" && m != "March" && m != "April" && m != "May" && m != "June" && m != "July" && m != "August" && m != "September" && m != "October" && m != "November" && m != "December") {
m = Input.getString( "Invalid month. Please type the month again." );
return m;
} else
return m;
}
}
There's nothing in the constructor of LongDate which sets the fields (monthName, day, and year) that getDate() reads.
I assume that the Date#editDay() and Date#editYear() functions look similar to LongDate#editMonth(). Note that editMonth() does not assign a value to the monthName field!
You should compare your strings with equals() and not ==. The equals() method compares string values, whereas == compares object references, which is not what you want here. So change:
if (monthName == "January") {
to:
if (monthName.equals("January")) {
and similarly for the other comparisons.
Couple of issues. First:
public LongDate(String m, int d, int y) {
super.day(d);
super.year(y);
editMonth(m);
}
You don't show Date so it is unclear to us what day() and year() are supposed to do, but regardless:
public class LongDate extends Date {
private String monthName;
private int day;
private int year;
...
}
Your declarations of these fields are hiding any similar fields that the base presumably has. In any case, at no point in your constructor are you setting this.day or this.year to anything, and so, of course, they remain at their initial value of 0.
You need to clean up your code a bit. Either refer to the correct day and year, or make sure you are setting and getting the base class' version of those fields instead of redeclaring them in the subclass (again, not sure what your base implementation does).
You may want to have a look at the official tutorial on Inheritance. It's concise and well-written and covers topics like overriding methods, hiding fields, etc. I think it will give you a good starting point for solving your issues here.
And, of course, comparing strings with == here will lead to other issues in the future: How do I compare strings in Java?
Your editMonth method returns a string, instead it should set the month:
monthName = m;
Another option is to keep the editMonth method the same, but in your constructor put:
monthName = editName(m);

Need assistance with attributes in Java

What I'm trying to do is access an object, in this case date1 which has 3 attributes day, month and year. I'm attempting to make a method called showTomorrow() which will display the objects information 1 day infront in String format. This means I cannot alter the attributes of the original object.
I've written the Data.java program and it's shown below, if someone could point me in the right direction or show me what it would be really helpfull.
This is what I'd essentially be running on my main method I believe.
**Date date1 = new Date(30, 12, 2013)** // instantiate a new object with those paramaters
**date1.showDate();** // display the original date
**date1.tomorrow();** // shows what that date would be 1 day infront
The problem is right now it's not displaying anything. I thought that by saying dayTomorrow = this.day++; I was adding it's default value + 1 day to the variable dayTomorrow.
public class Date
{
private int day;
private int month;
private int year;
private int dayTomorrow;
private int monthTomorrow;
private int yearTomorrow;
public Date()
{
day = 1;
month = 1;
year = 1970;
}
public Date(int inDay, int inMonth, int inYear)
{
day = inDay;
month = inMonth;
year = inYear;
}
public void setDate(int inDay, int inMonth, int inYear)
{
day = inDay;
month = inMonth;
year = inYear;
}
public String getDate()
{
String strDate;
strDate = day + "/" + month + "/" + year;
return strDate;
}
public String getTomorrow()
{
String strTomorrow;
strTomorrow = dayTomorrow + "/" + monthTomorrow + "/" + yearTomorrow;
return strTomorrow;
}
public String tomorrow()
{
dayTomorrow = this.day++;
monthTomorrow = this.month;
yearTomorrow = this.year;
if(dayTomorrow > 30)
{
dayTomorrow = 1;
monthTomorrow = this.month++;
}
if(monthTomorrow > 12)
{
monthTomorrow = 1;
yearTomorrow = this.year++;
}
return getTomorrow();
}
public void showDate()
{
System.out.print("\n\n THIS OBJECT IS STORING ");
System.out.print(getDate());
System.out.print("\n\n");
}
public void showTomorrow()
{
System.out.print("\n\n THE DATE TOMORROW IS ");
System.out.print(getTomorrow());
System.out.print("\n\n");
}
public boolean equals(Date inDate)
{
if(this.day == inDate.day && this.month == inDate.month && this.year == inDate.year)
{
return true;
}
else
{
return false;
}
}
}
You just need to use ++this.day, ++this.month and ++this.year. When you use this.day++ it returns the previous date value, not the new. Putting the ++ in the front solves the problem. Also, it changes the day value... you might want to change that to this.day + 1.
Are You calling showDate() after date1.tomorrow() to show your output?
or instead of date1.tomorrow(); call date1.showTomorrow();
Have a look at this : http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op1.html
post incremention ...
You could use the native date support in java but I figured you are just practicing right?
This should do the trick:
public class Date {
private int day = 1;
private int month = 1;
private int year = 1970;
private int dayTomorrow = day+1;
private int monthTomorrow;
private int yearTomorrow;
public Date()
{
tomorrow();
}
public Date(int inDay, int inMonth, int inYear)
{
day = inDay;
month = inMonth;
year = inYear;
tomorrow();
}
public void setDate(int inDay, int inMonth, int inYear)
{
day = inDay;
month = inMonth;
year = inYear;
}
public String getDate()
{
String strDate;
strDate = day + "/" + month + "/" + year;
return strDate;
}
public String getTomorrow()
{
String strTomorrow;
strTomorrow = dayTomorrow + "/" + monthTomorrow + "/" + yearTomorrow;
return strTomorrow;
}
public void tomorrow()
{
monthTomorrow = this.month;
yearTomorrow = this.year;
if(dayTomorrow > 30)
{
dayTomorrow = 1;
monthTomorrow = this.month++;
}
if(monthTomorrow > 12)
{
monthTomorrow = 1;
yearTomorrow = this.year++;
}
}
public void showDate()
{
System.out.print("\n\n THIS OBJECT IS STORING ");
System.out.print(getDate());
System.out.print("\n\n");
}
public void showTomorrow()
{
System.out.print("\n\n THE DATE TOMORROW IS ");
System.out.print(getTomorrow());
System.out.print("\n\n");
}
public boolean equals(Date inDate)
{
if(this.day == inDate.day && this.month == inDate.month && this.year == inDate.year)
{
return true;
}
else
{
return false;
}
}
}
Look carefully for any changes i've made ;)
Here's the main:
public static void main(String[] args) {
Date d = new Date();
d.showDate();
d.showTomorrow();
}

Java, Creating a calendar

In my Java class, I have to build a calendar application. I've got it mostly completed, however I need help with a couple of methods. I have commented the parts that I need help with. The code includes three classes and a main called TestCalendar. The functions I need help with are located in the Calendar class, named removeEvent(two of them, taking two different arguments), printEvents, and findEvents. Thanks in advance!
Here is the Date class.
public class Date {
int year, month, day;
//constructor
public Date(int yr, int mth, int dy){
year = yr;
if (yr < 2000 || yr > 2100)
{
System.out.println("Wrong Calander Year");
System.exit(1);
}
month = mth;
if (mth < 1 || mth > 12)
{
System.out.println("Wrong Month");
System.exit(1);
}
day = dy;
if (dy < 1 || dy > 31)
{
System.out.println("Wrong Day");
System.exit(1);
}
}
//accessor methods
public int getYear()
{
return year;
}
public int getMonth()
{
return month;
}
public int getDay()
{
return day;
}
//returns date in correct format
public String toString()
{
return "" + month + "/" + day + "/" + year;
}
}
Here is the Event class
public class Event {
Date date;
int hour;
String activity;
Event(int year, int month, int day, int hour, String activity)
{
if (year < 2000 || year > 2100)
{
System.out.println("Wrong Calander Year");
System.exit(1);
}
if (month < 1 || month > 12)
{
System.out.println("Wrong Month");
System.exit(1);
}
if (day < 1 || day > 31)
{
System.out.println("Wrong Day");
System.exit(1);
}
this.date = new Date(year, month, day);
this.hour = hour;
this.activity = activity;
}
public Date getDate()
{
return date;
}
public int getHour()
{
return hour;
}
public String getActivity()
{
return activity;
}
void setActivity(String newActivity)
{
this.activity = newActivity;
}
public String toString()
{
return "" + date +" " + "#" + hour +":" + " " + activity;
}
public boolean equals(Object obj)
{
if (obj instanceof Event)
{
return true;
}
else return false;
}
}
The Calendar class
public class Calander {
static final int MAXEVENTS = 10;
Event[] events;
int numEvents;
// constructor
public Calander() {
numEvents = 0;
events = new Event[MAXEVENTS];
}
void addEvent(int year, int month, int day, int hour, String activity) {
Event newEvent = new Event(year, month, day, hour, activity);
events[numEvents] = newEvent;
numEvents++;
}
void removeEvent(int year, int month, int day, int hour, String activity) {
{
if (events[numEvents] == null);
numEvents--;
}
}
// instructions say to remove (all) Event objects in the Calendar that are equals to the event argument. Use the equals method from the event class
void removeEvent(Event event) {
//what to put here?
}
// this method needs to print every Event in the associated Calendar that matches the date arguments. Print each on a separate line, using the toString method from the Event class.
void printEvents(int year, int month, int day) { // how to set equality
if (this.events[numEvents] == )
{
// what to put here?
}
}
// same as above but matches the (Date date) arguments
void printEvents(Date date) {
toString();
}
// Return the first Event in the Calendar that has a matching (equals) activity field. If no match is found, you must return a reference type, so return null.
Event findEvent(String activity) {
//what to put here?
return null;
}
void dump() {
for (int i = 0; i < MAXEVENTS; i++)
{
if (events[i] != null)
System.out.println(events[i]);
}
}
}
well, your event class has a method:
public boolean equals(Object obj)
Which, presumably, should return whether or not the passed event is equal to the instance.
So your void removeEvent(Event event) method should look similar to the following:
take note that this is psudo-code and not valid java. you're going to have to flesh out the details on your own.
void removeEvent(Event event)
{
foreach(event e in this.events)
{
if(event.equals(e))
{
// remove e from the events array
}
}
}
The rest of the methods are going to more or less be similar in concept to the first one with 2 varying factorrs:
how you identify a match
what you do with the match
Since this is homework, I don't actually want to do your homework. So as a hint, you want to use (your event).equals(comparing to other event), not "==".

Categories