This question already has answers here:
Java variable scope in if statement [duplicate]
(5 answers)
Closed 5 years ago.
I was attempting to code a program that gives you the season based on an inputed month and day, but ran into a problem halfway through. After I intialize the variable month in an if statement, to check if the value inputed is a valid month, I cannot use the variable month later in the code to find the season as it gives me the error "cannot find symbol." Any help would be much appreciated.
import java.util.Scanner;
public class Date
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Please enter the number of the month: ");
if (in.hasNextInt() && in.nextInt() > 0 && in.nextInt() <= 12)
{
int month = in.nextInt();
}
else
{
System.out.println("Error: Invlaid month value");
}
System.out.println("Please enter the day: ");
int day = in.nextInt();
String season;
if (0 < month && month <= 3)
{
season = "Winter";
}
else if (3 < month && month <= 6)
{
season = "Spring";
}
else if (6 < month && month <= 9)
{
season = "Summer";
}
else if (9 < month && month <= 12)
{
season = "Fall";
}
}
}
The problem you encounter is that you have declared the variable within the if statement, meaning it may only be accessed within the { }. This article goes over the basics of variable scope in Java. You will only be able to access a variable from a scope if the variable was defined in a scope that is a subset of the current scope.
To achieve what you want, you will need to declare the variable outside the if-statement so that it can be accessible. Note you will need to handle the case when month is invalid otherwise you will have the default value of 0.
int month = 0;
if (in.hasNextInt()) {
month = in.nextInt();
if (!(month > 0 && month <= 12)) {
month = 0;
System.out.println("ERROR");
}
} else {
// Handle graceful exit
}
...
if (0 < month && month <= 3) { ... }
Related
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
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
}
}
This question already has answers here:
Variables might not have been initialized
(3 answers)
Closed 8 years ago.
Doing some Java practice at home and I keep getting an error with this code.
I want to make a program which tells the season of a month that has been entered (in numerical form) but if the number is greater than 12, it should tell us that the month entered is invalid.
import java.util.Scanner;
class SeasonInput {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a month (in numbered form)");
String monthentered = input.nextLine();
int month = Integer.valueOf(monthentered);
String season;
if(month <13) {
if(month == 12 || month == 1 || month == 2)
season = "Winter";
else if(month == 3 || month == 4 || month == 5)
season = "Spring";
else if(month == 6 || month == 7 || month == 8)
season = "Summer";
else if(month == 9 || month == 10 || month == 11)
season = "Autumn";
System.out.println("The season that occurs during that month is " + season);
}
else
System.out.println("Enter a valid month");
}
}
It's a valid error, in your last else you don't set String season.
String season = null; // <-- give it a null. the error will go away.
You have cases where you don't initialize season.
This is what the compiler is complaining about.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last year.
Improve this question
For some reason I get a syntax error that says, "Syntax error, insert "}" to complete ClassBody." I checked every method, every statement to make sure I have complete opening and closing brackets, so I don't know why this is happening. Can anybody tell me why I might be getting this issue?
Copying the code into another file doesn't fix the problem, nor does going to Project > Clean.
import java.util.Scanner;
public class jloneman_Numerology
{
private String[] report;
private int day, month, year, num;
public jloneman_Numerology()
{
introduction();
report = new String[9];
num = 0;
}
public void introduction()
{
System.out.println("Welcome to ACME Numerology Reports! We will " +
"determine your special\nnumerology report based on your " +
"birth date.\n");
}
public void getDate()
{
char slash1, slash2;
do
{
System.out.print("Please enter your birth date (mm / dd / yyyy): ");
Scanner in = new Scanner(System.in);
String date = in.nextLine();
month = in.nextInt();
day = in.nextInt();
year = in.nextInt();
slash1 = date.charAt(3);
slash2 = date.charAt(8);
} while (validDate(slash1, slash2) == false);
calcNum();
}
public boolean validDate(char slash1, char slash2)
{
boolean isValid = true;
// Check for valid month
if (month < 1 || month > 12)
{
isValid = false;
System.out.printf("Invalid month: %d\n", month);
}
// Check for valid day
if (day < 1 || day > 31)
{
isValid = false;
System.out.printf("Invalid day: %d\n", day);
}
// Check for months with 30 days, else 31 days = invalid
if ((month == 4 || month == 6 || month == 9 || month == 11) && (day < 1 || day > 30))
{
isValid = false;
System.out.printf("Invalid day: %d\n", day);
}
else if (day < 1 || day > 31)
{
isValid = false;
System.out.printf("Invalid day: %d\n", day);
}
// Check for valid year
if (year < 1880 || year > 2280)
{
isValid = false;
System.out.println("Please enter a valid year between 1880 and 2280.");
}
// Check for correct separating character
if (slash1 != '/' || slash2 != '/')
{
isValid = false;
System.out.println("Invalid separating character, please use forward slashes");
}
if (leapYear() == true)
{
if (month == 2 && day > 29)
{
isValid = false;
System.out.printf("Invalid day for 2/%d: %d", year, day);
}
}
return isValid;
}
public boolean leapYear()
{
boolean isLeap;
if (year % 4 == 0 && year % 400 != 0)
isLeap = false;
else
isLeap = true;
return isLeap;
}
public void calcNum()
{
// Separate each digit of the date and add to a single number
// Test number for debugging
num = 5;
}
public void printReport()
{
report[0] = ":1: ";
report[1] = ":2: ";
report[2] = ":3: ";
report[3] = ":4: ";
report[4] = ":5: ";
report[5] = ":6: ";
report[6] = ":7: ";
report[7] = ":8: ";
report[8] = ":9: ";
System.out.println(report[num]);
}
}
78,0-1 Bot
Try removing (or commenting out) one method and see if the problem persists. If it does, remove or comment out an additional method, and so on, until the error disappears. Then restore everything but the last method.
If the error doesn't reappear, the problem is probably in that last method.
If it does reappear, the problem is more subtle; perhaps a control character embedded in the code. Try copying and pasting the code into a text-only editor (so any control characters will be ignored, save it, and recompiling.
I too had this error.
There are NO errors in the code above (when I used the code above as as a sub class).
I corrected my error by cleaning up my IDE's workspace and making sure the caller was working properly.
Project settings
Run settings
Made sure that main was listed properly
public static void main(String[] args) { ... }
I have faced the similar problem, solved it by deleting the class file and then recreated the file again and pasted the same code. It worked.
Take out the System.out.println and put it into the main function instead of the introduction() inside of the main(String[] args).
so i'm asking the user for a month and a year. month has to be one of the twelve months and year has to be a number and no letters. i'm trying to figure out the best way to make the program say "wrong input, try again" and prompt them for input again. here's the section of code i'm working with for the month section.
public class MonthLength {
public static void main(String[] args) {
int month = 0;
// Prompt the user to enter a month
SimpleIO.prompt("Enter a month name: ");
String userInput = SimpleIO.readLine();
if (userInput.trim().toLowerCase().equals("january")) {
month = 1;
} else if (userInput.trim().toLowerCase().equals("february")) {
month = 2;
} else if (userInput.trim().toLowerCase().equals("march")) {
month = 3;
} else if (userInput.trim().toLowerCase().equals("april")) {
month = 4;
} else if (userInput.trim().toLowerCase().equals("may")) {
month = 5;
} else if (userInput.trim().toLowerCase().equals("june")) {
month = 6;
} else if (userInput.trim().toLowerCase().equals("july")) {
month = 7;
} else if (userInput.trim().toLowerCase().equals("august")) {
month = 8;
} else if (userInput.trim().toLowerCase().equals("september")) {
month = 9;
} else if (userInput.trim().toLowerCase().equals("october")) {
month = 10;
} else if (userInput.trim().toLowerCase().equals("november")) {
month = 11;
} else if (userInput.trim().toLowerCase().equals("december")) {
month = 12;
}
// Terminate program if month is not a proper month name
if (month < 1 || month > 12) {
System.out.println("Illegal month name; try again");
return;
}
and here's what i'm working with for the year section:
// Prompt the user to enter a year
SimpleIO.prompt("Enter a year: ");
userInput = SimpleIO.readLine();
int year = Integer.parseInt(userInput);
//Here, trying to use hasNextInt to make sure input is an integer
//If it's not, need to give an error message and prompt input again
// public boolean hasNextInt()
//Prompt input again if year is negative
if (year < 0) {
System.out.println("Year cannot be negative; try again");
return;
}
// Determine the number of days in the month
int numberOfDays;
switch (month) {
case 2: // February
numberOfDays = 28;
if (year % 4 == 0) {
numberOfDays = 29;
if (year % 100 == 0 && year % 400 != 0)
numberOfDays = 28;
}
break;
case 4: // April
case 6: // June
case 9: // September
case 11: // November
numberOfDays = 30;
break;
default: numberOfDays = 31;
break;
}
// Display the number of days in the month
System.out.println("There are " + numberOfDays +
" days in this month");
}
}
after seeing the code i'm sure it will be more clear what i'm asking. if they enter a word that isn't a month, prompt them and ask for input again. same thing if they enter a year that isn't integers. thanks in advance!
Running it in a loop, will do:
String userInput;
int month;
do{
SimpleIO.prompt("Enter a month name: ");
userInput = SimpleIO.readLine();
try{
month = Integer.parseInt(userInput);
} catch(NumberFormatException e){
continue;
}
}while(month <= 0 || month > 12);
You should create a loop that keeps prompting the user until the month is correctly inserted. Something in the following lines:
boolean correct_month = false; // Control variable
while(!correct_month)
{
int month = 0;
// Prompt the user to enter a month
SimpleIO.prompt("Enter a month name: ");
String userInput = SimpleIO.readLine();
...
// If the month is indeed correct
// then correct_month = true;
}
Then you apply the same idea to the years.
Instead of having all of those conditions on the month, I think it is better to add all the month strings into an ArrayList:
ArrayList <String> all_months = new ArrayList <String> ();
and then you just have to use all_months.indexOf with the string insert by the user. If it returns -1 the string is not a valid month, otherwise, it will give you the position where the month is on the list. For example
month = all_months.indexOf(userInput);
if(month != -1){
correct_month = true;
}
Thus, the complete solution would be something like:
ArrayList <String> all_months = new ArrayList <String> ();
all_months.add("january");
... // and so one
int month = 0; // Control variable
while(month <= 0)
{
// Prompt the user to enter a month
SimpleIO.prompt("Enter a month name: ");
String userInput = SimpleIO.readLine();
month = all_months.indexOf(userInput.trim().toLowerCase()) + 1;
}