import java.util.Calendar;
import java.util.GregorianCalendar;
public class CountingSundays {
public static void main(String args[]) {
Calendar cal = new GregorianCalendar(1901, 00, 01); // month set to 0for jan , 1= feb etc
while((cal.get(Calendar.YEAR) != 2001) && (cal.get(Calendar.MONTH) != 0) && cal.get(Calendar.DAY_OF_MONTH) != 1) { // while not 1/1/2001
System.out.print(cal.get(Calendar.MONTH));
// cal.add(Calendar.DAY_OF_MONTH, 1);
}
}
}
Im trying to iterate through the while loop by adding on a day at a time but it wont even access the while loop the first time. Are the conditions in the while loop right? When i tested it it worked with just one condition but stopped when i added the second condition.
It should be
while( !(cal.get(Calendar.YEAR) == 2001 && cal.get(Calendar.MONTH) == 0 && cal.get(Calendar.DAY_OF_MONTH) == 1) ) { // while not 1/1/2001
This is just a simple logic error. If even one of those is false (say, if the month IS 0), then you have true && false && true, which is false.
You need the "not" outside of the entire expression, or you need to use "||" to combine them:
while( !(year == 2001 && month == 0 && day == 1) )
or
while( (year != 2011) || (month != 0) || (day != 1) )
Related
I have a program that quotes up to 57 customizable products at one time. If there is a compatibility issue within one of the products the customer designs, an error pops up and a quote is not generated. I have it so if the generate button on line 57 is clicked, the program will check if lines 57, 56, 55... down to 1 are correct, then it will generate if they are. If line 56 is clicked, it checks 56 down to 1.
Is there a ways to loop is so that I only have to write it out once?
Here is my code:
if(e.getSource() == CA1.BTNgeneratequoteCA1)
{
if(CA1.generateCA1 == true)
{
try
{
FillAllKIS();
E2fill();
FillQuote();
}
catch(IOException y)
{
Logger.severe(y.getMessage());
}
RecordAllLines();
}
}
// if statments for lines 2 to 56 here
if(e.getSource() == CA57.BTNgeneratequoteCA1)
{
if(CA1.generateCA1 == true && CA2.generateCA1 == true && CA3.generateCA1 == true && CA4.generateCA1 == true && CA5.generateCA1 == true &&
CA6.generateCA1 == true && CA7.generateCA1 == true && CA8.generateCA1 == true && CA9.generateCA1 == true && CA10.generateCA1 == true &&
CA11.generateCA1 == true && CA12.generateCA1 == true && CA13.generateCA1 == true && CA14.generateCA1 == true && CA15.generateCA1 == true &&
CA16.generateCA1 == true && CA17.generateCA1 == true && CA18.generateCA1 == true && CA19.generateCA1 == true && CA20.generateCA1 == true &&
CA21.generateCA1 == true && CA22.generateCA1 == true && CA23.generateCA1 == true && CA24.generateCA1 == true && CA25.generateCA1 == true &&
CA26.generateCA1 == true && CA27.generateCA1 == true && CA28.generateCA1 == true && CA29.generateCA1 == true && CA30.generateCA1 == true &&
CA31.generateCA1 == true && CA32.generateCA1 == true && CA33.generateCA1 == true && CA34.generateCA1 == true && CA35.generateCA1 == true &&
CA36.generateCA1 == true && CA37.generateCA1 == true && CA38.generateCA1 == true && CA39.generateCA1 == true && CA40.generateCA1 == true &&
CA41.generateCA1 == true && CA42.generateCA1 == true && CA43.generateCA1 == true && CA44.generateCA1 == true && CA45.generateCA1 == true &&
CA46.generateCA1 == true && CA47.generateCA1 == true && CA48.generateCA1 == true && CA49.generateCA1 == true && CA50.generateCA1 == true &&
CA51.generateCA1 == true && CA52.generateCA1 == true && CA53.generateCA1 == true && CA54.generateCA1 == true && CA55.generateCA1 == true &&
CA56.generateCA1 == true && CA57.generateCA1 == true)
{
try
{
FillAllKIS();
E2fill();
FillQuote();
}
catch(IOException y)
{
Logger.severe(y.getMessage());
}
RecordAllLines();
}
I thought about doing it with a list filled with the instances of the classes but I'm struggling to think of how the logic would work for checking the boolean of each line, since there is another one to check with each added line item.
/* Create a list to hold CA1..CA57 */
List<MyClass> allCas = new ArrayList<>();
/* As you create CA1..CA57, whether in a loop or hardcoded, add them to your list, in order*/
...
allCas.add(CA1);
...
allCas.add(CA31);
...
allCas.add(CA57);
/* When button is clicked, find the related CA instance and check the preceding objects too. */
int selected = IntStream.range(0, allCas.size())
.filter(idx -> e.getSource() == allCas.get(idx))
.findFirst().getAsInt() + 1;
if (allCas.stream().limit(selected).allMatch(ca -> ca.generateCA1)) {
/* Fill quote and stuff. */
...
}
so I am trying to do a test class, the instruction is
Create a class called TestDate whose constructor creates fifteen Date objects and displays the day of the week for the dates by calling each Date’s getDayOfTheWeek() method. The dates are specifically these ones, in this precise order:
but when I run it, I keep getting errors! I think it's my constructor crashing or somewhere along that line.
Below is my TestDate class code
public class TestDate
{
private Date date;
/*
* Main Constructor
* #param fifteen specific date, test to your heart's content
*/
public TestDate()
{
Date d1 = new Date(1970, 11, 15);
System.out.println(date.getDayOfTheWeek());
Date d2 = new Date(1887, 7, 31);
Date d3 = new Date(1966, 5, 2);
Date d4 = new Date(1980, 8, 19);
Date d5 = new Date(2001, 9, 11);
Date d6 = new Date(1900, 6, 26);
Date d7 = new Date(1940, 2, 28);
Date d8 = new Date(1974, 10, 30);
Date d9 = new Date(1914, 1, 15);
Date d10 = new Date(1840, 10, 1);
Date d11 = new Date(1999, 12, 31);
Date d12 = new Date(1988, 5, 20);
Date d13= new Date(2012, 3, 10);
Date d14 = new Date(2006, 4, 1);
Date d15 = new Date(1992, 2, 29);
}
}
And here is my Date Class constructor and method getDayofTheWeek, I think that's all the information related to my problem.
public class Date
{
public Date(int year, int month, int day)
{
setYear(year);
setMonth(month);
setDay(day);
}
public String getDayOfTheWeek()
{
int step0 = year%100;
int step1 = step0 / 12;
int step2 = step0 % 12;
int step3 = step2 / 4;
int step4 = day;
int step5 = 0;
if(month == JANUARY || month == OCTOBER)
{
step5 = JAN_CODE;
}
else if(month == FEBURARY || month == MARCH || month == NOVEMBER)
{
step5 = FEB_CODE;
}
else if(month == APRIL || month == JULY)
{
step5 = APR_CODE;
}
else if(month == MAY)
{
step5 = MAY_CODE;
}
else if(month == JUNE)
{
step5 = JUN_CODE;
}
else if(month == AUGUST)
{
step5 = AUG_CODE;
}
else if(month == SEPTEMBER || month == DECEMBER)
{
step5 = SEP_CODE;
}
else
{
step5 = 0;
}
if(year/100 ==16 || year/100 == 20)
{
step5 = step5 + SPECIAL_CODE_SIX;
}
else if(year/100 == 17 || year/100 == 21)
{
step5 = step5 + SPECIAL_CODE_FOUR;
}
else if(year/100 == 18)
{
step5 = step5 + SPECIAL_CODE_TWO;
}
int step6 = (step1 + step2 + step3 +step4 + step5)%MOD_CODE;
if(step6 == SAT_CODE)
{
return "Saturday";
}
else if(step6 == SUN_CODE)
{
return "Sunday";
}
else if(step6 == MON_CODE)
{
return "Monday";
}
else if(step6 == TUE_CODE)
{
return "Tuesday";
}
else if(step6 == WED_CODE)
{
return "Wednesday";
}
else if(step6 == THU_CODE)
{
return "Thursday";
}
else if(step6 == FRI_CODE)
{
return "Friday";
}
else
{
return null;
}
}
}
and I passed the parameter in the mutator method
public void setYear(int year)
{
if(year <= CURRENT_YEAR && year >= YEAR_ZERO)
{
this.year = year;
}
}
public void setMonth(int month)
{
if(month <= DECEMBER && month >= JANUARY)
{
this.month = month;
}
}
public void setDay(int day)
{
if(month == JANUARY || month == MARCH || month == MAY || month == JULY || month == AUGUST
|| month == OCTOBER || month == DECEMBER)
{
if(day <= DAY_THIRTY_ONE && day >= DAY_ONE)
{
this.day = day;
}
else
{
year = CURRENT_YEAR;
month = JANUARY;
day = DAY_ONE;
}
}
else if(month == APRIL || month == JUNE || month == SEPTEMBER || month == NOVEMBER)
{
if(day <= DAY_THIRTY && day >= DAY_ONE)
{
this.day = day;
}
else
{
year = CURRENT_YEAR;
month = JANUARY;
day = DAY_ONE;
}
}
else if(month == FEBURARY)
{
if((isLeapYear() == true) && day <= DAY_FEB_LEAP && day >= DAY_ONE)
{
this.day = day;
}
else if((isLeapYear() == false) && day <= DAY_FEB_NORMAL && day >= DAY_ONE)
{
this.day = day;
}
else
{
year = CURRENT_YEAR;
month = JANUARY;
day = DAY_ONE;
}
}
}
Sorry for the long list of code, I don't really know which ones are useless.
In the second line of your constructor you are calling
System.out.println(date.getDayOfTheWeek());
on the variable date which is null at this point as it has not been initialized yet. This leads to a NullPointerException. Read here for more information: What is a NullPointerException, and how do I fix it?
What I am (assuming) you wanted to do there is:
System.out.println(d1.getDayOfTheWeek());
Things besides that that I noticed:
You use the #param field in a javadoc comment without there being a parameter. Do not do this. If your constructor does not take arguments then there should not be a #param.
You are creating 15 instances of Date in your constructor whose scope end as soon as the constructor is finished. You could just delete them and nothing would change. I am assuming you want this class to be a "test" whether your dates are initialized correctly. I would recommend doing this in a main method (for a quick test while coding) and with an actual test framework like JUnit for 'real' testing. You can read this tutorial if you are interested. It also goes into detail why you actually want to test.
I started learning java on my own a few weeks back and I keep running up to the same basic problem, where I can't call a method from another method in the same class. I either get a "symbol not found" error (I think because the method is out scope or the method just doesn't work anymore. The following code is part of a java exercise for creating a calender sort of a programme. I'll use the // in code commentaries to indicate, where exactly is the problem.
public class MyDate {
private int year;
private int month;
private int day;
private static String[] strMonths = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
private static String[] strDays = {"Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday"};
private static int[] daysInMonths = {31, 28, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
public static boolean isLeapYear(int year) { // This is the first method, which works fine
// when being called from the main method.
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) {
return true;
} else {
return false;
}
};
public static boolean isLeapYear; // I put this declaration in, because I got
// "symbol not found" errors, when referencing the method from the second method.
// I'm guessing it partially invalidates the first declaration.
public static boolean isValidDate(int year, int month, int day) { // The second method
if ((year >= 1 ) && (year <= 9999)){
if ((month >= 0) && (month <= 11)) {
if ((day >= 1) && ((month == 0) || (month == 2) || (month == 4) || (month == 6)
|| (month == 7) || (month == 9) || (month == 11)) && (day <= 31)) {
return true;
}
else if ((day >= 1) && ((month == 3) || (month == 5) || (month == 8)
|| (month == 10) && (day <= 30))) {
return true;
}
else if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)){
// Code from the first method (above), which I would like to replace with just a reference
// to the first method (for instance (isLeapYear = true)),
// but it doesn't work the same as the code above (or at all).
if ((month == 1) && (day == 29)) {
return true;
}
else
if ((day >= 1) && ((month == 1) && (day <= 28))) {
return true;
}
else {
return false;
}
}
}
}
return isValidDate; }
For reference, the method isLeapYear works as it's supposed to, when testing it with this main method:
public static void main(String[] args) {
System.out.println(isLeapYear(1900)); // false
System.out.println(isLeapYear(2000)); // true
System.out.println(isLeapYear(2011)); // false
System.out.println(isLeapYear(2012)); // true
}
}
Thanks for your help!
Remove public static boolean isLeapYear; from your code and every time you need to call a function, in this case public static boolean isLeapYear(int year) { ..} you must use a parenthesis to let the compiler know that you are actually calling a function there.
In this case you should go with isLeapYear(year)
and then if (isLeapYear(year)) { .. } else {..}
Given package name of MyApplication (substitute your package name in each place this one occurs below) import isLeapYear as shown below.
package MyApplication;
public class MyDate {
public static boolean isLeapYear(int year) { // This is the first method, which works fine
// when being called from the main method.
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) {
return true;
} else {
return false;
}
};
}
Main class:
package MyApplication;
import static MyApplication.MyDate.isLeapYear;
public class NewClass{
public static void main(String[] args) throws Exception
{
System.out.println(isLeapYear(1900)); // false
System.out.println(isLeapYear(2000)); // true
System.out.println(isLeapYear(2011)); // false
System.out.println(isLeapYear(2012));
}
}
the If condition doesn't work always trade in allowance= 3,250.00 I need it depends on the state and car year. I attached what my code and more explanation.
The trade-in allowance depends on the year of manufacture of the vehicle and the state in which it had been registered at initial purchase. FHM does not accept vehicles manufactured earlier that 1990 for trade-in allowance. For vehicles manufactured between
1990 and 1999 and initially registered in Illinois, Indiana, Iowa, Kansas, Michigan, Minnesota, Missouri, or Nebraska, the trade-in allowance is $3000.00, for all other states it is $ 2750.00.
For vehicles manufactured between 2000 and 2009 and initially registered in Illinois, Indiana, Iowa, Kansas, Michigan, Minnesota, Missouri, Nebraska, North Dakota, Ohio, South Dakota or Wisconsin, the trade-in allowance is $3250.00, for all other states it is $ 3000.00.
For vehicles manufactured in 2010 and after, the trade-in allowance is $5000.00, irrespective of the state of initial registration.
if (vehiclesYear <= 1999 || vehiclesYear >= 1990
& (stateNames.getSelectedItem() == "IL")
|| (stateNames.getSelectedItem() == "IN")
|| (stateNames.getSelectedItem() == "IA")
|| (stateNames.getSelectedItem() == "KS")
|| (stateNames.getSelectedItem() == "MI")
|| (stateNames.getSelectedItem() == "MN")
|| (stateNames.getSelectedItem() == "MO")
|| (stateNames.getSelectedItem() == "NE")) {
tradeIn = 3000.00;
} else {
tradeIn = 2750.00;
}
if (vehiclesYear >= 2000
& (stateNames.getSelectedItem() == "IL")
|| (stateNames.getSelectedItem() == "IN")
|| (stateNames.getSelectedItem() == "IA")
|| (stateNames.getSelectedItem() == "KS")
|| (stateNames.getSelectedItem() == "MI")
|| (stateNames.getSelectedItem() == "MN")
|| (stateNames.getSelectedItem() == "MO")
|| (stateNames.getSelectedItem() == "NE")
|| (stateNames.getSelectedItem() == "ND")
|| (stateNames.getSelectedItem() == "OH")
|| (stateNames.getSelectedItem() == "SD")
|| (stateNames.getSelectedItem() == "WI")) {
tradeIn = 3250.00;
} else {
tradeIn = 3000.00;
}
if (vehiclesYear >= 2010) {
tradeIn = 5000.00;
}
let us walk through your code.
if you want to have a between check
change following
if (vehiclesYear <= 1999 || vehiclesYear >= 1990)
to
if (vehiclesYear <= 1999 && vehiclesYear >= 1990)
also i suggest you define a String variable and assign it to stateNames.getSelectedItem()
like
String item = stateNames.getSelectedItem();
and use this item for comparison
also as it is a string i suggest you to use .equals() method for comparison than == to avoid reference comparison issue
also for comparison you can implement method using switch(item) java 7 and above will support the same
like
switch (item)
{
case "IL":
case "IN":
.
.
case "KS":
return true;//or do something here
break;
}
One main problem is that you're comparing Strings using the == operator, which is not guaranteed to give the expected result.
In Java, Strings are objects, and the == operator compares for object reference equality.
So if I do
String myString = "Foo";
if (myString == "Foo") {
System.out.println("They are the same");
} else {
System.out.println("They are not the same");
}
the results are not guaranteed. To compare Strings for equality, use the String.equals(String) method.
On a more stylistic note, I would probably have inserted the state codes into separate Set<String> instances like so:
private boolean isInTheNineties(int year) {
return year >= 1990 && year <= 1999;
}
private double getTradeIn(int vehiclesYear, SomeClass stateNames) {
Set<String> s0 = new HashSet<>();
s0.addAll(Arrays.asList("IL", ... , "NE"));
String registrarState = stateNames.getSelectedItem();
if (isInTheNineties(vehiclesYear)) {
if (s0.contains(registrarState)) {
return 3000.00;
} else {
return 2750.00;
}
}
// And so on for the 2000s
}
Also, the Why not use Double or Float to represent currency? question seems relevant here.
Currently any year satisfies the following condition:
if (vehiclesYear <= 1999 || vehiclesYear >= 1990)
This is because every year is either before 1999 or after 1990.
If you want the years between 1999 and 1990 then you need to do this:
if (vehiclesYear <= 1999 && vehiclesYear >= 1990)
I'm not completely sure about this, but you might have to put the "tradein=3000.00;" inside of a block to get it to work out. {} after your 'if' statement and before your 'else' statement, everything should be surrounded in a block, this might alter and fix your problem!
I am working through the JavaBat questions and am confused about my logic.
Here's the task:
Given a day of the week encoded as 0=Sun, 1=Mon, 2=Tue, ...6=Sat, and
a boolean indicating if we are on vacation, return a string of the
form "7:00" indicating when the alarm clock should ring. Weekdays, the
alarm should be "7:00" and on the weekend it should be "10:00". Unless
we are on vacation -- then on weekdays it should be "10:00" and
weekends it should be "off".
alarmClock(1, false) → "7:00" alarmClock(5, false) → "7:00"
alarmClock(0, false) → "10:00"
Here's my code:
public String alarmClock(int day, boolean vacation) {
if ( (day >=1 && day <=5) && (!vacation)) {
return "7:00";
} else if ( (day >=1 && day <=5) && (vacation)) {
return "10:00";
} else {
return "off";
}
}
Why do these two tests fail?
alarmClock(0, false) → "10:00" "off" X
alarmClock(6, false) → "10:00" "off" X
Surely, this line covers it?
if (day >=1 && day <=5) && (!vacation))
how about this?
public String alarmClock(int day, boolean vacation) {
if (day >=1 && day <=5) {
return vacation ? "10:00" : "7:00";
} else {
return vacation ? "off" : "10:00";
}
}
Note it does depend if your coding convention allows the use of the turnary operator. But in this case I think the logic is easier to read.
Surely, this line covers it?
if ((day >=1 && day <=5) && (!vacation))
No, that line doesn't cover it. If the day is Sunday or Saturday (0 or 6), the first part of your "and" expression (day >=1 && day <=5) will be false, since 0 and 6 are not between 1 and 5 inclusive.
The only branch that handles days 0 and 6 is your else branch: "off".
This is a great time to use helper methods to express your logic closer to the English description:
if ( isWeekday(day) ) {
if ( vacation ) {
//what to return here?
} else {
//what to return here?
}
} else {
if ( vacation ) {
//what to return here?
} else {
//what to return here?
}
}
Then you just need to implement isWeekday:
private boolean isWeekday(int day) {
return /*fill this in*/;
}
Although the ternary operator is useful here, as this problem can be done in a single return statement, the following code below allows readability.
public String alarmClock(int day, boolean vacation) {
if(vacation){ //if we are on vacation
if(day > 0 && day < 6){ //if it is weekday and we are on vacation
return "10:00";
}
else return "off"; //it must be the weekend!
}
//from here on out all the cases where vacation is true have been weeded out
if(day > 0 && day < 6){
return "7:00";
}
else return "10:00";
}
if ((day == 0 || day == 6) && (!vacation) || (day >= 1 && day <= 5) && (vacation)) {
return "10:00";
}
if ((day >= 1 && day <= 5) && (!vacation)) {
return "7:00";
}
return "off";
public String alarmClock(int day, boolean vacation) {
if (((day==0)||(day==6))&&(!vacation)){
return "10:00";
}
else if (((day!=0)||(day!=6))&&(!vacation)){
return "7:00";
}
else if (((day==0)||(day==6))&&(vacation)){
return "off";
}
else{
return "10:00";
}
}