Checking if an integer argument is defined for a method - java

Scenario: I am currently attempting to make a calendar in Java, one of the methods I have created (getMonthSize) is to get the size of a month (as shown). My goal currently is to make the method respond regardless of whether the argument is defined by the user (give the current month size if argument left blank, and give the size of the inputted month if argument is defined).
Efforts: I have given quite a thorough search for an answer on the web, I have come across answers testing to see if the arg.length==0 (although it turns out that works only if the arg is a String), and answers using something along the lines of "arg!==undefined" (which I think may be for javascript), with no avail. I have also learned that if an integer is not initialized, its default value will be 0, so that is what I tried to take advantage of with my code shown, although it seemed that java still expects me to input "0" for the method to work.
Question: I am hoping there is some command that checks if the argument is left blank, allowing me to set 2 cases, and achieve what I want with the method.
package model;
import java.util.Calendar;
public class myCalendar {
private Calendar calendar=Calendar.getInstance();
private int day=calendar.get(Calendar.DAY_OF_WEEK);
private int date=this.calendar.get(Calendar.DAY_OF_MONTH);
private int month=calendar.get(Calendar.MONTH)+1;
private int year=calendar.get(Calendar.YEAR);
public void setCalendar(int Year, int Month, int Date){
this.calendar.set(Year,Month-1,Date);
}
public int getDay(){
return day;
}
public int getDate () {
return date;
}
public int getMonth(){
return month;
}
public int getYear() {
return year;
}
public int getFirstDay () {
Calendar test = this.calendar;
test.set(year, month-1, 1);
return test.get(Calendar.DAY_OF_WEEK)-1;
}
public int getMonthSize (int num) {
int Month=0;
int days=0;
if (num>0){
Month=num;
} else {
Month=month;
}
if(Month==1||Month==3||Month==5||Month==7
||Month==8||Month==10||Month==12){
days=31;
}
if(Month==4||Month==6||Month==9||Month==11)
{
days=30;
}
if(Month==2)
{
if(((year%4==0)&&(year%100!=0))||(year%400==0))
{
days=29;
}
else
{
days=28;
}
}
return days;
}
public String getNow () {
String monthNames[]={"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
String a=monthNames[month-1]+", "+String.valueOf(year);
return a;
}
}

I hope that I understood your problem correctly.
Your problem is that your user can start the method without a valid argument. If you have a frontend than you should catch it there too. But in the backend (java) you can work with a try-block or simply with if-else.
Cast the Integer to a String and then use regex (maybe something like this
String text = num + "";
if (text != null && text.matches("\\d+")) {
//...
}
Or you can cast your Integer to a String and use String.isEmpty().isEmpty returns true if, and only if, length() is 0. (https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#isEmpty()).
Sting temp = num + "";
if (num.isEmpty()) {
//...
}
Or simply a try-catch Block where you cast your input to a new variable.
try {
Month = Integer.parseInt(num);
} catch (NumberFormatException e) {
// handle error
}
And please notice that your variable "Month" should be "month". In most programming communities everyone uses lowercase variables.
There are countless options how you can handle this situation and you can try every one of them. I hope that the ones I listed are all correct.
Edit:
Oh and I checked the other comments and I noticed that you are a beginner. Here are maybe some useful tips, so everyone in your class including the teacher can read easier your code. In most programming languages there is something like "checkstyle". It is hard to explain, but with some google you can find useful tips.
I will make a few "suggestions" to your code, which you can adopt or ignore. Like spaces between some characters some comments, etc.
But don't focus to hard on the quality. In some IDEs you can automatically format your code to "the standard". With Intellij it is. ctrl+alt+l
import java.util.Calendar;
public class myCalendar {
private Calendar calendar = Calendar.getInstance();
private int day = calendar.get(Calendar.DAY_OF_WEEK);
private int date = this.calendar.get(Calendar.DAY_OF_MONTH);
private int month = calendar.get(Calendar.MONTH) + 1;
private int year = calendar.get(Calendar.YEAR);
/**
* Description what the method does.
*
* #param Year what does the parameter?
* #param Month ""
* #param Date ""
*/
public void setCalendar(int Year, int Month, int Date) {
this.calendar.set(Year, Month - 1, Date);
}
public int getDay() {
return day;
}
public int getDate() {
return date;
}
public int getMonth() {
return month;
}
public int getYear() {
return year;
}
/**
* Description what the method does.
*
* #return value (short description)
*/
public int getFirstDay() {
Calendar test = this.calendar;
test.set(year, month - 1, 1);
return test.get(Calendar.DAY_OF_WEEK) - 1;
}
/**
* Description what the method does.
*
* #param num (short description)
* #return (short description)
*/
public int getMonthSize(int num) {
int month;
int days = 0; //My IDE tells me that need to be initialized, but why? Are there cases where the method returns 0?
//I think that num=100 returns 0, so maybe you can catch this case with if(num > 12) or something similar
if (num > 0) {
month = num;
} else {
month = this.month;
}
if (month == 1 || month == 3 || month == 5 || month == 7
|| month == 8 || month == 10 || month == 12) {
days = 31;
}
if (month == 4 || month == 6 || month == 9 || month == 11) {
days = 30;
}
if (month == 2) {
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) {
days = 29;
} else {
days = 28;
}
}
return days;
}
public String getNow() {
String monthNames[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
String a = monthNames[month - 1] + ", " + String.valueOf(year);
return a;
}
}

Related

Duplicate Value when parameter names are different and constructor chaining only giving zeros as output

Im trying to make 3 constructors to put into someone elses code. Im getting 2 weird errors. 1. its giving me a duplicate error when the names are different and 2. Its outputting only zeros even when there is user input to say other wise. Im assuming its my constructors but Im not sure. EDIT: Ive added the rest of the code for reference
public class MyDateChoice {
private static final String[] monthNames = {"January", "February",
"March", "April", "May", "June", "July", "August",
"September", "October", "November", "December"};
private static final int[] monthDays = {31, 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31};
private int day; // day of the month
private int month; // month in the year
private int year; // year
public MyDateChoice () {
this (0,0,0);
}
public MyDateChoice (int month, int day, int year) {
}
public MyDateChoice (String monthName, int day, int year) {
}
public MyDateChoice(int ddd, int year) {
if (year < 0) { // validate year
throw new IllegalArgumentException("year must be > 0");
}
if (ddd < 1 || ddd > 366) { // check for invalid day
throw new IllegalArgumentException("day out of range");
}
this.year = year;
int dayTotal = 0;
for (int m = 1;
m < 13 && (dayTotal + daysInMonth(m, year)) < ddd; ++m) {
dayTotal += daysInMonth(m, year);
this.month = 1;
}
this.day = ddd - dayTotal;
}
// Set the day
public void setDay(int day) {
if (day < 1 || day > daysInMonth(month, year)) {
throw new IllegalArgumentException("day out of range for current month");
}
this.day = day;
}
// Set the month
public void setMonth(int month) {
if (month <= 0 || month > 12) { // validate month
throw new IllegalArgumentException("month must be 1-12");
}
this.month = month;
}
// Set the year
public void setYear(int year) {
if (year < 0) { // validate year
throw new IllegalArgumentException("year must be > 0");
}
this.year = year;
}
// return Date in format: mm/dd/yyyy
public String toString() {
return String.format("%d/%d/%d", month, day, year);
}
// return Date in format: MonthName dd, yyyy
public String toMonthNameDateString() {
return String.format(
"%s %d, %d", monthNames[month ], day, year);
}
// return Date in format DDD YYYY
public String toDayDateString() {
return String.format("%d %d", convertToDayOfYear(), year);
}
// Return the number of days in the month
private static int daysInMonth(int month, int year) {
return leapYear(year) && month == 2 ? 29 : monthDays[month - 1];
}
// test for a leap year
private static boolean leapYear(int year) {
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
return true;
}
else {
return false;
}
}
// convert mm and dd to ddd
private int convertToDayOfYear() {
int ddd = 0;
for (int m = 1; m < month; ++m) {
if (leapYear(year) && m == 2) {
ddd += 29;
}
else {
ddd += monthDays[m -1];
}
}
ddd += day;
return ddd;
}
// convert from month name to month number
private static int convertFromMonthName(String monthName) {
for (int subscript = 0; subscript < 12; subscript++) {
if (monthName.equals(monthNames[subscript])) {
return subscript + 1;
}
}
throw new IllegalArgumentException("Invalid month name");
}
}
For the first issue, The constructor does not really care about the name of the variables as they are aliases. It only cares about the type of the input parameters, in this case both methods have two int inputs.
For the second issue, it seems for now you have implemented the default constructor which simply initializes all your members to zero. That's the reason why you are getting everything as zero (I am guessing this is the one only used for initialization of your new objects for now)
Design tips:
Rather than having setter for every member, it is a good practice to follow the builder pattern (https://dzone.com/articles/design-patterns-the-builder-pattern)
Rather than having many constructors with different parameter types you can use generic methods (https://docs.oracle.com/javase/tutorial/extra/generics/methods.html) or even simpler way is to use conversions. To elaborate this further:
This is what you have:
public MyDateChoice (int month, int day, int year) {
}
public MyDateChoice (String monthName, int day, int year) {
}
What you can do is create a static method that converts the month name from string to int, and this allows you to eliminate the second constructor:
public MyDateChoice (int month, int day, int year) {
}
public static int getMonthNameInt(Stringt monthName) {
}

Confusion about java dates comparison

Pre-notes:
Yes, this is homework.
Our school's tutor is out for the day
My book is useless
I'm not exactly sure what to search for on google for help with my confusion...
Question:
Anyway - The question / confusion that I have involves the first bit of code that I have in my program to test the compareTo method.
Would I use the variables at the top of the code as my variables in the static void main area, or assign new variables, like I do have?
The values in public Date()... <-- Is that the date that my code in static void main is comparing to? (If so, I have a piece of code that I want to use that uses the current date, rather than what's in Date()).
I may have more questions later on, but I hope that someone can clear up my confusion better than my book or google has proven thus far.
Code:
package date;
import java.util.*;
public class Date implements Comparable
{
static Scanner console = new Scanner(System.in);
private int dMonth; //Part a of confusion 1
private int dDay;
private int dYear;
public Date()
{
dMonth = 1; //Confusion 2
dDay = 1;
dYear = 1900;
}
public Date(int month, int day, int year)
{
dMonth = month;
dDay = day;
dYear = year;
}
public void setDate(int month, int day, int year)
{
dMonth = month;
dDay = day;
dYear = year;
}
public int getMonth()
{
return dMonth;
}
public int getDay()
{
return dDay;
}
public int getYear()
{
return dYear;
}
public String toString()
{
return (dMonth + "." + dDay + "." + dYear);
}
public boolean equals(Object otherDate)
{
Date temp = (Date) otherDate;
return (dYear == temp.dYear
&& dMonth == temp.dMonth
&& dDay == temp.dDay);
}
public int compareTo(Object otherDate)
{
Date temp = (Date) otherDate;
int yrDiff = dYear - temp.dYear;
if (yrDiff !=0)
return yrDiff;
int monthDiff = dMonth - temp.dMonth;
if (monthDiff !=0)
return monthDiff;
return dDay - temp.dDay;
}
public static void main(String[] args) //Part b of confusion 1
{
int month;
int day;
int year;
Date temp;
System.out.print("Enter date in the form of month day year");
month = console.nextInt();
day = console.nextInt();
year = console.nextInt();
System.out.println();
}
}
As mentioned in the comments, I think you need to read about the difference between static methods/attributes and the ones in instances. I think this is what you should be doing in the main method:
System.out.print("Enter date in the form of month day year");
Date date1 = new Date(console.nextInt(), console.nextInt(), console.nextInt());
System.out.print("Enter second date in the form of month day year");
Date date2 = new Date(console.nextInt(), console.nextInt(), console.nextInt());
System.out.println("Comparison result:");
System.out.println(date1.compareTo(date2));
Regarding your confusion points:
Class attributes
private int dMonth; //Part a of confusion 1
private int dDay;
private int dYear;
These are special variables. Each instance (that is, every object created with new Date) has its own value for dMonth, dDay and dYear. It is not accessible from the main because main is a static method, and thus doesn't have access to instance variables.
If you didn't understand, at least you know the names to search further.
Default constructor
public Date()
{
dMonth = 1; //Confusion 2
dDay = 1;
dYear = 1900;
}
Those values are used when you create a new Date object without specifying which month/day/year you want. So new Date(2, 3, 2013) means 2/3/2013, while new Date() means 1/1/1900.
No you can't, dMonth, dDay and dYear are member variables. If you want to use them directly inside your main method you will have to use the keyword static so that they become class variables. But no, that is not what you want.
Your main method is doing nothing useful really. Your confusion point 2 is a constructor:
Date d = new Date(); // Data Instance -> First constructor
d.getMonth(); // 1
d.getDay(); // 1
d.getYear(); // 1900
Date d2 = new Date(2, 2, 1901);
d2.getMonth(); // 2
d2.getDay(); // 2
d2.getYear(); // 1901
d2.setDate(3, 3, 1902);
d2.getMonth(); // 3
d2.getDay(); // 3
d2.getYear(); // 1902
d.getMonth(); // Still 1 since member variables of d are independent of d2
d.compareTo(d2); // -2 -> (1900 - 1902)
You can create date instances inside your main method and use code like the one above to access member variables (probably the whole point of your exercise).

Result does not show, date validation

Any idea why my code won't show the result? Maybe I messed up something, just new to programming by the way.
The goal of the program is to see if the date given by the main class is valid or not, it's not that specific on details such as the month of February and leap years so its pretty simple.
This is my DataRec.java :
public class DateRec {
int month, day, year;
boolean good;
public DateRec (){
month = 1;
day = 1;
year = 2008;
good = true;
}
public DateRec (int setMonth, int setDay, int setYear){
month = setMonth;
day = setDay;
year = setYear;
}
public void validate (){
if ((month < 0) || (month > 12)){
good = false;
if (year == 0)
good = false;
if ((day < 0) || (day > 31))
good = false;
}
}
#Override
public String toString() {
if (good = true) {
return String.format("%dd/%dd/%dddd", month, day, year);
} else {
return String.format("%dd/%dd/%dddd", month, day, year);
}
}
}
This is my main class DataRecTest.java:
public class DateRecTest {
public static void main (String[] args){
DateRec today = new DateRec(1,2,2014);
DateRec anyDay = new DateRec();
DateRec noDay = new DateRec(13,31,2014);
anyDay.validate();
today.validate();
noDay.validate();
today.toString();
anyDay.toString();
noDay.toString();
}
}
Default value of boolean (good) is false so you need to initialized good in constructor or validate() function i.e
good = true; // in constructor or validate function
To see the results you need to print them.
//To print in java use System.out.print() or println();
System.out.println(today.toString());
//or simply
System.out.println(today); // println will call today.toString() internally
[EDIT]
Since you are storing result in good I recommend the following:
public DateRec (int setMonth, int setDay, int setYear){
month = setMonth;
day = setDay;
year = setYear;
good = true;
validate();
}
Now you don't need to call validate() every-time; just check the value of good
your validate() is wrong.... It will always be set t false (default value) in whenever you use the 3- argument constructor. You are not setting it to true when date is correct.
change it to,
public void validate (){
if ((month <= 0) || (month > 12) || (year==0) || (day<=0) || (day>31)){
good = false;
}
else
{
good=true;
}

Simple way to add 30 days to a date

I'm new to programming (doing a course on Computer Science) and one of the exercises is to have the program read a date and then print the next 30 days over and over until the end of the year.
Problem is, there are restrictions. I cannot use Date/Calendar classes, only the Scanner class. So I'm having some trouble getting the dates right... so the only way I've found is to use Switch and have a case for each month, but then there's the issue with the 30/31-day months and leap years. So the days are not the same.
Is there a simpler way to do it?
If you can't use date/calendar classes, then the question is aimed at getting you to do the kind of things that date/calendar classes do internally. I wouldn't be surprised to see switch statements as part of your answer. You will need to teach your implementation knows how many days are in a month, which years are leap years etc.
You could use something like this,
Main class:
public class AppMain {
public static void main(String[] args) {
MyDate initDate = new MyDate(14, 1, 2012);
printMyDate(initDate);
MyDate newDate = initDate;
do{
newDate = DateIncrementator.increaseDate(newDate, 30);
printMyDate(newDate);
}while(newDate.getYear() == initDate.getYear());
}
private static void printMyDate(MyDate date){
System.out.println("[Day: "+ date.getDay() + "][" + "[Mont: "+ date.getMonth() + "][" + "[Year: "+ date.getYear() + "]");
}
}
DateIncrementator class:
public class DateIncrementator {
private static final int[] MONTH_DAYS_NOP_LEAP_YEAR = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
public static MyDate increaseDate(MyDate date, int numberOfDays){
if(numberOfDays < 1 || numberOfDays > 30){
throw new IllegalArgumentException("numberOfDays must have a value between 1 and 30");
}
int numberDaysCurrentMonth = MONTH_DAYS_NOP_LEAP_YEAR[date.getMonth() - 1];
if(date.getMonth() == 2 && isLeapYear(date.getYear())){
numberDaysCurrentMonth++;
}
int newDay = date.getDay();
int newMonth = date.getMonth();
int newYear = date.getYear();
newDay += numberOfDays;
if(newDay > numberDaysCurrentMonth){
newDay = newDay % numberDaysCurrentMonth;
newMonth++;
}
if(newMonth > 12){
newMonth = 1;
newYear++;
}
return new MyDate(newDay, newMonth, newYear);
}
private static boolean isLeapYear(int year){
if(year % 4 != 0){
return false;
}
if(year % 100 != 100){
return true;
}
if(year % 400 == 0){
return true;
}else{
return false;
}
}
}
MyDate class:
public class MyDate {
private int day; // 1 to 31
private int month; // 1 to 12
private int year; // 0 to infinite
public MyDate(int day, int month, int year) {
this.day = day;
this.month = month;
this.year = year;
}
public int getDay() {
return day;
}
public int getMonth() {
return month;
}
public int getYear() {
return year;
}
}

Can anyone please help me solve this?? (solving year 2000 with java) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have a project in school to solve year 2000 with java. here is the description of the assignment:
Create a Date object with the following:
attribute: a julian date representing the number of days since Jan 1, 1501 (the epoch date for this project) - this should be a private member variable of the class with the associated accessor and mutator methods.
constants: a suitable constant for each month
a suitable contant for each component of the epoch date
method: Date(long year, long month, long day) that converts the given year, month, and day to the julian date.
method: a method that converts a year, month, and day into the number of days since the project's epoch date.
method: a method that determines if a given year is a leap year
method: a method that returns the number of days in a given year; replace the current simple if statement with a single statement using the conditional operator (? :)
method: a method that returns the number of days in a given month of a given year; method should implement a switch statement using appropriate constants.
methods: any of the other methods developed in class should probably also be included.
method: returnYear() a method that determines the year component of the julian date value
method: returnMonth() a method that determines the month component of the julian date value
method: returnDay() a method that determines the day component of the julian date value
method: returnMonthName() a method that returns the name of the given month ( if month = JAN return "January" (use a switch statement))
method: returnDate() a method that returns the date in the format monthName day, year
class: Utility containing two query methods.
And here is the code I came with so far.. it is not compiling because there is something wrong with the switch!
import java.util.Scanner;
class Date
{
public final static long EPOCHYEAR = 1501;
private long julianDate;
Date(long year, long month, long day)
{
julianDate = returnTotalJulianDay(year, month, day);
System.out.println("Days is " + julianDate);
}
boolean isLeapYear(long year)
{
boolean answer;
if(year % 4 == 0 && (year % 4 == 0 || year % 100 != 0))
{
answer = true;
}
else
{
answer = false;
}
return answer;
}
long returnDaysInMonth(long year, long month)
{
if(month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)
{
return 31;
}
else if(month == 4 || month == 6 || month == 9 || month == 11)
{
return 30;
}
else if(isLeapYear(year))
{
return 29;
}
else
{
return 28;
}
}
long returnJulianDate(long year, long month, long day)
{
long julianDate;
long monthCounter;
julianDate = 0;
monthCounter = 1;
while(monthCounter < month)
{
julianDate += returnDaysInMonth(year, monthCounter);
monthCounter += 1;
}
julianDate += day;
return julianDate;
}
long returnTotalJulianDay(long year, long month, long day)
{
long totalJulianDay = 0;
long yearCounter = 1;
while(yearCounter < year)
{
totalJulianDay += returnJulianDate(year, month, yearCounter);
yearCounter += 1;
}
return totalJulianDay;
}
long returnDaysInYear(long year)
{
final long DAYSINYEAR = 365;
if(isLeapYear(year))
{
return 366;
}
else
{
return DAYSINYEAR;
}
}
long returnJulianEpochDays(long year, long month, long day)
{
long yearCounter = EPOCHYEAR;
long total = 0;
while(yearCounter < year)
{
total += returnDaysInYear(yearCounter);
yearCounter += 1;
}
total += returnJulianDate(year, month, day);
return total;
}
long returnYear()
{
long dayCounter = 0;
long yearCounter = EPOCHYEAR;
for(dayCounter = this.julianDate; dayCounter > returnDaysInYear(yearCounter); yearCounter++)
{
dayCounter -= returnDaysInYear(yearCounter);
}
return yearCounter;
}
long returnMonth()
{
long julianEpochDays = julianDate;
long yearCounter = EPOCHYEAR;
long monthCounter = 1;
while(julianEpochDays > returnDaysInYear(yearCounter))
{
julianEpochDays -= returnDaysInYear(yearCounter);
yearCounter++;
}
while(julianEpochDays > returnDaysInMonth(yearCounter, monthCounter))
{
julianEpochDays -= returnDaysInMonth(yearCounter, monthCounter);
monthCounter++;
}
return monthCounter;
}
long returnDay()
{
long julianEpochDays = julianDate;
long yearCounter = EPOCHYEAR;
long monthCounter = 1;
while(julianEpochDays > returnDaysInYear(yearCounter))
{
julianEpochDays -= returnDaysInYear(yearCounter);
yearCounter++;
}
while(julianEpochDays > returnDaysInMonth(yearCounter, monthCounter))
{
julianEpochDays -= returnDaysInMonth(yearCounter, monthCounter);
monthCounter++;
}
return julianEpochDays;
}
long returnMonthName()
{
int month = 0;
final int JAN = 1;
final int FEB = 2;
final int MAR = 3;
final int APR = 4;
final int MAY = 5;
final int JUN = 6;
final int JUL = 7;
final int AUG = 8;
final int SEP = 9;
final int OCT = 10;
final int NOV = 11;
final int DEC = 12;
switch(month)
{
case JAN:
return "January";
case FEB:
return "Febuary";
case MAR:
return "March";
case APR:
return "April";
case MAY:
return "May";
case JUN:
return "June";
case JUL:
return "July";
case AUG:
return "August";
case SEP:
return "September";
case OCT:
return "October";
case NOV:
return "November";
case DEC:
return "December";
}
}
}
class utility
{
public char queryForCharacter(String prompt)
{
int typedCharacter = ' ';
try
{
System.out.print(prompt);
typedCharacter = System.in.read();
}
catch(Exception e)
{
}
return (char) typedCharacter;
}
public static long queryForLong(String prompt)
{
Scanner keyboard;
long theNumber;
keyboard = new Scanner(System.in);
System.out.print(prompt);
theNumber = keyboard.nextInt();
return theNumber;
}
}
public class DateDriver
{
public static void main(String[] args)
{
Date aTestDate = null;
aTestDate = new Date(1502, 1, 1);
}
}
Your method returnMonthName() is declared to return a long, but the switch cases return Strings.
Also, the method needs to return something if none of the cases in the switch match.
Your function returns a type of long:
"long returnMonthName() {"
But your are returning a type of "String". i.e. "January".

Categories

Resources