Test an int variable with a boolean in Java - java

I am still learning Java and am stuck and getting errors. Can someone help with a solution of how the best way to do this would be.
import java.util.Scanner;
public class LeapYear2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int year;
year = scan.nextInt();
boolean boolVar1,boolVar2,boolVar3;
boolVar1 = (year / 4);
boolVar2 = (year / 100);
boolVar3 = (year / 400);
if (boolVar1 == true && boolVar2 == true && boolVar3 == true)
{
System.out.println("This is a leap year.");
}
else if (boolVar1 == true && boolVar2 == true && boolVar3 != true)
{
System.out.println("This is not a leap year.");
}
else if (boolVar1 == true)
{
System.out.println("This is a leap year.");
}
else
{
System.out.println("This is not a leap year.");
}
}
}

If you want to know whether an int value is evenly divisible by another, you can do this:
boolVar1 = year % 4 == 0;
boolVar2 = year % 100 == 0;
boolVar3 = year % 400 == 0;
In Java, integer and boolean values are not interchangeable (unlike languages like C where 0 is false and any non-zero value is considered true). You need to use a comparison operator like ==. The % operator is the remainder function, which (from the rest of your code) looks like what you want to be using.
P.S. In the future, when you are asking about how to deal with errors, it would be very helpful if you posted the error message(s) in your question.
P.P.S. You should get in the habit of giving your variables meaningful names. For example, I would replace boolVar1 with divisibleBy4, etc. This will save you lots of headaches when you start writing more complex code.
Also, as others have pointed out, with a boolean variable b, recommended Java style is to use
if (...b...)
instead of
if (...b == true...)
and
if (...!b...)
instead of
if (...b == false...)

You need an explicit comparison to make an expression boolean. You do not need an explicit comparison with true on booleans, so the code should be as follows:
boolean boolVar1,boolVar2,boolVar3;
boolVar1 = (year % 4) == 0;
boolVar2 = (year % 100) == 0;
boolVar3 = (year % 400) == 0;
if (boolVar1 && boolVar2 && boolVar3)
{
System.out.println("This is a leap year.");
}
else if (boolVar1 && boolVar2 && !boolVar3)
{
System.out.println("This is not a leap year.");
}
else if (boolVar1)
{
System.out.println("This is a leap year.");
}
else
{
System.out.println("This is not a leap year.");
}
Note that boolVar != true and boolVar == false is equivalent to !boolVar.

use the modulo method for this.
if(year % 4 == 0){
System.out.println("This is a leap year.");
}
and so on. From what I can see you do not need to declare 3 separate int types for this. Just reuse this in each conditional statement.

You do not need all those booleans. You can simply test:
if ((year % 4 == 0) && (year % 100 != 0)){
System.out.println(year + " is a leap year.");
}
else if (year % 400 == 0){
System.out.println(year + " is a leap year.");
}
else {
System.out.println(year + " is not a leap year.");
}

rather than calculating so many conditions just put the following code
if(year%4==0)
System.out.println("The given year is leap year");
else
System.out.println("The given year is not leap year");
There is no situation where you stuck up between int value and boolean.

Use this code
boolVar1 = (year % 4) == 0;
boolVar2 = (year % 100) ==0;
boolVar3 = (year % 400) == 0;
Note that the original version would have worked in C.

Related

My validation with true/false statements is not working properly

so i have a problem validating the last section of this code where i have commented
public void newTicket() throws Exception {
boolean validation = false;
boolean phoneUnique = false;
int num;
int member;
String memberPhoneNum;
final int memTicket = 80;
final int nonMem = 100;
int min = 100;
int max = 200;
int random_int = (int) Math.floor(Math.random() * (max - min + 1) + min);
int dd;
int mm;
int yy;
String ticketDate;
boolean isTrueDate = true;
System.out.println();
System.out.println("Transaction Id: " + random_int);
int transactionId = random_int;
do {
System.out.print("Enter Day: ");
dd = scan.nextInt();
System.out.print("Enter Month");
mm = scan.nextInt();
System.out.print("Enter Year");
yy = scan.nextInt();
ticketDate = (dd + "" + mm + "" + yy);
System.out.println("Ticket date: " + ticketDate);
validation = v.checkDate(ticketDate);
if (!isTrueDate) {
System.out.println("Invalid"); // PROBLEM WITH VALIDATION
}
} while (!isTrueDate);
Whenever i enter a wrong date, for example: 300224, it still proceeds to the next line. ive tried changing the true/false statements but it still does work how i want it to.
public static boolean checkDate(String ticketDate) {
boolean isTrueDate = true;
int day = 0;
int month = 0;
int year = 0;
if (month > 12) {
isTrueDate = false;
} else if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
if (day <= 31) {
isTrueDate = true;
} else if (day >= 31) {
isTrueDate = false;
}
} else if (month == 4 || month == 6 || month == 9 || month == 11) {
if (day <= 30) {
isTrueDate = true;
} else if (day >= 30) {
isTrueDate = false;
}
} else if (month == 2) // February check
{
if (year % 4 == 0) // Leap year check for February
{
if (day <= 29) {
isTrueDate = true;
} else if (day >= 29) {
isTrueDate = false;
}
} else if (year % 4 != 0) {
if (day <= 28) {
isTrueDate = true;
} else if (day >= 28) {
isTrueDate = false;
}
}
}
return isTrueDate;
This is my validation class to test for leap years and whatnot
I appreciate any help given
I am new to this site too, but I can try to give you a response that may help.
This is going to be a long one, as I have a lot of potential issues to solve. I will provide something that I think could work at the end though.
The first thing I noticed is that your long series of conditionals involves a lot of brackets and you may have missed one as you nested many of them into each other. I did a thorough check and really, the only one I did not see was the one that should end the boolean method after return isTrueDate; so I thought I should mention it just in case. To be clear, you probably have it, but make sure you have a bracket that closes the method. Also in the future, make sure to put the whole code snippet for clarity. Thanks in advance.
Now the second thing I see is the way you got the validation. I do not know exactly what you mean when you say validation = v.checkDate(ticketDate); in the first code snippet because I do not know what v is, although I will assume it is the main class. In this case, while I am not sure, it looks like you are trying to run your method and assign the boolean value of whether the date is a real date to the value of validation. This makes sense, but what I think you should change is how you used isTrueDate to verify by asking if the value is not isTrueDate. I think it might solve an issue if you simply put an invalid response on validation being false and vice versa for validation being true. Here's an example:
validation = v.checkDate(ticketDate);
if (validation == true) {
//Something here if you want.
//However you may not need this space.
} else {
System.out.println("invalid")
}
However, with this, there are really two approaches that I can think of: the one that preserves security and the one that ensures your code is working.
So the code above is better at preserving security b/c it accounts for anything that may not make the validation false in the else statement in addition to it being false because your code worked properly. For example, if your series of conditionals has a flaw in it, b/c you initialized validation as being false, if something goes wrong, its likely to just invalidate the ticket, which could be semi-useful in a security sense to avoid some vulnerabilities. However, you can do that later. The first thing you need to make sure of is that your code works properly, so I would also recommend that when you declare validate at the top of your first code snippet, to not initialize it.
Like this:
boolean validation;
Instead of this:
boolean validation = false;
This ensures that your series of conditionals is responsible for the value of validation rather than the conditions simply not working and the value being false by default.
This brings me to another thing that I believe would also cause problems in your code.
It refers to this section from your first code snippet:
boolean isTrueDate = true;
System.out.println();
System.out.println("Transaction Id: " + random_int);
int transactionId = random_int;
So two things:
The easy one refers to the bottom two lines. It's not a mistake causing you errors, but I would suggest switching the order of the bottom two lines to assign transactionId to the value of random_int and then printing:
System.out.println("Transaction Id: " + transactionId);
Now the second one is the real problem. In the code above you are assigning true to isTrueDate.
This is a problem because you are later using isTrueDate in that series of conditionals in that other boolean method called checkDate()
This will mess up your code. Here is how:
So first the isTrueDate you used inside your method, checkDate() is kept local to that method because you declared it inside there. If you did not do this, you likely would have gotten a separate error because you declared a boolean isTrueDate in two separate places. You declared it at the top in that first code snippet, and you declared it in that method. Normally, this would cause an error because you have already declared it once and changing the value would only require you to assign isTrueDate to something else with an equal sign rather than declaring it again. To really show you what I mean, look at this example:
Incorrect:
boolean isTrueDate = true;
//Other actions
//I want to change the value of isTrueDate
boolean isTrueDate = false;
Correct:
boolean isTrueDate = true;
//Other actions
//I want to change the value of isTrueDate
isTrueDate = false;
What you did (doesn't return error but messes up your code):
I put it in a different order to better show the problem.
public static boolean checkDate(String ticketDate) {
boolean isTrueDate = true; //first declaration
//Lots of conditions
}
static void someMethod() {
//This method may not be exactly how you did it,
//but you did not show me that.
boolean isTrueDate = true; //usually invalid second declaration.
//However, it still works b/c they are in different methods and
// thus kept separate from each other. This still messes up your
// code though
//more code
validation = v.checkDate(ticketDate);
if (!isTrueDate) {
System.out.println("Invalid");
}
//Doesn't work b/c the value of isTrueDate you initialized
// in someMethod() is the one that this if else statement checks
// instead of the one that you used in checkDate()
//That means, isTrueDate will always be true.
//To solve this, you must first use validation to present the
// invalid message as discussed above, but furthermore, you should
// delete the initialization of isTrueDate in the method that is
// not checkDate() because you don't need it there.
}
Sorry, that's a lot to explain, and there may be more to fix, but I have one more correction for now: I looked through the conditionals that you used to account for all the ways a date could be correct or incorrect and I think its pretty good for the most part, but I can offer one thing that will save you some lines.
Every time you check if a date is within the max number of days for that month, you then put a separate else if condition that accounts for the other of the two possibilities. Here's an example from your code:
if (day <= 31) {
isTrueDate = true;
} else if (day >= 31) {
isTrueDate = false;
}
This does help to show exactly what is happening, but I would still advise deleting this else if part and replacing it with one big else {} part at the end because it would say the same thing as all of these other separate else if blocks, just much more concisely. Here is what that would look like:
//This new list of conditions will work such that it finds every true
// possibility and denies everything else.
if (month < 12) //Changed to fit new strategy
{
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)
{
if (day <= 31)
{
isTrueDate = true;
}
} else if (month == 4 || month == 6 || month == 9 || month == 11)
{
if (day <= 30)
{
isTrueDate = true;
}
} else if (month == 2) // February check
{
if (year % 4 == 0) // Leap year check for February
{
if (day <= 29)
{
isTrueDate = true;
}
} else if (year % 4 != 0)
{
if (day <= 28)
{
isTrueDate = true;
}
}
}
} else { // All the times it was false
isTrueDate = false;
}
return isTrueDate;
So there you have it. As thorough as I could because in truth, this is my first answered question and I wanted to do it right. I hope it helps in some way. The main thing is to make sure that the data you received from the scanner correctly enters into the method and that the right data from that method goes to your validation. I'll leave you with everything I can think to correct on both snippets.
New Snippet 1:
public void newTicket() throws Exception {
boolean validation;
boolean phoneUnique = false;
int num;
int member;
String memberPhoneNum;
final int memTicket = 80;
final int nonMem = 100;
int min = 100;
int max = 200;
int random_int = (int) Math.floor(Math.random() * (max - min + 1) + min);
int dd;
int mm;
int yy;
String ticketDate;
//Removed unnecessary declaration of isTrueDate in this part
System.out.println(); //I don't know why you have this but I will leave it alone.
int transactionId = random_int; //Switched
System.out.println("Transaction Id: " + transactionId);
do { // I like this part
System.out.print("Enter Day: ");
dd = scan.nextInt();
System.out.print("Enter Month");
mm = scan.nextInt();
System.out.print("Enter Year");
yy = scan.nextInt();
ticketDate = (dd + "" + mm + "" + yy);
System.out.println("Ticket date: " + ticketDate);
validation = v.checkDate(dd, mm, yy); //This change is explained in snippet 2
if (validation == false) { //uses validation instead of isTrueDate
System.out.println("Invalid"); // Hopefully this helps
}
} while (!isTrueDate); //I don't know what happens here so I won't touch.
//Code that was not shown
New Snippet 2:
//parameters changed
public static boolean checkDate(int day, int month, int year) {
boolean isTrueDate; //Changed out of preference
//int day = 0;
//int month = 0; No longer needed in this new code.
//int year = 0;
//One more problem:
//It looks like you tried to use ticketDate as the parameter
// to get the values for days, month, and year, but this
// doesn't quite work b/c there is not anything that takes that
// string and then extracts the values for day, month and year.
//The way I chose to address this was by placing the day, month,
// and year as parameters in the checkDate() method, and then
// calling checkDate() in snippet one with the values of the
// scanner.
//However, there are other ways to do this. For example, you could
// keep your ticketDate String and then access different parts of
// that String to get the values of day, month, and year.
//In the end, I just did what seemed easiest to me.
//This new list of conditions will work such that it finds every true
// possibility and denies everything else.
if (month < 12) //Changed to fit new strategy
{
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)
{
if (day <= 31)
{
isTrueDate = true;
}
} else if (month == 4 || month == 6 || month == 9 || month == 11)
{
if (day <= 30)
{
isTrueDate = true;
}
} else if (month == 2) // February check
{
if (year % 4 == 0) // Leap year check for February
{
if (day <= 29)
{
isTrueDate = true;
}
} else if (year % 4 != 0)
{
if (day <= 28)
{
isTrueDate = true;
}
}
}
} else { // All the times it was false
isTrueDate = false;
}
return isTrueDate;
} //The extra bracket! Closes the method
Peace <3

Calculate Leap Year in Java is bypassing an else statement

There must be a bug somewhere in my 30 lines of code but I cannot find it and it's driving me nuts.
If I execute this code using isLeapYear(2004) I receive a true:
public class LeapYear {
public static void main(String[] args) {
isLeapYear(2004);
}
public static boolean isLeapYear (int year) {
boolean status = true;
if (year >= 0 || year <= 9999) {
if (year % 4 == 0){
status = true;
System.out.println("true");
} else if (year % 100 == 0){
status = true;
System.out.println("true");
} else if (year % 400 == 0) {
status = true;
System.out.println("true");
} else {
status = false;
System.out.println("false");
}
} else if (year < 0 || year > 9999){
status = false;
System.out.println("false");
}
return status;
}
}
But if I run it for isLeapYear(-1200) it returns me a true as well but it shouldn't.
Why is my code bypassing else if (year < 0 || year > 9999) ?
you just have to change your first if statement to :
if (year >= 0 && year <= 9999) {
-1200 was always lower than 9999 so it was always going through this condition because of the ||.

Repeating code for leap year

I already know how to check for a leap year, like this:
import java.util.*;
public class LeapYear {
public static void main(String[] args) {
int year;
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter year: ");
year = scan.nextInt();
if ((year % 4 == 0) && year % 100 != 0) {
System.out.println(year + " is a leap year.");
} else if ((year % 4 == 0) && (year % 100 == 0)
&& (year % 400 == 0)) {
System.out.println(year + " is a leap year.");
} else {
System.out.println(year + " is not a leap year.");
}
}
}
}
But now I want to repeat this code. I've seen repeating code snippets before, and I can use just about any successfully, but this one is giving me trouble.
import java.util.Scanner;
public class LeapUpgrade
{
public static void main(String[] args)
{
String another = "y";
int year;
Scanner scan = new Scanner(System.in);
while (another.equalsIgnoreCase("y"))
{
System.out.println("Enter year: ");
year = scan.nextInt();
if ((year % 4 == 0) && year % 100 != 0)
{
System.out.println(year + " is a leap year.");
System.out.print("test another (y/n)? ");
another = scan.nextLine();
}
else if ((year % 4 == 0) && (year % 100 == 0)
&& (year % 400 == 0))
{
System.out.println(year + " is a leap year.");
System.out.print("test another (y/n)? ");
another = scan.nextLine();
}
else
{
System.out.println(year + " is not a leap year.");
System.out.print("test another (y/n)? ");
another = scan.nextLine();
}
}
}
}
What am I doing wrong here?
Thanks in advance for your help and don't judge.
To avoid repetition, just encapsulate the lines of code in a method
public static boolean isLeapYear(int year){
return (year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0);
}
You can then call it like this
if(LeapYear.isLeapYear(year)){
System.out.println("Leap year");
}else{
System.out.println("Not a leap year");
}
EDIT: See Rohan's answer. It's better for the sake of modularity and cleanliness/readability of code.
When you want to do something multiple times you typically just need a loop. As a hint, your loop should enclose this part of your code:
year = scan.nextInt();
if ((year % 4 == 0) && year % 100 != 0) {
System.out.println(year + " is a leap year.");
} else if ((year % 4 == 0) && (year % 100 == 0) && (year % 400 == 0)) {
System.out.println(year + " is a leap year.");
} else {
System.out.println(year + " is not a leap year.");
}
I'll leave the type of loop and conditions to you.

Program won't return String

So I've been assigned a problem in my intro to programming class. I did a little research into a way to accomplish this problem and I am able to compile with no errors however one of the stipulations is that I must return a String. This is where I run my head into a brick wall. I've tried a few means to fix the issue but I'm hoping someone here can spot the issue that I've been pulling my hair out over.
public class TellSeason {
public static void main(String[] args) {
season(5 , 12);
}
public static String season(int month , int day) {
if ((month == 9 && day >=16)
|| month == 10
|| month == 11
|| (month == 12 && day <=15)) {
return ("Fall");
}
else if ((month == 12 && day >=16)
|| month == 1
|| month == 2
||(month == 3 && day <=15)) {
return ("Winter");
}
else if ((month == 3 && day >=16)
|| month == 4
|| month == 5
||(month == 6 && day <=15)) {
return ("Spring");
}
else {
return("Summer");
}
}
}
Something like this?
public static void main(String[] args){
System.out.println(season(5 , 12));
}
One more hint - you can compare month and day together
int idx = month * 100 + day;
if (idx <= 315 || idx >= 1216)
return ("Winter");
if (idx >= 916)
return ("Fall");
if (idx >= 616)
return("Summer");
//if (idx >= 316)
return ("Spring");
Two things, first you are not doing anything with the result of your method. Basically, you just call season in your main method, and do nothing with the result.
Secondly, look at the method signature of your main method. It explicitly states that main have the return type void. Which means, this method can't return anything. You can provide a exit code, by using System.exit(), however, this is limited to integer return codes.
I strongly suspect that all you are really after, is the ability to print your result to the console. That is,
System.out.println(season(5,12));
If you want to return anything from your main, it is impossible.
But if you want to display your result, System.out.println is your method

Why does my program only outputs one result instead five?

/*
*Find if a year is leap or not
*/
public class LeapYear{
private static int leapYear;
public void setLeapYear(int leapYear){
this.leapYear = leapYear;
}// end method
public static void main (String[] args) {
LeapYear leap = new LeapYear();
leap.setLeapYear(2010);
leap.setLeapYear(2008);
leap.setLeapYear(1900);
leap.setLeapYear(2000);
leap.setLeapYear(1565);
// Is it Divisible by 4?
if (leapYear % 4 == 0) {
// Is it Divisible by 4 but not 100?
if (leapYear % 100 != 0) {
System.out.println(leapYear + ": is a leap year.");
}
// Is it Divisible by 4 and 100 and 400?
else if (leapYear % 400 == 0) {
System.out.println(leapYear + ": is a leap year.");
}
// It is Divisible by 4 and 100 but not 400!
else {
System.out.println(leapYear + ": is not a leap year.");
}
}
// It is not divisible by 4.
else {
System.out.println(leapYear + ": is not a leap year.");
}
}
}
I am new to Java and I wrote this code so that it would call for all five years into the boolean and generate answers for all of them. However it only calls the last one. How would I do this right?
Problem 1
The four first calls to setLeapYear:
leap.setLeapYear(2010); // leap.leapYear = 2010;
leap.setLeapYear(2008); // leap.leapYear = 2008;
leap.setLeapYear(1900); // leap.leapYear = 1900;
leap.setLeapYear(2000); // leap.leapYear = 2000;
gets overridden by the last one:
leap.setLeapYear(1565); // leap.leapYear = 1565;
I would probably write a boolean method called something like isLeapYear(int year) and do
System.out.println(isLeapYear(2010));
System.out.println(isLeapYear(2008));
...
Problem 2
leapYear is static, so you don't need to / shouldn't do LeapYear leap = new LeapYear(); (alternatively, you should drop the static modifier).
You need use separate object for each year or at least call the Leap Year checking method as soon as you crated the object for that year.
What you have is a series of call to a function that assigns a value to an attribute of the same object. Therefore, only the last statement has the effect as previous values are overwritten.
On additional note, your code doesn't seem to be properly organized. Whey do you make the checkings in Main and it seems that leapYear isn't defined anywhere.
Perhaps, you may want to define a function that returns true/false depending on the value of the passed parameter or the value of the year stored in object.
The code may look something like this:
leap.setLeapYear(2010); // leap.leapYear = 2010;
System.out.println(leap.isLeapYear());
leap.setLeapYear(2008); // leap.leapYear = 2008;
System.out.println(leap.isLeapYear());
leap.setLeapYear(1900); // leap.leapYear = 1900;
System.out.println(leap.isLeapYear());
leap.setLeapYear(2000);
System.out.println(leap.isLeapYear());
leap.setLeapYear(1565);
System.out.println(leap.isLeapYear());
You have to define isLeapYear() by moving the checks in main to that function.
I would be inclined to write the tests in your if statements in order from 400 to 4:
String result;
if (year % 400 == 0) {
result = "is a leap year.";
} else if (year % 100 == 0) {
result = "is not a leap year.";
} else if (year % 4 == 0) {
result = "is a leap year.";
} else {
result = "is not a leap year.";
}
System.out.println(year + ": " + result);

Categories