Calling a method from another method (java) - java

I started learning java on my own a few weeks back and I keep running up to the same basic problem, where I can't call a method from another method in the same class. I either get a "symbol not found" error (I think because the method is out scope or the method just doesn't work anymore. The following code is part of a java exercise for creating a calender sort of a programme. I'll use the // in code commentaries to indicate, where exactly is the problem.
public class MyDate {
private int year;
private int month;
private int day;
private static String[] strMonths = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
private static String[] strDays = {"Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday"};
private static int[] daysInMonths = {31, 28, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
public static boolean isLeapYear(int year) { // This is the first method, which works fine
// when being called from the main method.
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) {
return true;
} else {
return false;
}
};
public static boolean isLeapYear; // I put this declaration in, because I got
// "symbol not found" errors, when referencing the method from the second method.
// I'm guessing it partially invalidates the first declaration.
public static boolean isValidDate(int year, int month, int day) { // The second method
if ((year >= 1 ) && (year <= 9999)){
if ((month >= 0) && (month <= 11)) {
if ((day >= 1) && ((month == 0) || (month == 2) || (month == 4) || (month == 6)
|| (month == 7) || (month == 9) || (month == 11)) && (day <= 31)) {
return true;
}
else if ((day >= 1) && ((month == 3) || (month == 5) || (month == 8)
|| (month == 10) && (day <= 30))) {
return true;
}
else if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)){
// Code from the first method (above), which I would like to replace with just a reference
// to the first method (for instance (isLeapYear = true)),
// but it doesn't work the same as the code above (or at all).
if ((month == 1) && (day == 29)) {
return true;
}
else
if ((day >= 1) && ((month == 1) && (day <= 28))) {
return true;
}
else {
return false;
}
}
}
}
return isValidDate; }
For reference, the method isLeapYear works as it's supposed to, when testing it with this main method:
public static void main(String[] args) {
System.out.println(isLeapYear(1900)); // false
System.out.println(isLeapYear(2000)); // true
System.out.println(isLeapYear(2011)); // false
System.out.println(isLeapYear(2012)); // true
}
}
Thanks for your help!

Remove public static boolean isLeapYear; from your code and every time you need to call a function, in this case public static boolean isLeapYear(int year) { ..} you must use a parenthesis to let the compiler know that you are actually calling a function there.
In this case you should go with isLeapYear(year)
and then if (isLeapYear(year)) { .. } else {..}

Given package name of MyApplication (substitute your package name in each place this one occurs below) import isLeapYear as shown below.
package MyApplication;
public class MyDate {
public static boolean isLeapYear(int year) { // This is the first method, which works fine
// when being called from the main method.
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) {
return true;
} else {
return false;
}
};
}
Main class:
package MyApplication;
import static MyApplication.MyDate.isLeapYear;
public class NewClass{
public static void main(String[] args) throws Exception
{
System.out.println(isLeapYear(1900)); // false
System.out.println(isLeapYear(2000)); // true
System.out.println(isLeapYear(2011)); // false
System.out.println(isLeapYear(2012));
}
}

Related

Condtional statements using Calendar.HOUR_OF_DAY

I have this code and it has to show one of the strings based on the time of the day.
The code is
public void onTimeTick() {
mTime.setTimeInMillis(System.currentTimeMillis());
// Let's see what string we need according to the time
int saluteResId = R.string.salute_fallback;
if (mTime.get(Calendar.HOUR_OF_DAY) > 4) {
saluteResId = R.string.salute_morning;
} else if (mTime.get(Calendar.HOUR_OF_DAY) > 12) {
saluteResId = R.string.salute_evening;
} else if (mTime.get(Calendar.HOUR_OF_DAY) > 19 || mTime.get(Calendar.HOUR_OF_DAY) < 5) {
saluteResId = R.string.salute_night;
}
}
But the problem is that HOUR_OF_DAY will always remain greater than 4 so it will never even check the remaining two conditions and the string will always be set to salute_morning. I am not very good in java and trying to figure out how I can make the first condition false so it will check the other conditions and set the string according to them.
I think this can be helpful
if (mTime.get(Calendar.HOUR_OF_DAY) > 4 && mTime.get(Calendar.HOUR_OF_DAY) <= 12) {
//saluteResId = R.string.salute_morning;
} else if (mTime.get(Calendar.HOUR_OF_DAY) > 12 && mTime.get(Calendar.HOUR_OF_DAY) <= 19) {
//saluteResId = R.string.salute_evening;
} else if (mTime.get(Calendar.HOUR_OF_DAY) > 19 && mTime.get(Calendar.HOUR_OF_DAY) <= 4) {
//saluteResId = R.string.salute_night;
}
Try this code
final Calendar d = Calendar.getInstance();
final int hh = d.get(Calendar.HOUR_OF_DAY);
//try this way
String time = null;
if (hh == 0) {
time =("Salute_Night");
} else if (hh == 1) {
time =("Salute_Night");
} else if (hh == 2) {
time =("Salute_Night");
} else if (hh == 3) {
time =("Salute_Night");
} else if (hh == 4) {
time =("Salute_Night");
} else if (hh == 5) {
time =("Salute_Morning");
} else if (hh == 6) {
time =("Salute_Morning");
} else if (hh == 7) {
time =("Salute_Morning");
} else if (hh == 8) {
time =("Salute_Morning");
} else if (hh == 9) {
time =("Salute_Morning");
} else if (hh == 10) {
time =("Salute_Morning");
} else if (hh == 11) {
time =("Salute_Morning");
} else if (hh == 12) {
time =("Salute_Evening");
} else if (hh == 13) {
time =("Salute_Evening");
} else if (hh == 14) {
time =("Salute_Evening");
} else if (hh == 15) {
time =("Salute_Evening");
} else if (hh == 16) {
time =("Salute_Evening");
} else if (hh == 17) {
time =("Salute_Evening");
} else if (hh == 18) {
time =("Salute_Evening");
} else if (hh == 19) {
time =("Salute_Evening");
} else if (hh == 20) {
time =("Salute_Night");
} else if (hh == 21) {
time =("Salute_Night");
} else if (hh == 22) {
time =("Salute_Night");
} else if (hh == 23) {
time =("Salute_Night");
}
//your text view where you want it to display
textviewTimeOfDay.settext.(time);

Why can't my test class run?

so I am trying to do a test class, the instruction is
Create a class called TestDate whose constructor creates fifteen Date objects and displays the day of the week for the dates by calling each Date’s getDayOfTheWeek() method. The dates are specifically these ones, in this precise order:
but when I run it, I keep getting errors! I think it's my constructor crashing or somewhere along that line.
Below is my TestDate class code
public class TestDate
{
private Date date;
/*
* Main Constructor
* #param fifteen specific date, test to your heart's content
*/
public TestDate()
{
Date d1 = new Date(1970, 11, 15);
System.out.println(date.getDayOfTheWeek());
Date d2 = new Date(1887, 7, 31);
Date d3 = new Date(1966, 5, 2);
Date d4 = new Date(1980, 8, 19);
Date d5 = new Date(2001, 9, 11);
Date d6 = new Date(1900, 6, 26);
Date d7 = new Date(1940, 2, 28);
Date d8 = new Date(1974, 10, 30);
Date d9 = new Date(1914, 1, 15);
Date d10 = new Date(1840, 10, 1);
Date d11 = new Date(1999, 12, 31);
Date d12 = new Date(1988, 5, 20);
Date d13= new Date(2012, 3, 10);
Date d14 = new Date(2006, 4, 1);
Date d15 = new Date(1992, 2, 29);
}
}
And here is my Date Class constructor and method getDayofTheWeek, I think that's all the information related to my problem.
public class Date
{
public Date(int year, int month, int day)
{
setYear(year);
setMonth(month);
setDay(day);
}
public String getDayOfTheWeek()
{
int step0 = year%100;
int step1 = step0 / 12;
int step2 = step0 % 12;
int step3 = step2 / 4;
int step4 = day;
int step5 = 0;
if(month == JANUARY || month == OCTOBER)
{
step5 = JAN_CODE;
}
else if(month == FEBURARY || month == MARCH || month == NOVEMBER)
{
step5 = FEB_CODE;
}
else if(month == APRIL || month == JULY)
{
step5 = APR_CODE;
}
else if(month == MAY)
{
step5 = MAY_CODE;
}
else if(month == JUNE)
{
step5 = JUN_CODE;
}
else if(month == AUGUST)
{
step5 = AUG_CODE;
}
else if(month == SEPTEMBER || month == DECEMBER)
{
step5 = SEP_CODE;
}
else
{
step5 = 0;
}
if(year/100 ==16 || year/100 == 20)
{
step5 = step5 + SPECIAL_CODE_SIX;
}
else if(year/100 == 17 || year/100 == 21)
{
step5 = step5 + SPECIAL_CODE_FOUR;
}
else if(year/100 == 18)
{
step5 = step5 + SPECIAL_CODE_TWO;
}
int step6 = (step1 + step2 + step3 +step4 + step5)%MOD_CODE;
if(step6 == SAT_CODE)
{
return "Saturday";
}
else if(step6 == SUN_CODE)
{
return "Sunday";
}
else if(step6 == MON_CODE)
{
return "Monday";
}
else if(step6 == TUE_CODE)
{
return "Tuesday";
}
else if(step6 == WED_CODE)
{
return "Wednesday";
}
else if(step6 == THU_CODE)
{
return "Thursday";
}
else if(step6 == FRI_CODE)
{
return "Friday";
}
else
{
return null;
}
}
}
and I passed the parameter in the mutator method
public void setYear(int year)
{
if(year <= CURRENT_YEAR && year >= YEAR_ZERO)
{
this.year = year;
}
}
public void setMonth(int month)
{
if(month <= DECEMBER && month >= JANUARY)
{
this.month = month;
}
}
public void setDay(int day)
{
if(month == JANUARY || month == MARCH || month == MAY || month == JULY || month == AUGUST
|| month == OCTOBER || month == DECEMBER)
{
if(day <= DAY_THIRTY_ONE && day >= DAY_ONE)
{
this.day = day;
}
else
{
year = CURRENT_YEAR;
month = JANUARY;
day = DAY_ONE;
}
}
else if(month == APRIL || month == JUNE || month == SEPTEMBER || month == NOVEMBER)
{
if(day <= DAY_THIRTY && day >= DAY_ONE)
{
this.day = day;
}
else
{
year = CURRENT_YEAR;
month = JANUARY;
day = DAY_ONE;
}
}
else if(month == FEBURARY)
{
if((isLeapYear() == true) && day <= DAY_FEB_LEAP && day >= DAY_ONE)
{
this.day = day;
}
else if((isLeapYear() == false) && day <= DAY_FEB_NORMAL && day >= DAY_ONE)
{
this.day = day;
}
else
{
year = CURRENT_YEAR;
month = JANUARY;
day = DAY_ONE;
}
}
}
Sorry for the long list of code, I don't really know which ones are useless.
In the second line of your constructor you are calling
System.out.println(date.getDayOfTheWeek());
on the variable date which is null at this point as it has not been initialized yet. This leads to a NullPointerException. Read here for more information: What is a NullPointerException, and how do I fix it?
What I am (assuming) you wanted to do there is:
System.out.println(d1.getDayOfTheWeek());
Things besides that that I noticed:
You use the #param field in a javadoc comment without there being a parameter. Do not do this. If your constructor does not take arguments then there should not be a #param.
You are creating 15 instances of Date in your constructor whose scope end as soon as the constructor is finished. You could just delete them and nothing would change. I am assuming you want this class to be a "test" whether your dates are initialized correctly. I would recommend doing this in a main method (for a quick test while coding) and with an actual test framework like JUnit for 'real' testing. You can read this tutorial if you are interested. It also goes into detail why you actually want to test.

Nesting If Statements in Java

I am having trouble nesting these if statements from Python to Java.
def leapyear(yearr):
if (year % 4 == 0):
if (year % 100 == 0):
if (year % 400 == 0):
return True
else:
return False
else:
return True
else:
return False
I currently am working to convert the above to Java:
boolean leapyear(int year) {
if (year % 4==0) {
if (yearr%100==0) {
if (year%400==0) {
else
return false;
}
else
return true;
}
else
return false;
}
}
However, my Java conversion is giving me errors, mainly because I do not think my nested conditionals have the right closed braces. Can you give me any hints or resources that can help me figure this out?
It's not good practice to have so many possible exit points. Also, if you don't want to reinvent the wheel, you can use Java library code, for example:
boolean isLeapYear(int year){
GregorianCalendar cal = new GregorianCalendar();
return cal.isLeapYear(year);
}
Your else statements need braces too, you forgot a return statement for the innermost if, and you misspelled yearr in one location:
boolean leapyear(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;
}
}
Java doesn't need the indentation like Python does, but it'd help make your branching structure more readable if you did use it anyway:
boolean leapyear(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;
}
}
You don't need as many return statements here, the year % 400 == 0 already evaluates to a boolean:
boolean leapyear(int year) {
if (year % 4 == 0) {
if (year % 100 == 0) {
return year % 400 == 0;
} else {
return true;
}
} else {
return false;
}
}
or as a one-liner:
boolean leapyear(int year) {
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
For completeness sake, here is the Python version the way I would write it:
def leapyear(year):
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
or better still, use calendar.isleap() instead.
What about removing the ifs altogether?
public boolean leapyear(int year) {
return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
}
heres my attempt:
boolean leapyear(int year)
{
if (year % 4 == 0)
{
if (year % 100 == 0)
{
return (year % 400 == 0);
}
else
{
return true
}
}
return false;
}
or use this:
return Java.util.GregorianCalendar.getInstance().isLeapYear(year)
boolean leapyear(int year)
{
if (year % 4==0)
{
if (year%100==0)
{
if (year%400==0)
{
return true;
}
else
{
return true;
}
}
else``
{
return false;
}
}
}

Multiple conditions in a while loop

import java.util.Calendar;
import java.util.GregorianCalendar;
public class CountingSundays {
public static void main(String args[]) {
Calendar cal = new GregorianCalendar(1901, 00, 01); // month set to 0for jan , 1= feb etc
while((cal.get(Calendar.YEAR) != 2001) && (cal.get(Calendar.MONTH) != 0) && cal.get(Calendar.DAY_OF_MONTH) != 1) { // while not 1/1/2001
System.out.print(cal.get(Calendar.MONTH));
// cal.add(Calendar.DAY_OF_MONTH, 1);
}
}
}
Im trying to iterate through the while loop by adding on a day at a time but it wont even access the while loop the first time. Are the conditions in the while loop right? When i tested it it worked with just one condition but stopped when i added the second condition.
It should be
while( !(cal.get(Calendar.YEAR) == 2001 && cal.get(Calendar.MONTH) == 0 && cal.get(Calendar.DAY_OF_MONTH) == 1) ) { // while not 1/1/2001
This is just a simple logic error. If even one of those is false (say, if the month IS 0), then you have true && false && true, which is false.
You need the "not" outside of the entire expression, or you need to use "||" to combine them:
while( !(year == 2001 && month == 0 && day == 1) )
or
while( (year != 2011) || (month != 0) || (day != 1) )

Javabat Help: alarmClock

I am working through the JavaBat questions and am confused about my logic.
Here's the task:
Given a day of the week encoded as 0=Sun, 1=Mon, 2=Tue, ...6=Sat, and
a boolean indicating if we are on vacation, return a string of the
form "7:00" indicating when the alarm clock should ring. Weekdays, the
alarm should be "7:00" and on the weekend it should be "10:00". Unless
we are on vacation -- then on weekdays it should be "10:00" and
weekends it should be "off".
alarmClock(1, false) → "7:00" alarmClock(5, false) → "7:00"
alarmClock(0, false) → "10:00"
Here's my code:
public String alarmClock(int day, boolean vacation) {
if ( (day >=1 && day <=5) && (!vacation)) {
return "7:00";
} else if ( (day >=1 && day <=5) && (vacation)) {
return "10:00";
} else {
return "off";
}
}
Why do these two tests fail?
alarmClock(0, false) → "10:00" "off" X
alarmClock(6, false) → "10:00" "off" X
Surely, this line covers it?
if (day >=1 && day <=5) && (!vacation))
how about this?
public String alarmClock(int day, boolean vacation) {
if (day >=1 && day <=5) {
return vacation ? "10:00" : "7:00";
} else {
return vacation ? "off" : "10:00";
}
}
Note it does depend if your coding convention allows the use of the turnary operator. But in this case I think the logic is easier to read.
Surely, this line covers it?
if ((day >=1 && day <=5) && (!vacation))
No, that line doesn't cover it. If the day is Sunday or Saturday (0 or 6), the first part of your "and" expression (day >=1 && day <=5) will be false, since 0 and 6 are not between 1 and 5 inclusive.
The only branch that handles days 0 and 6 is your else branch: "off".
This is a great time to use helper methods to express your logic closer to the English description:
if ( isWeekday(day) ) {
if ( vacation ) {
//what to return here?
} else {
//what to return here?
}
} else {
if ( vacation ) {
//what to return here?
} else {
//what to return here?
}
}
Then you just need to implement isWeekday:
private boolean isWeekday(int day) {
return /*fill this in*/;
}
Although the ternary operator is useful here, as this problem can be done in a single return statement, the following code below allows readability.
public String alarmClock(int day, boolean vacation) {
if(vacation){ //if we are on vacation
if(day > 0 && day < 6){ //if it is weekday and we are on vacation
return "10:00";
}
else return "off"; //it must be the weekend!
}
//from here on out all the cases where vacation is true have been weeded out
if(day > 0 && day < 6){
return "7:00";
}
else return "10:00";
}
if ((day == 0 || day == 6) && (!vacation) || (day >= 1 && day <= 5) && (vacation)) {
return "10:00";
}
if ((day >= 1 && day <= 5) && (!vacation)) {
return "7:00";
}
return "off";
public String alarmClock(int day, boolean vacation) {
if (((day==0)||(day==6))&&(!vacation)){
return "10:00";
}
else if (((day!=0)||(day!=6))&&(!vacation)){
return "7:00";
}
else if (((day==0)||(day==6))&&(vacation)){
return "off";
}
else{
return "10:00";
}
}

Categories