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;
}
Related
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;
}
}
When I run the following code I receive the error -
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
at homework6.main(homework6.java:6)
I researched why this could occur and previous answers had said the class name needed to match the java file name, my class matches that of the .java file as well. I also tried removing "void" and the entire statement altogether, but then a new error occurred saying I needed public void main(String[] args). Am I encountering a different problem then the class and .java?
public class homework6 {
public static void main(String[] args) {
class Date {
private int month;
private int day;
private int year;
private String name;
public Date() {
}
{
month=1;
day = 1;
year = 2001;
name = "January";
}
public Date(int m, int d, int y) {
setDate(m, d, y);
}
public void setDate(int m, int d, int y) {
month = m;
day = d;
year = y;
if (m ==1 )
name="January";
else if(m == 2)
name="February";
else if(m == 3)
name="March";
else if(m == 4)
name="April";
else if(m == 5)
name = "May";
else if(m == 6)
name = "June";
else if(m == 7)
name = "July";
else if(m == 8)
name = "August";
else if(m == 9)
name = "September";
else if(m == 10)
name = "October";
else if(m == 11)
name="November";
else if(m == 12)
name = "December";
}
public void showDate1() {
System.out.println(month + "/" + day + "/" + year);
}
public void showDate2() {
System.out.println(name + "" + day + "," + year);
}
public void showDate3() {
System.out.println(day + "" + name + "" + year);
}
}
}
}
You're nesting a class, Date, within a method, the main method to be precise -- something you can't and shouldn't do.
Solution: don't do this.
Create one file called Date.java and place your Date class code in it.
Create a 2nd file called Homework6.java and place your main method in it.
Done.
Valid points those in the answer. You could alternatively just put the class outside the main and get it to compile.
If you take a step back though, and assuming you get this code to compile, what would be the expected output? You seem to make no calls to any methods. Do you want to spend a moment in understanding your logic?
Probably because of this:
public Date() {
}
{
month=1;
day = 1;
year = 2001;
name = "January";
}
The first two brackets should be removed, because the code between the second two is not in a method. So it should be like this:
public Date() {
month=1;
day = 1;
year = 2001;
name = "January";
}
Below is a class that represents time using hours and minutes (seconds are not represented).
public class ClassTime {
public static int hour;
public static int minute;
public static String amPm;
//Initializes the object using specified parameter values.
public ClassTime(int hour, int minute, String amPm){
//hour value between 1 and 12, both inclusive.
boolean validHour = false;
if (hour >= 1 && hour <= 12){
validHour = true;
this.hour = hour;
} else {
throw new IllegalArgumentException("Invalid hour value");
}
//minute value between 0 and 59, both inclusive.
boolean validMinute = false;
if (minute >= 0 && minute <= 59){
validMinute = true;
this.minute = minute;
} else {
throw new IllegalArgumentException("Invalid minutes value");
}
//amPm is either "am" or "pm".
if (amPm.equalsIgnoreCase("am")){
this.amPm = amPm;
} else if (amPm.equalsIgnoreCase("pm")){
this.amPm = amPm;
} else {
throw new IllegalArgumentException("Invalid am/pm value");
}
}
/*
* Returns a string using the format "hour:minutes am" or "hour:minutes pm".
* A single space is used in between minutes and am/pm. The minutes always
* appear with two digits (e.g., 0 minutes will be "00").
*/
public String toString(){
String toBeReturned = "hour:" + String.format("%02d", this.minute) +
" " + amPm;
return toBeReturned;
}
/*
* Compares two time objects. Two time objects are considered equal if
* they represent the same time.
*/
public boolean equals(ClassTime obj){
boolean equal = false;
if (obj.minute == this.minute && obj.hour == this.hour &&
obj.amPm.equalsIgnoreCase(this.amPm)){
equal = true;
}
return equal;
}
/*
* Compares two time objects. Returns -1 if the current object is a time
* that precedes the time parameter, 0 if the current object and the time
* parameter represent the same time, and 1 if the current object represents
* a time that is after the time parameter.
*/
public int compareTo(ClassTime obj){
int returnNum = 2;
if(this.amPm.equalsIgnoreCase("am") && obj.amPm.equalsIgnoreCase("pm")){
returnNum = -1;
} else if (this.amPm.equalsIgnoreCase("pm") &&
obj.amPm.equalsIgnoreCase("am")){
returnNum = 1;
} else if (this.amPm.equalsIgnoreCase(obj.amPm)){
if (this.hour < obj.hour){
returnNum = -1;
} else if (this.hour > obj.hour){
returnNum = 1;
} else if (this.hour == obj.hour){
if (this.minute < obj.minute){
returnNum = -1;
} else if (this.minute > obj.minute){
returnNum = 1;
} else if (this.minute == obj.minute){
returnNum = 0;
}
}
}
return returnNum;
}
/*
* Returns a new time object corresponding to the time we will have after
* increasing the time parameter by the specified number of minutes.
*/
public static ClassTime increaseByMinutes(ClassTime obj, int minutes){
//create variables that monitor changes in minutes, hours, and amPm.
int minValue = obj.minute + minutes;
int hourValue = obj.hour;
String amPmValue = obj.amPm;
/*
* increments hour and minutes if the total minutes is below two hours,
* but greater tan or equal to 1 hour.
*/
if(minValue > 59 && minValue < 120){
minValue = minValue % 60;
hourValue = hourValue + 1;
if (hourValue > 12){
hourValue = hourValue % 12;
} else if(hourValue == 12 && amPmValue.equalsIgnoreCase("am")){
amPmValue = "pm";
} else if (hourValue == 12 && amPmValue.equalsIgnoreCase("pm")){
amPmValue = "am";
}
/*
* Increment for when the total amount of minutes is greater
* or equal to 2 hours.
*/
} else if (minValue > 119){
for(int i = 0; i <= (minValue/60); i++){
hourValue++;
if(hourValue > 12){
hourValue = hourValue % 12;
} else if (hourValue == 12 && amPmValue.equalsIgnoreCase("am")){
amPmValue = "pm";
} else if (hourValue == 12 && amPmValue.equalsIgnoreCase("pm")){
amPmValue = "am";
}
}
}
/*
* Create a new ClassTime object with the found values of minutes, hours,
* and amPm Value. This is what will be returned.
*/
ClassTime newObject = new ClassTime(hour, minute, amPm);
newObject.minute = minValue;
newObject.hour = hourValue;
newObject.amPm = amPmValue;
return newObject;
}
public static void main(String[] args) {
}
}
I don't know how to test the constructor or the methods in a JUnit test case. So far the only thing I can come up with for the constructor is:
import static org.junit.Assert.*;
import org.junit.Test;
public class JunitTests {
#Test
public void testClassTime() {
ClassTime object1 = new ClassTime(3, 30, "pm");
}
}
How would I finish doing a test for the constructor and maybe just 1 method. Please don't do all of them.
I suggest you read up on unit testing, your question is a bit too broad.
Basically the idea is that given some situation, when a thing happens, then some conditions should be true. (I personally add comments to my tests to help me think in those terms.)
Here's an abstract example:
Given bread and a toaster
When I put the bread in the toaster and get it out when it's done
Then it should be toasted
Look up JUnit's assertion library to help find good ways to assert conditions. When looking up JUnit examples you'll usually see things like assertTrue(...) or assertNotNull(...), these are static methods from the Assert class, I mention this because you seem like a novice and I don't want you to get confused by examples. Usually all these methods are imported statically in the examples.
What you have in your test case currently is the given, a when could be doing toString() (String actual = object1.toString();). Your then clause would be asserting that the String returned equals what it should, which is probably "3:30 PM" (assertEquals("3:30 PM", actual);). I didn't design your code, so I don't know if that's correct, you may expect it to return `"Hello, World!" In any case, I'd run this one first ;)
Excel has a function named NETWORKDAYS.INTL. It receives a start date, an end date, a "type" of weekend and a list of holidays and calculates the number of working days between the two dates. The weekend flag is important because I can consider saturday as a working day. More info here:
http://office.microsoft.com/en-nz/excel-help/networkdays-intl-function-HA010354379.aspx
Is there something like NETWORKDAYS.INTL in Java? Using ObjectLab Kit, Joda and Jollyday I can keep my national holidays and check if the day is saturday, sunday or holiday, but to calculate like the function above I need to iterate over each day and check if valid.
I found nothing so I just code my own method. In my application all dates are saved as timestamp.
public boolean isHoliday(long date) {
return holidaysCalendar.isHoliday(new LocalDate(date));
}
public boolean isSaturday(long date) {
return (new LocalDate(date).dayOfWeek().get() == 7);
}
public boolean isSunday(long date) {
return (new LocalDate(date).dayOfWeek().get() == 1);
}
public boolean isValid(long date, boolean saturday, boolean sunday) {
boolean valid = true;
if (isHoliday(date)) {
valid = false;
} else {
if (!saturday && isSaturday(date)) {
valid = false;
}
if (!sunday && isSunday(date)) {
valid = false;
}
}
return valid;
}
public long addDays(long date, int days) {
return new LocalDate(date).plusDays(days).toDateTimeAtStartOfDay()
.getMillis();
}
public int validDaysBetweenDates(long date1, long date2,
boolean saturday, boolean sunday) {
date1 = addDias(date1, 1);
int cont = 0;
for (long dateTmp = date1; dataTmp <= date2; dataTmp = addDays(dataTmp, 1)) {
if (isValid(dataTmp, saturday, sunday))
cont++;
}
return cont;
}
I have to validate the date,For example If I enter 31/2/2013,It should give an error as February doesn't contains 31 days,but I am stuck at how to achieve that,I tried to use the switch statement but still in vain.Help would be much appreciated.
public class Date
{
private int PDay;
private int PMonth;
private int PYear;
public Date(int day,int month,int year)
{
setDay(day);
setMonth(month);
setYear(year);
}
public Date(int month,int year)
{
this(1,month,year);
}
public Date(int year)
{
this(1,1,year);
}
public void setDay(int day)
{
PDay=day;
}
public int getDay()
{
return PDay;
}
public void setMonth(int month)
{
if(month>=1 && month<=12)
PMonth=month;
else
System.out.println("Month Invalid-Must be Between 1 & 12");
}
public int getMonth()
{
return PMonth;
}
public void setYear(int year)
{
if(year>=1950 && year<=2049)
PYear=year;
else
System.out.println("Year Invalid-Must be Between 1950 & 2049");
}
public int getYear()
{
return PYear;
}
public String toString()
{
return PDay+"/"+PMonth+"/"+PYear;
}
}
P.S. Its not Homework :P/>
Test Program is:
public class DateTest
{
public static void main(String[] args)
{
Date newDate = new Date(7,14,2012);
Date newDate1 = new Date(2152);
System.out.println(newDate);
System.out.println(newDate1);
}
}
In the constructor, set the day after the year and month:
public Date(int day, int month, int year) {
setYear(year);
setMonth(month);
setDay(day);
}
And in the method setDay() add the validation logic:
public void setDay(int day) {
if (pMonth == 1 && (day < 1 || day > 31)) {
// throw exception or handle error
throw new IllegalArgumentException("invalid number of days");
} else if (pMonth == 2 && (day < 1 || day > 28)) {
// same thing
}
// ... rest of validations
PDay = day;
}
If you want to be even more strict, you can use the year to determine if February has 28 or 29 days.
EDIT: Don't implement date handling on your own as long as there are existing frameworks fitting your needs.
But beware of the pitfalls of some of the existing frameworks: (end of EDIT)
Don't use java.util.Date for such checks. Nearly all of the methods of Date are buggy and have been declared as deprecated. Those setters and getters have been reimplemented in the java.util.Calendar classes. But since they are still buggy in some circumstances the best choice would be to use the new Date Time API of Java 8 if this is an option or to use the "third-party" Jodatime library for correct date handling.
If you just want to have some checks on input, then you may use java.text.SimpleDateFormat that handles the parsing and the checks.