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 7 years ago.
Improve this question
I am getting an error when trying to call a boolean method from another class. I have tried editing the way I am calling the method, but none have worked so far. I'm posting the code I had for both classes for the clearest error message i got which was the ".class" expected error.
public class Date
{
public int Day;
public int Month;
public int Year;
public Date(int myDay, int myMonth, int myYear){
Month = myMonth;
Day = myDay;
Year = myYear;
}
public int daysIs(){
return Day;
}
public int monthIs(){
return Month;
}
public int yearIs(){
return Year;
}
public boolean isLeapYear(int Year){
if (Year % 4 != 0){
return false;
}else if (Year % 400 == 0) {
return true;
}else if (Year % 100 == 0){
return false;
}else {
return true;
}
}
Date mydate = new Date(Day, Month, Year);
}
For the first class here it compiles with no errors. The method I am trying to call is the isLeapYear method near the end. My second class always has some kind of error when I try to call the method.
import javax.swing.JOptionPane;
public class DateJDialog
{
public static void main(String[]args)
{
String input;
int Day;
int Month;
int Year;
//prompt the day
input = JOptionPane.showInputDialog("Please enter the 2 digit day of the month: ");
Day = Integer.parseInt(input);
//prompt the month
input = JOptionPane.showInputDialog("Please enter the 2 digit month of the year: ");
Month = Integer.parseInt(input);
//prompt the year
input = JOptionPane.showInputDialog("Please enter the 4 digit year: ");
Year = Integer.parseInt(input);
Date inputDate = new Date(Day,Month,Year);
if( inputDate.isLeapYear(int Year)= false){
JOptionPane.showMessageDialog(null,"The given year was NOT a Leap Year.");
}else {
JOptionPane.showMessageDialog(null,"The given year WAS a Leap Year.");
}
}
}
The errors always happen on the first line of the if statement near the end.
Try to write this line of if condition.
if (inputDate.isLeapYear(int Year)= false) {...}
Like this:
if (!inputDate.isLeapYear(2015)) {
You don't specify a data type of a parameter when you call a method. Also, = is an assigning operator, in conditions we use a comparing operator ==.
There is no need of comparing a boolean value to another boolean value, so == is pointless in this case.
Your thinking too hard, you should take it simple when programming. You don't need the type when calling a method, only do this when you declare it.
Related
How do I find the next leap year if the given input isn't a leap year?
A year is considered a leap year when it is either:
divisible by 4, but not 100 or
divisible by both 4, 100, and 400 at the same time
Input:
A single line containing a number that represents a year, here 1702.
Output:
The next soonest leap year if the input is not a leap year. Otherwise, output "Leap year".
The next leap year is 1704
Heres my code:
When I input 1702 nothing shows but if it's 1700 it works. If ever you can help pls only use if else or while since these two are the only allowed for it to run.
import java.util.Scanner;
class Main {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
int year = input.nextInt();
int leap = 0;
if (year % 400 == 0) {
System.out.print("Leap year");
} else if (year % 100 == 0) {
leap += 4;
year += leap;
System.out.print("The next leap year is ");
System.out.print(year);
} else if (year % 4 == 0) {
System.out.print("Leap year");
}
input.close();
}
}
tl;dr short solution with java.time:
Java 8+ provide the package java.time which has a class Year which provides a method to determine if that very year was/is/will be a leap year, that is Year.isLeap().
You could use it to get your desired result, maybe like in the following example:
public static void main(String[] args) {
// hard-coded example number
int numericalYear = 1702;
// create the year from the number given
Year year = Year.of(numericalYear);
// check if that year is leap
if (year.isLeap()) {
System.out.println("Leap Year");
} else {
// of find the next one by adding 1 year and checking again
while (!year.isLeap()) year = year.plusYears(1);
// print the next one
System.out.println("Next leap year is " + year);
}
}
This example has an output of
Next leap year is 1704
The major part of the main() is an if-statement with three branches. I think the most difficulties you have is you mixed the part to determine a leap year, and the part to control the workflow.
The workflow of your program is:
Take an user input
Check if this is a leap year
Print the response according to step 2
The logic to determine a leap year is:
divisible by 4, but not 100 or
divisible by both 4, 100, and 400 at the same time
You could try to isolate these two area with two different piece of code. Take one step at a time. Then things will become less complex. You can simplify your if from three to two branches. Since the year is either a leap or not, no other possibility. If it is leap year, print the year. Else, print next leap year. Only two cases.
In order to check whether a year leap year or not, obviously you need an algorithms. You can decouple the algorithms into a separate function. This way you can isolate the leap year logic with your workflow.
Example
import java.util.Scanner;
public class Main{
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
int year = input.nextInt();
// base cycle is 4 year
final int leapCycle = 4;
if (isLeapYear(year)) {
System.out.print("Leap year");
} else {
// complete the year with next cycle
year += leapCycle - (year % leapCycle);
// the next maybe not a leap year e.g. 1800, 1900
if (!isLeapYear(year)) {
// then advance it with one more cycle
year += leapCycle;
}
System.out.print("The next leap year is ");
System.out.print(year);
}
input.close();
}
private static boolean isLeapYear(int year) {
if (year % 4 == 0) {
if (year % 100 == 0) {
return year % 400 == 0;
} else {
return true;
}
}
return false;
}
}
Test cases
1700
The next leap year is 1704
1702
The next leap year is 1704
1799
The next leap year is 1804
1800
The next leap year is 1804
1999
The next leap year is 2000
2000
Leap year
2001
The next leap year is 2004
My if statement is not working correctly. The purpose is to compare a user given date with the current date, and if both the month and week match (a user's birthday), then getBonus = true.
However, my if statement is giving me the following error:
bad operand types for binary operator '&&'
first type: int
second type: int
incompatible types: int cannot be converted to boolean
Why is my if statement trying to run as a boolean when all of the variables involved are int?
public static boolean getBonus ( int Week, int Month, int bMonth, int bWeek
) {
boolean getBonus = false;
/**************************************************************************
The following statement is used to determine if the user's birthday is
this week, using the month and week of the month. bMonth/bWeek are generated
from user input, Month/Week are generated from a real time calendar.
**************************************************************************/
if(bWeek = Week && bMonth = Month)
{
getBonus = true;
}
return getBonus;
}//end class getBonus
Use If Statement as follow
if(bWeek == Week && bMonth == Month)
{
getBonus = true;
}
== is used to compare
= is use to assign value
Do this
if(bWeek == Week && bMonth == Month)//used to compare
// true && true --> true
Instead of this
if(bWeek = Week && bMonth = Month)//used to assign
Error description here
I can return either getMonth() or getYear() from the following code.
When both are called, an error is displayed.
I have tried giving the value of m and y separately in the calculate date function and that works perfectly !!
Any suggestions?
I am a beginner, apologies if there is a trivial mistake, though there shouldn't be according to me.
import java.util.Scanner;
public class Second_Java {
public static int getMonth() {
int a;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the input for the required month: ");
a = sc.nextInt(); // stored in 'a' locally
while (a < 1 || a > 12) {
a = -1;
System.out.println(a);
}
sc.close();
return a;
}
public static int getYear() {
int b;
Scanner input = new Scanner(System.in);
System.out.println("Enter the input for the required year: ");
b = input.nextInt(); // stored in 'a' locally
while (b < 1) {
b = -2;
System.out.println(b);
}
input.close();
return b;
}
public static void calculateDays(int m, int y) {
switch (m) {
case 4:
case 6:
case 9:
case 11:
m = 30;
System.out.println(m);
break;
case 2:
if (y % 400 == 0 || (y % 4 == 0 && y % 100 != 0)) {
m = 29;
System.out.println(m);
} else {
m = 28;
System.out.println(m);
}
break;
default: {
m = 31;
System.out.println(m);
}
}
}
public static void main(String[] args) {
int m = getMonth();
int y = getYear();
calculateDays(m, y);
}
}
Closing the Scanner also closes the input stream it's scanning -- in this case System.in. Hence, when you subsequently call getYear(), it finds the input stream System.in already closed.
One way to avoid this is to use the same Scanner in both methods, by passing it as an argument to the methods.
From the Java API docs for Scanner.close():
public void close()
Closes this scanner.
If this scanner has not yet been closed then if its underlying readable also implements the Closeable interface then the readable's close method will be invoked. If this scanner is already closed then invoking this method will have no effect.
By the way, the purpose of the loops in getMonth() and getYear() are unclear. If you want to continue scanning until a valid value is entered, then you want to include a call to Scanner.nextInt() inside the loops. And consider using a do-while statement, since you know you want to read at least one value.
You can do this, simply by defining an object with both values as fields e.g. for the above.
class MonthAndYear {
public int month;
public int year;
}
and your function can execute both your methods above, and return an instance of MonthAndYear populated with the month and year values.
In the above case, your month and year are obviously closely tied together, and you're on your way to (re)defining some sort of Date class.
Note that lots of codebases have a Pair object (or similar) for this sort of things. If you're using Scala, you can couple the two values together trivially using a tuple (e.g. like this (month, year) )
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm making a thingy that takes 3 inputs like "1500, 1 and 1" or "1500, January and 1" and returns "January 1st, 1500" or "1/1/1500", i had some problems on the day part but someone already told me how to fix it, and now I'm having problems with the month part, i made this kinda fast and i haven't figured out why it isn't working, it SHOULD see if the input is a valid month, if it is then it outputs the month(this part is just for testing), and if it isn't then it should say "please use a valid month or a number between 1 and 12", but when i write anything that isn't a month it just stops, and doesn't output anything, even if i put a month after it just doesn't do anything, i tried to see if there was any errors but i didn't found any, this is the code that i used:
Scanner scan = new Scanner(System.in);
String mx;
System.out.println("Insert Month");
String[] mm = {"january","february","march","april","may","june","july","august","september","october","november","december"};
int mz = 0;
while (0 < 1){
mx = scan.nextLine();
mx = mx.toLowerCase();
for(int i = 0; i < 11; i++){
if (mx.equals(mm[i])){
mz = i + 1;
break;
}
else {
if(i == 11){
System.out.println("please use a valid month or a number between 1 and 12");
}
else{
}
}
}
//}
if(mz > 0){
break;
}
else {}
}
System.out.println(mx);
The reason your program just "stops" is that you only print the statement "please enter a valid month..." if i == 11 and you have your for loop break if i >= 11. Thus, this condition will never be met. The while loop keeps running, even though this statement isnt printed. You could have entered a non-month string on the first try, and then a month string on the second and your while loop would have been broken.
Here is how I have improved your code to work for taking in the month. Pay attention to subtle changes of highlighted. These are important for writing better, more readable code:
Scanner scan = new Scanner(System.in);
//initialize to empty string
String mx = "";
System.out.println("Insert Month");
//use good naming conventions for easier code readability
String[] validMonths = {"january","february","march","april","may","june","july","august","september","october","november","december"};
//using a boolean to break makes much more sense than the way you have written it with an infinite loop and a manual break statement
boolean noMonth = true;
while (noMonth){
mx = scan.nextLine();
for(int i = 0; i < 12; i++){
//rather than convert to lowercase, use this handy String method
//also compares for valid number entries
if (mx.equalsIgnoreCase(validMonths[i]) || mx.equals(Integer.toString(i+1))){
noMonth = false;
break;
}
}
if(noMonth){
System.out.println("please use a valid month or a number between 1 and 12");
}
}
System.out.println(mx);
Create a new while loop to take in the day and a new one to take in the year after these, checking for valid input. Also, every if does not require an else in Java.
You're not using meaningful variable names, making your code a little bit hard to read and maintain. So, I had to create you the following code from scratch:
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
String month = getMonthName(getInt("Enter Month: ", keyboard) - 1);
int day = getInt("Enter Day: ", keyboard);
int year = getInt("Enter Year: ", keyboard);
System.out.printf("%s %d, %d\n", month, day, year);
}
public static String getMonthName(final int monthNo)
{
String[] months = {"january","february","march","april","may","june","july","august","september","october","november","december"};
return months[monthNo];
}
public static int getInt(final String msg, Scanner keyboard)
{
System.out.print(msg);
return keyboard.nextInt();
}
The code above does NOT perform and input validation, as you may have noticed already. If you want to validate month input for example, your if condition may look something like this:
if (month < 0 || month < 12)
{
System.out.println("Invalid month number entered");
System.exit(0);
}
I'm trying to use try and catch. If the entered input isn't valid the loop sould repeat and ask the user for input again, but it's not working. When I type something wrong it just repeats the System.out.println.
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
public class Price
{
public static void main(String[] args)
{
userInput();
}
public static void userInput()
{
Scanner scan = new Scanner(System.in);
int x = 1;
int month, day, year;
do {
try {
System.out.println("Please enter a month MM: ");
month = scan.nextInt();
if(month>12 && month<1)
{
System.out.println("FLOP");
}
x=2;
}
catch(Exception e){
System.out.println("not today mate");
}
}
while(x==1);
}
}
this is a working solution to your problem
public static void userInput(){
Scanner scan = new Scanner(System.in);
int x = 1;
int month, day, year;
System.out.println("Please enter a month MM: ");
month = scan.nextInt();
boolean i = true;
while(i == true)
{
if(month < 12 && month > 1)
{
System.out.println("FLOP");
i = false;
}
else if(month >= 12 || month <= 1)
{
System.out.println("not today mate");
month = scan.nextInt();
}
}
}
As a general rule, exceptions are used for exceptional circumstances, not to drive the logic of a program. Validating inputted data is not an exceptional circumstance in this case. It's a normal state of affairs that a user might make an error and enter an incorrect number. Put the input in a loop and repeat until a correct value is entered (perhaps with an option for the user to cancel).
First your condition is wrong.
You have:
if(month>12 && month<1)
{
System.out.println("FLOP");
}
So month cannot be bigger than 12 and at the same time less than 1.
I think you wanted to put OR instead of AND, e.g.
if(month > 12 || month < 1)
{
System.out.println("FLOP");
}
As for the exception, it might occur when user enters non numeric value or input is exausted.
Throws:
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed