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
Related
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 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.
My program is supposed to check if an integer is in a random integer. It will return true or false. For example: 45903 contains 4: true. For some reason; my code kept running after i entered the digit. Some thing is wrong with my containDigit() method but i can't seem to figure out. i'm very new to boolean.
import java.util.Scanner;
import java.util.*;
public class checkNum {
public static void main(String[] args) {
// Create a new Scanner object
Scanner console = new Scanner(System.in);
// Create a new Random objects
Random rand = new Random();
// Declare a integer value that is getting the value in the range of[10000, 99999]
int randomNum = rand.nextInt(90000)+10000;
// Show the random value to user by using of System.out.println
System.out.println(randomNum);
// Type a prompt message as "Enter a digit"
System.out.println("Enter a digit: ");
// Assign user input to integer value
int digit = console.nextInt();
// Define a boolean value that is assigned by calling the method "containDigit(12345,5)"
// Show the output
System.out.println(randomNum+ " contains" +
digit+" " + containDigit(randomNum,digit));
}
public static boolean containDigit(int first, int second) {
int digi = 10000;
// Define all statements to check digits of "first"
while (first > 0) {
digi = first % 10;
digi = first / 10;
}
if (digi == second){
return true;
}else {
return false;
}
// If it has "second" value in these digits, return true,
// If not, return false
// return a boolean value such as "return false";
return false;
}
}
If you're not restricted with way of solution, I can suggest below:
return (randomInt + "").contains(digit + "");
I dont understand why are you assigning first %10to digi and then immediately overwriting digi with first / 10.
Your while loop may never exit as first might always be greater than 0. It might never be entered as first might be equal to 0. You might want to do this:
while (first/10 == 0) {
first = first % 10;
if (first == second)
return true;
}
if(first%10 == second)
return true;
return false;
Your while loop never exits:
while (first > 0) {
digi = first % 10;
first = first / 10; // i believe this should be first instead of digit
}
You should add a simple print statement to check what your digit and first variables' values are:
System.out.println("digi: "+digi);
System.out.println("first: "+first);
I have a file that contains lots of movie titles along with their years, rating out of 5 stars, and length. I'm attempting to read the file and store the titles, year, rating, and length as variables. The problem I've encountered is in my code for retrieving the year. The code compiles, but then upon running throws a NumberFormatException when it gets to a movie with multiple years (for example, it is listed as 2006-2009). Here is my code.
while((line = bufferedReader.readLine()) != null) {
//System.out.println(line);
for(int i = 0; i < line.length(); i++)
{
if(line.charAt(i) == ')' || line.charAt(i) == '-')//get year
{
yr = line.substring(yearStart,i);
year = Integer.parseInt(yr);
}
}
System.out.println(year);
}
Shouldn't line.charAt(i) == '-' in my if statement take care of this issue?
EDIT: The below code is where yearStart comes from.
if(line.charAt(i) == '(')//get title
{
title = line.substring(0,i);
yearStart = i+1;
}
The file is formatted like this:
title (year) | rating, length
Sorry, I should have included that originally.
EDIT #2: Here's a sample of part of the file, if that helps
!Women Art Revolution (2010) | 3 stars, 1hr 22m
#1 Cheerleader Camp (2010) | 3 stars, 1hr 35m
$5 a Day (2008) | 3.4 stars, 1hr 37m
'night, Mother (1986) | 3.7 stars, 1hr 36m
'Til Death (2006-2009) | 3.7 stars, 4 Seasons//This is the one that causes the error
#Suicide Room (2011) | 3.4 stars, 1hr 51m
... And God Spoke (1993) | 2.8 stars, 1hr 22m
What happens once you have found the year? The loop will still run until the end of the line, trying to parse things as numbers every time it finds a ) or a -.
Maybe you should exit the loop once you have found the year.
if(line.charAt(i) == ')' || line.charAt(i) == '-')//get year
{
yr = line.substring(yearStart,i);
year = Integer.parseInt(yr);
break; // year found, no point in looping more
}
Or maybe you should reset the yearStart index so that the second year can be parsed.
if (line.charAt(i) == '-')
{
// parse first year
yr = line.substring(yearStart,i);
year = Integer.parseInt(yr);
yearStart = i + 1; // reset to parse second year
}
else if (line.charAt(i) == ')')
{
yr = line.substring(yearStart,i);
year = Integer.parseInt(yr);
break; // year found
}
Put Intger.parseInt in a try/catch block (similar to the one below) to see where this is failing and how:
try {
year = Integer.parseInt(yr);
} catch (Exception e) {
throw new RuntimeException(
"Failed to parse year '" + yr + "' in line '" + line + "'", e);
}
Btw: line.indexOf(')') returns the position of '(' in line.
After the first year is found, yearStart is still at the index of the first year. So when you try and get a subString, it is still (2006-2009) - Automatic NumberFormatException, can't parse the -.
You should change the yearStart after the first year is found:
for(int i = 0; i < line.length(); i++)
{
if(line.charAt(i) == ')' || line.charAt(i) == '-')//get year
{
yr = line.substring(yearStart,i);
year = Integer.parseInt(yr);
yearStart = i + 1;
}
}
The condition if(line.charAt(i) == ')' || line.charAt(i) == '-') holds true twice in your loop. First, when the hyphen matches, and then, when the closing parenthesis matches. The first time, year is assigned to, in your example, 2009. But then, the loop keeps running, and a few iterations later, you try to parse "2005-2009" which results in the NumberFormatException.
The most straightforward solution is to break; the loop just after assigning year, so that year is only assigned once. That said, supposing that you want to get the starting value of the interval.
A cleaner solution would be to avoid the loop at all, and instead judiciously using String.indexOf. Something like that (disclaimer: untested).
String title;
int year;
while((line = bufferedReader.readLine()) != null) {
title = line.substring(0, line.indexOf('('));
int yearStart = line.indexOf('(') + 1;
int yearEnd;
if (line.indexOf('-', yearStart) > 0 ) {
yearEnd = line.indexOf('-', yearStart);
} else {
yearEnd = line.indexOf('(', yearEnd);
}
int yr = line.substring(yearStart,i);
year = Integer.parseInt(yr);
System.out.println(year);
}
Finally, a more professional solution would use regular expresions, I understand you might not be familiar with that, and thus I have tried to provide an answer that follows a similar structure as yours.
I have a java programming assignment where you have to input a date on a single line and it gives you a numerology (horoscope-like) report based on the date. It is assumed that the user will enter a formatted date, separated with spaces.
I can retrieve the month, day, and year of the input by using in.nextInt(). However, I also have to check that the user used a correct separating character for each part of the date, which means I just have to check whether the user used forward slashes.
When looking at my code below, I currently use charAt() to find the separating characters. The problem is that the date won't always be 14 characters long. So a date in the form of 10 / 17 / 2004 is 14 characters long, but a date of 4 / 7 / 1992 is only 12 characters long, meaning that "slash1" won't always be in.charAt(3), in the latter situation it would be in.charAt(2).
Does java have a method that allows something like in.nextChar()? I know that it doesn't, but how could I just find a next character in the date?
EDIT: I forgot to reflect this originally, but my professor said that we are NOT allowed to use the String.split() method, for some reason. The thing is, I get the month, day, and year perfectly fine. I just need to check that the person used a forward slash to separate the date. If a dash is entered, the date is invalid.
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();
}
you could consider to split the input date string with " / ", then you get a String array. the next step is converting each string in that array to int.
I would use Scanner just to get a line. Then split() the line on whitespace and check the fields:
import java.util.Scanner;
import java.util.regex.Pattern;
public class GetDate {
int month, day, year;
public static void main(String[] args)
{
GetDate theApp = new GetDate();
theApp.getDate();
}
public void getDate()
{
String date;
do
{
System.out.print("Please enter your birth date (mm / dd / yyyy): ");
Scanner in = new Scanner(System.in);
date = in.nextLine();
} while (validDate(date) == false);
calcNum();
}
boolean validDate(String date)
{
// split the string based on white space
String [] fields = date.split("\\s");
// must have five fields
if ( fields.length != 5 )
{
return false;
}
// must have '/' separators
if ( ! ( fields[1].equals("/") && fields[3].equals("/") ) )
return false;
// must have integer strings
if ( ! ( Pattern.matches("^\\d*$", fields[0]) &&
Pattern.matches("^\\d*$", fields[2]) &&
Pattern.matches("^\\d*$", fields[4]) ) )
return false;
// data was good, convert strings to integer
// should also check for integer within range at this point
month = Integer.parseInt(fields[0]);
day = Integer.parseInt(fields[2]);
year = Integer.parseInt(fields[4]);
return true;
}
void calcNum() {}
}
Rather than thinking about what characters are used as separators, focus on the content you want, which is digits.
This code splits on non digits, do it doesn't matter how many digits are in each group or what characters are used as separators:
String[] parts = input.split("\\D+");
It's also hardly any code, so there's much less chance for a bug.
Now that you have the numerical parts in the String[], you can get on with your calculations.
Here's some code you could use following the above split:
if (parts.length != 3) {
// bad input
}
// assuming date entered in standard format of dd/mm/yyyy
// and not in retarded American format, but it's up to you
int day = Integer.parseInt(parts[0];
int month = Integer.parseInt(parts[1];
int year = Integer.parseInt(parts[2];
Look ahead in the stream to make sure it contains what you expect.
private static final Pattern SLASH = Pattern.compile("\\s*/\\s*");
static SomeTypeYouMadeToHoldCalendarDate getDate() {
while (true) { /* Might want to give user a way to quit. */
String line =
System.console().readLine("Please enter your birth date (mm / dd / yyyy): ");
Scanner in = new Scanner(line);
if (!in.hasNextInt())
continue;
int month = in.nextInt();
if (!in.hasNext(SLASH)
continue;
in.next(SLASH);
...
if (!validDate(month, day, year))
continue;
return new SomeTypeYouMadeToHoldCalendarDate(month, day, year);
}
}
This uses Scanner methods to parse:
import java.util.Scanner;
import java.util.InputMismatchException;
public class TestScanner {
int month, day, year;
public static void main(String[] args)
{
TestScanner theApp = new TestScanner();
theApp.getDate();
theApp.calcNum();
}
public void getDate()
{
int fields = 0;
String delim1 = "";
String delim2 = "";
Scanner in = new Scanner(System.in);
do
{
fields = 0;
System.out.print("Please enter your birth date (mm / dd / yyyy): ");
while ( fields < 5 && in.hasNext() )
{
try {
fields++;
switch (fields)
{
case 1:
month = in.nextInt();
break;
case 3:
day = in.nextInt();
break;
case 5:
year = in.nextInt();
break;
case 2:
delim1 = in.next();
break;
case 4:
delim2 = in.next();
break;
}
}
catch (InputMismatchException e)
{
System.out.println("ERROR: Field " + fields + " must be an integer");
String temp = in.nextLine();
fields = 6;
break;
}
}
} while ( fields != 5 || validDate(delim1, delim2) == false);
in.close();
System.out.println("Input date: " + month + "/" + day + "/" + year);
}
boolean validDate(String delim1, String delim2)
{
if ( ( ! delim1.equals("/") ) || ( ! delim2.equals("/") ) )
{
System.out.println("ERROR: use '/' as the date delimiter");
return false;
}
if ( month < 1 || month > 12 )
{
System.out.println("Invalid month value: " + month);
return false;
}
if ( day < 1 || day > 31 )
{
System.out.println("Invalid day value: " + day);
return false;
}
if ( year < 1 || year > 3000 )
{
System.out.println("Invalid year: " + year);
return false;
}
return true;
}
void calcNum()
{
}
}