Nesting If Statements in Java - 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;
}
}
}

Related

Reverse loop TicTacToe

I've got loop:
for (int i = 0; i<3; i++){
System.out.println(i);
}
output:
0
1
2
I need to reverse this loop to output:
2
1
0
I need it because I work on TicTacToe Java game.
Here is my code for check win:
static boolean checkWin(char dot) {
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[i].length; j++) {
if (map[0][i] == dot && i == 2) {
return true;
}
if (map[1][i] == dot && i == 2) {
return true;
}
if (map[2][i] == dot && i == 2) {
return true;
}
if (map[i][0] == dot && i == 2) {
return true;
}
if (map[i][1] == dot && i == 2) {
return true;
}
if (map[i][2] == dot && i == 2) {
return true;
}
if (map[i][i] == dot && i == 2) {
return true;
}
if (map[i][0] == dot && i == 2) {
return true;
}
}
}
return false;
}
last thing that I need to refactor this method:
static boolean checkWin(char dot) {
if (map[0][0] == dot && map[0][1] == dot && map[0][2] == dot) {
return true;
}
if (map[1][0] == dot && map[1][1] == dot && map[1][2] == dot) {
return true;
}
if (map[2][0] == dot && map[2][1] == dot && map[2][2] == dot) {
return true;
}
if (map[0][0] == dot && map[1][0] == dot && map[2][0] == dot) {
return true;
}
if (map[0][1] == dot && map[1][1] == dot && map[2][1] == dot) {
return true;
}
if (map[0][2] == dot && map[1][2] == dot && map[2][2] == dot) {
return true;
}
if (map[0][0] == dot && map[1][1] == dot && map[2][2] == dot) {
return true;
}
if (map[0][2] == dot && map[1][1] == dot && map[2][0] == dot) {
return true;
}
return false;
}
}
I almost done it.
Last thing that i need refactor this part of code:
if (map[0][2] == dot && map[1][1] == dot && map[2][0] == dot) {
return true;
}
to something like
if (map[i][0] == dot && i == 2) {
return true;
}
Main question is here:
for (int i = 0; i<3; i++){
System.out.println(i);
}
output:
0
1
2
I need to reverse this loop to output:
2
1
0
to feel this last part:
if (map[i][0] == dot && i == 2) {
return true;
}
i need to feel this last condition with values 2 1 0
if (map[i][insert here] == dot && i == 2) {
return true;
}
Please Help.
If all you want to do is reverse the loop output, you can just invert what you're doing in the for loop
for (int i = 2; i>=0; i--){
System.out.println(i);
}
output:
2
1
0
As a quick example.

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);

print a leap year in a certain format

i would like to print leap years in between two years given in a format like
'[2120,2024,2028]'.i want them with these commas and square brackets..kindly help me with this.in java
my program:
System.out.print("[");
for(int i=2017;i<=2040;i++)
{
if(i%4==0)
{
System.out.print(i);
if(i!=2040)
{
System.out.print(",");
}
}
}
System.out.print("]");
if i change the value the comma is not working right
It is easier to put a comma before each number and not after. The effect is the same, but then you just need to make the first leap year a special case:
System.out.print("[");
boolean isFirstLeapYear = true;
for (int i=2017;i<=2040;i++) {
if (i%4 == 0 && (i%100 != 0 || i%400 == 0)) {
if (isFirstLeapYear) {
isFirstLeapYear = false;
} else {
System.out.print(",");
}
System.out.print(i);
}
}
System.out.print("]");
There is more rules about leap year.
I suggest you to study this method and use it in your code:
boolean isLeapYear(year) {
if (year % 400 == 0) {
return true;
} else {
if ((year % 4 == 0) && (year % 100 != 0)) {
return true;
} else {
return false;
}
}
}

Calling a method from another method (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));
}
}

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