Program won't return String - java

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

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

Is there a || operator for int?

I am trying to write a method that takes a single int parameter that is the numeric month and returns the number of days in the given month. So, a parameter of 1 would return 31 since there are 31 days in January and a parameter of 2 would return 28 since there are 28 days in February.
Here's what I have so far:
public static void daysInMonth(int month) {
if (month == 1||3||5||7||8||10||12)
System.out.println("31");
else if (month == 4||6||9||11)
System.out.println("30");
else if (month == 2)
System.out.println("28");
I keep getting the error message "operator || cannot be applied to boolean,int." Can anyone help me figure out what to do?
You want something like this:
if ( (month == 1) || (month == 3) || (month == 5) || (month == 7)
|| (month == 8) || (month == 10)
You can avoid any switch or if/else statements with the new Java 1.8 time API using java.time.Month:
public static int daysInMonth(int month) {
return Month.of(month).minLength();
}
You can use the || operator on a boolean expression :
if (month == 1 || month == 3 || month == 5) {
// do something ...
}
|| will result into boolean and then boolean || int is not valid action
what you need is
month == 1 || month == 3 || ...
or a Map<Integer, Integer> monthNumberToMaxDaysMap
also this way you don't have leap year scenario covered, it is suitable to re-use already solved problem
public static void daysInMonth(int month) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, month -1);
return cal.getActualMaximum(Calendar.DAY_OF_MONTH)
}
above method only considers current year, you could leverage it to pass year as well

Need help method calling program - day number in year

basically I am in the middle of my program that involves asking a user to enter a day,month, and year, and based on that entry I am supposed to create a method that calculates the number of days in the year, but of course I need a method that defines how many days are in each month, and a method that determines whether or not it is a leap year or not. I have established my methods, user input, but now I am having method/return issue. Here is what I have so far:
import java.util.Scanner;
public class DayNumber{
public static void main(String[] args){
int year;
int month;
int day;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the date's year (0001 - 9999): ");
year = keyboard.nextInt();
System.out.print("Enter the date's month (1 - 12): ");
month = keyboard.nextInt();
System.out.print("Enter the date's day (1 - 31): ");
day = keyboard.nextInt();
}
public static int numberOfDays(int day, int month, int year){
int numberOfDays;
return numberOfDays;
}
public static int daysInMonth(int month, int year){
int daysInMonth;
if (month ==1 || month==3 || month==5 || month==7 || month==8 ||
month==10 || month==12){
month = 31;}
if (month ==4 || month ==6 || month==9|| month==11){
month = 30;}
else if (month ==2){
if (){
}
}
return daysInMonth;
}
public static boolean isLeapYear(int year){
if (((year%4 == 0) && (year%100 != 0)) || (year%400 ==0)){
return true;
}
else{
return false;
}
}
}
I would appreciate any advice or tips. I am really new to Java so go ahead and critique away! Thanks.
There are several different ways. Yours looks fine to me.
But my favorite is this tiny little line :
daysInMonth = (month === 2) ? (28 + isLeapYear) : 31 - (month - 1) % 7 % 2;
If you are asking yourself : Why % 7 % 2 ?
Well, you have noticed that starting from august, the pattern is reverted, that's what we are doing here. We say that between 0 - 6 it's normal then if it's 7 (7 % 7 = 0) we are going back from the beggining). Then the % 2 is to alternate between 0 - 1.
Hope I made myself clear
Although your question is not clear. I tried to understand and here is my understanding:
Input date
Display number of days in month
Display whether year is leap year or not
Here is what I will do
Class MyDateHomework {
public static boolean isLeapYear(int year) {
//put logic to find leapyear
}
public static int daysInMonth(int month, int year) {
if(month == 2) {
return isLeapYear(year) ? 28 : 29;
}
//put logic to find days in month
}
public static void main(String[] args) {
//take input and call method to do homework
}
}

Test an int variable with a boolean in 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.

if-else-else if

I am a beginner in java and i am doing some practiceit questions to brush up on my java skills.
Write a method named season that takes two integers as parameters representing a month and day and that returns a String indicating the season for that month and day. Assume that months are specified as an integer between 1 and 12 (1 for January, 2 for February, and so on) and that the day of the month is a number between 1 and 31.
If the date falls between 12/16 and 3/15, you should return "Winter". If the date falls between 3/16 and 6/15, you should return "Spring". If the date falls between 6/16 and 9/15, you should return "Summer". And if the date falls between 9/16 and 12/15, you should return "Fall".
public static String season(int month,int day){
   
    if(month>=9 && month<=12 && day==15||day==16){
        return "Fall";
    }
    else if (month>=4 && month<=6 && day==16||day==15){
       return "Spring";
     }
    else if (month>=6 && month<=9 && day==16||day==15){
         return "Summer";
     }
     else {
          return"Winter";
         
      }
  
}
But i'm not getting the output.But it seems right to me.Anyone can tell me where did i go wrong?
|| has lower precendence than && and your conditions don't look correct - you probably wanted to write something like:
if((month == 9 && day >= 16) //September, on or after the 16th
|| month == 10 //or October
|| month == 11 //or November
|| (month == 12 && day <=15)) { //or December, but before or on the 15th
return "Fall";
}
(same comment for the other conditions)
You could make it shorter by using a little hack, but readability is maybe not as good (debatable):
int mdd = month * 100 + day; //date in MDD format, for example 507 for May 7th
if (mdd >= 916 && mdd <= 1215) {
return "Fall";
}
You should try to write something like this:
if((month>9 && month<12) || (month==9 && day>=16) || (month==12 && day<=15)){
return "Fall";
} else if
...
}
The precedences are important, also, but you have to think over what you really want to achieve, and build your expression according to that.
if(month>=9 && month<=12 && (day==15||day==16)){
return "Fall";
}
This issue with this is that only the 15th and 16th of months 9-12 are considered the winter.
Solution
If it were up to me, I would re-factor the if-else tree to first check for months, then check the days. So for example:
if(month>=9 && month<=12)
{
// Some special cases.
if((month == 9 && day < 15) || (month == 12 && day > 16))
{
// It isn't fall.
}
else
{
// It is fall.
}
}
This runs just fine. You had some minow mistakes I corrected
public static String season(int month,int day){
if((month>=9 && month<=12) && (day==15||day==16))
return "Fall";
else{
if ((month>=4 && month<=6) && (day==16||day==15))
return "Spring";
else{
if ((month>=6 && month<=9) && (day==16||day==15))
return "Summer";
else
return"Winter";
}
}
}

Categories