This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I have class date which just simply creates an arrayList of days of the week.
import java.util.*;
public class Date {
public static final String[] daysofTheWeek = {"Mon" , "Tue" , "Wed" , "Thurs" , "Fri" , "Sat" , "Sun"};
private String dayofweek;
private int day;
private int month;
public int getDate() {
return this.day;
}
public int getMonth() {
return this.month;
}
public Date(String dayofweek, int day, int month) {
this.day = 1;
if (day >= 1 && day <= 31) {
this.day = day;
}
this.month = 12;
if (month >= 1 && month <= 12) {
this.month = month;
}
this.dayofweek = "Mon";
if (isValidDOW(dayofweek)) { // why is this in the parameters?
this.dayofweek = dayofweek;
}
}
// must validate is DOW
// TRUE/FALSE is the day of the week matching?
public boolean isValidDOW(String d) {
for (int i = 0; i < dayofweek.length(); i++)
if (d.equals(daysofTheWeek[i])) { // why i?
return true;
}
return false;
}
// to string
public static String monthToString(int i) {
switch(i) {
case 1: return "January";
case 2: return "Feb";
case 3: return "March";
case 4: return "April";
case 5: return "May";
case 6: return "June";
case 7: return "July";
case 8: return "August";
case 9: return "September";
case 10: return "October";
case 11: return "November";
case 12: return "December";
default: return "Invalid Month!!";
}
}
public String toString() {
return this.dayofweek + "," + Date.monthToString(this.month) + " " + this.day;
}
public String getDayOfWeek() {
return this.dayofweek;
}
}
Now I am trying to get all days ( Say, return number of times sundays pop up). I tried using a loop to go through and count everything, but I am getting a null pointer exception. I've been looking at this for a while, and can't figure out whats wrong with it. Can anyone guide me in the right direction?
import java.util.*;
/**
* ArrayList example
*/
public class Calendar {
private ArrayList<Date> Schedule;
public ArrayList<Date> sundays(String dayofweek) {
ArrayList<Date> app = new ArrayList<Date>();
for (Date entry : Schedule) {
String d = entry.getDayOfWeek();
if (entry.getDayOfWeek() == dayofweek) {
app.add(entry);
}
else if (app.size() == 0) {
return null;
}
}
return app;
}
}
You never initialize the field Schedule, so it is default-initialized to null. Therefore, the line for (Date entry:Schedule) (which is syntactic sugar for calling Schedule.iterator() and iterating over the resulting iterator) throws a NullPointerException.
Also — non-static field names in Java are supposed to start with lowercase letters. You should change Schedule to schedule. (Or you can follow one of the more-specific naming conventions that exist out there. Some projects start all field-names with f — in your case fSchedule; others start all field-names with m for "member" — in your case, mSchedule. If you adopt one of those conventions, just be sure to be consistent about it.)
I think the method isValidDOW should be:
public boolean isValidDOW(String d){
for (int i=0; i < daysofTheWeek.length; i++)
if ( d.equals(daysofTheWeek[i])) // why i?
{
return true;
}
return false;
}
Using daysofTheWeek.length instead of dayofweek.length(), for example if dayofweek = 'Sat', the for loop will only execute 3 times, but 'Sat' is in the 6th place and the value is 5 in ArrayList daysofTheWeek.
Related
Scenario: I am currently attempting to make a calendar in Java, one of the methods I have created (getMonthSize) is to get the size of a month (as shown). My goal currently is to make the method respond regardless of whether the argument is defined by the user (give the current month size if argument left blank, and give the size of the inputted month if argument is defined).
Efforts: I have given quite a thorough search for an answer on the web, I have come across answers testing to see if the arg.length==0 (although it turns out that works only if the arg is a String), and answers using something along the lines of "arg!==undefined" (which I think may be for javascript), with no avail. I have also learned that if an integer is not initialized, its default value will be 0, so that is what I tried to take advantage of with my code shown, although it seemed that java still expects me to input "0" for the method to work.
Question: I am hoping there is some command that checks if the argument is left blank, allowing me to set 2 cases, and achieve what I want with the method.
package model;
import java.util.Calendar;
public class myCalendar {
private Calendar calendar=Calendar.getInstance();
private int day=calendar.get(Calendar.DAY_OF_WEEK);
private int date=this.calendar.get(Calendar.DAY_OF_MONTH);
private int month=calendar.get(Calendar.MONTH)+1;
private int year=calendar.get(Calendar.YEAR);
public void setCalendar(int Year, int Month, int Date){
this.calendar.set(Year,Month-1,Date);
}
public int getDay(){
return day;
}
public int getDate () {
return date;
}
public int getMonth(){
return month;
}
public int getYear() {
return year;
}
public int getFirstDay () {
Calendar test = this.calendar;
test.set(year, month-1, 1);
return test.get(Calendar.DAY_OF_WEEK)-1;
}
public int getMonthSize (int num) {
int Month=0;
int days=0;
if (num>0){
Month=num;
} else {
Month=month;
}
if(Month==1||Month==3||Month==5||Month==7
||Month==8||Month==10||Month==12){
days=31;
}
if(Month==4||Month==6||Month==9||Month==11)
{
days=30;
}
if(Month==2)
{
if(((year%4==0)&&(year%100!=0))||(year%400==0))
{
days=29;
}
else
{
days=28;
}
}
return days;
}
public String getNow () {
String monthNames[]={"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
String a=monthNames[month-1]+", "+String.valueOf(year);
return a;
}
}
I hope that I understood your problem correctly.
Your problem is that your user can start the method without a valid argument. If you have a frontend than you should catch it there too. But in the backend (java) you can work with a try-block or simply with if-else.
Cast the Integer to a String and then use regex (maybe something like this
String text = num + "";
if (text != null && text.matches("\\d+")) {
//...
}
Or you can cast your Integer to a String and use String.isEmpty().isEmpty returns true if, and only if, length() is 0. (https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#isEmpty()).
Sting temp = num + "";
if (num.isEmpty()) {
//...
}
Or simply a try-catch Block where you cast your input to a new variable.
try {
Month = Integer.parseInt(num);
} catch (NumberFormatException e) {
// handle error
}
And please notice that your variable "Month" should be "month". In most programming communities everyone uses lowercase variables.
There are countless options how you can handle this situation and you can try every one of them. I hope that the ones I listed are all correct.
Edit:
Oh and I checked the other comments and I noticed that you are a beginner. Here are maybe some useful tips, so everyone in your class including the teacher can read easier your code. In most programming languages there is something like "checkstyle". It is hard to explain, but with some google you can find useful tips.
I will make a few "suggestions" to your code, which you can adopt or ignore. Like spaces between some characters some comments, etc.
But don't focus to hard on the quality. In some IDEs you can automatically format your code to "the standard". With Intellij it is. ctrl+alt+l
import java.util.Calendar;
public class myCalendar {
private Calendar calendar = Calendar.getInstance();
private int day = calendar.get(Calendar.DAY_OF_WEEK);
private int date = this.calendar.get(Calendar.DAY_OF_MONTH);
private int month = calendar.get(Calendar.MONTH) + 1;
private int year = calendar.get(Calendar.YEAR);
/**
* Description what the method does.
*
* #param Year what does the parameter?
* #param Month ""
* #param Date ""
*/
public void setCalendar(int Year, int Month, int Date) {
this.calendar.set(Year, Month - 1, Date);
}
public int getDay() {
return day;
}
public int getDate() {
return date;
}
public int getMonth() {
return month;
}
public int getYear() {
return year;
}
/**
* Description what the method does.
*
* #return value (short description)
*/
public int getFirstDay() {
Calendar test = this.calendar;
test.set(year, month - 1, 1);
return test.get(Calendar.DAY_OF_WEEK) - 1;
}
/**
* Description what the method does.
*
* #param num (short description)
* #return (short description)
*/
public int getMonthSize(int num) {
int month;
int days = 0; //My IDE tells me that need to be initialized, but why? Are there cases where the method returns 0?
//I think that num=100 returns 0, so maybe you can catch this case with if(num > 12) or something similar
if (num > 0) {
month = num;
} else {
month = this.month;
}
if (month == 1 || month == 3 || month == 5 || month == 7
|| month == 8 || month == 10 || month == 12) {
days = 31;
}
if (month == 4 || month == 6 || month == 9 || month == 11) {
days = 30;
}
if (month == 2) {
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) {
days = 29;
} else {
days = 28;
}
}
return days;
}
public String getNow() {
String monthNames[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
String a = monthNames[month - 1] + ", " + String.valueOf(year);
return a;
}
}
When I run the following code I receive the error -
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
at homework6.main(homework6.java:6)
I researched why this could occur and previous answers had said the class name needed to match the java file name, my class matches that of the .java file as well. I also tried removing "void" and the entire statement altogether, but then a new error occurred saying I needed public void main(String[] args). Am I encountering a different problem then the class and .java?
public class homework6 {
public static void main(String[] args) {
class Date {
private int month;
private int day;
private int year;
private String name;
public Date() {
}
{
month=1;
day = 1;
year = 2001;
name = "January";
}
public Date(int m, int d, int y) {
setDate(m, d, y);
}
public void setDate(int m, int d, int y) {
month = m;
day = d;
year = y;
if (m ==1 )
name="January";
else if(m == 2)
name="February";
else if(m == 3)
name="March";
else if(m == 4)
name="April";
else if(m == 5)
name = "May";
else if(m == 6)
name = "June";
else if(m == 7)
name = "July";
else if(m == 8)
name = "August";
else if(m == 9)
name = "September";
else if(m == 10)
name = "October";
else if(m == 11)
name="November";
else if(m == 12)
name = "December";
}
public void showDate1() {
System.out.println(month + "/" + day + "/" + year);
}
public void showDate2() {
System.out.println(name + "" + day + "," + year);
}
public void showDate3() {
System.out.println(day + "" + name + "" + year);
}
}
}
}
You're nesting a class, Date, within a method, the main method to be precise -- something you can't and shouldn't do.
Solution: don't do this.
Create one file called Date.java and place your Date class code in it.
Create a 2nd file called Homework6.java and place your main method in it.
Done.
Valid points those in the answer. You could alternatively just put the class outside the main and get it to compile.
If you take a step back though, and assuming you get this code to compile, what would be the expected output? You seem to make no calls to any methods. Do you want to spend a moment in understanding your logic?
Probably because of this:
public Date() {
}
{
month=1;
day = 1;
year = 2001;
name = "January";
}
The first two brackets should be removed, because the code between the second two is not in a method. So it should be like this:
public Date() {
month=1;
day = 1;
year = 2001;
name = "January";
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I am trying to return an integer if particular string is true. (For this I do not want to use an array).
public String calcNextDay()
{
if (day == "Sunday"){
return 0; // If day is Sunday return 0
}else if (day == "Monday"){
return 1; // If Day is Monday return 1
}else if (day == "Tuesday"){
return 2; // If day is tuesday return 2
}else if(day == "Wednesday"){
return 3; // If day is Wednesday return 3
}else if(day == "Thursday"){
return 4;// If day is Thursday return 4
}else if (day == "Friday"){
return 5;// If day is Friday return 5
}else if(day == "Saturday"){
return 6;// if day is Saturday return 6
}
}
I have also tried this, but am getting an error with the return dayValue stating it can not be converted to String (even though I do not want to turn it to a string)
public String calcNextDay()
{
int dayValue = 0;
if (day == "Sunday"){
dayValue = 0; // If day is Sunday return 0
}else if (day == "Monday"){
dayValue =1; // If Day is Monday return 1
}
return dayValue;
}
What am I doing wrong?
Based on the comments I changed some code to
Public String calcNextDay()
{
int dayValue = 0;
if (day.equals("Sunday")){
dayValue = 0;
}else if (day.equals("Monday")){
dayValue = 1;
}else if (day.equals("Tuesday")){
dayValue = 2;
}return dayValue;
}
error: incompatible types: int cannot be converted to String
}return dayValue;
Thank you, I got passed that problem and then I get to the error
Day.java:178: error: non-static variable dayValue cannot be referenced from a static context
System.out.println("Your day is stored as " + testday.setDay() + dayValue);
^
1 error
My main() is a static, but my dayValue is not
All the string comparisons are wrong, in Java they must be done like this:
if (day.equals("Sunday"))
In other words, use equals() for testing equality, instead of ==. Even better, it's a good practice to put the literal value first, in case the other value is null. This is what I mean:
if ("Sunday".equals(day))
And also, you are trying to return an int inside a function that specifies the return type as String, so change this:
public String calcNextDay()
… to this:
public int calcNextDay()
In Java the strings are not compared with ==. The correct way is to use method equals.
if ("Sunday".equals(day))
For safety compare using "Yoda convention": the comparison will not fail even if day is null.
As for returning integer, using a lot of if else if not the best practice either. There are better ways to do it:
Use switch statement
switch (day) {
case "Monday" : return 0;
case "Tuseday": return 1;
...
}
Create an array with day names and search for specific day in array. Return an index of the item found
Also, since you're returning int, your function's result type should be also int
Any idea why my code won't show the result? Maybe I messed up something, just new to programming by the way.
The goal of the program is to see if the date given by the main class is valid or not, it's not that specific on details such as the month of February and leap years so its pretty simple.
This is my DataRec.java :
public class DateRec {
int month, day, year;
boolean good;
public DateRec (){
month = 1;
day = 1;
year = 2008;
good = true;
}
public DateRec (int setMonth, int setDay, int setYear){
month = setMonth;
day = setDay;
year = setYear;
}
public void validate (){
if ((month < 0) || (month > 12)){
good = false;
if (year == 0)
good = false;
if ((day < 0) || (day > 31))
good = false;
}
}
#Override
public String toString() {
if (good = true) {
return String.format("%dd/%dd/%dddd", month, day, year);
} else {
return String.format("%dd/%dd/%dddd", month, day, year);
}
}
}
This is my main class DataRecTest.java:
public class DateRecTest {
public static void main (String[] args){
DateRec today = new DateRec(1,2,2014);
DateRec anyDay = new DateRec();
DateRec noDay = new DateRec(13,31,2014);
anyDay.validate();
today.validate();
noDay.validate();
today.toString();
anyDay.toString();
noDay.toString();
}
}
Default value of boolean (good) is false so you need to initialized good in constructor or validate() function i.e
good = true; // in constructor or validate function
To see the results you need to print them.
//To print in java use System.out.print() or println();
System.out.println(today.toString());
//or simply
System.out.println(today); // println will call today.toString() internally
[EDIT]
Since you are storing result in good I recommend the following:
public DateRec (int setMonth, int setDay, int setYear){
month = setMonth;
day = setDay;
year = setYear;
good = true;
validate();
}
Now you don't need to call validate() every-time; just check the value of good
your validate() is wrong.... It will always be set t false (default value) in whenever you use the 3- argument constructor. You are not setting it to true when date is correct.
change it to,
public void validate (){
if ((month <= 0) || (month > 12) || (year==0) || (day<=0) || (day>31)){
good = false;
}
else
{
good=true;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have a project in school to solve year 2000 with java. here is the description of the assignment:
Create a Date object with the following:
attribute: a julian date representing the number of days since Jan 1, 1501 (the epoch date for this project) - this should be a private member variable of the class with the associated accessor and mutator methods.
constants: a suitable constant for each month
a suitable contant for each component of the epoch date
method: Date(long year, long month, long day) that converts the given year, month, and day to the julian date.
method: a method that converts a year, month, and day into the number of days since the project's epoch date.
method: a method that determines if a given year is a leap year
method: a method that returns the number of days in a given year; replace the current simple if statement with a single statement using the conditional operator (? :)
method: a method that returns the number of days in a given month of a given year; method should implement a switch statement using appropriate constants.
methods: any of the other methods developed in class should probably also be included.
method: returnYear() a method that determines the year component of the julian date value
method: returnMonth() a method that determines the month component of the julian date value
method: returnDay() a method that determines the day component of the julian date value
method: returnMonthName() a method that returns the name of the given month ( if month = JAN return "January" (use a switch statement))
method: returnDate() a method that returns the date in the format monthName day, year
class: Utility containing two query methods.
And here is the code I came with so far.. it is not compiling because there is something wrong with the switch!
import java.util.Scanner;
class Date
{
public final static long EPOCHYEAR = 1501;
private long julianDate;
Date(long year, long month, long day)
{
julianDate = returnTotalJulianDay(year, month, day);
System.out.println("Days is " + julianDate);
}
boolean isLeapYear(long year)
{
boolean answer;
if(year % 4 == 0 && (year % 4 == 0 || year % 100 != 0))
{
answer = true;
}
else
{
answer = false;
}
return answer;
}
long returnDaysInMonth(long year, long month)
{
if(month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)
{
return 31;
}
else if(month == 4 || month == 6 || month == 9 || month == 11)
{
return 30;
}
else if(isLeapYear(year))
{
return 29;
}
else
{
return 28;
}
}
long returnJulianDate(long year, long month, long day)
{
long julianDate;
long monthCounter;
julianDate = 0;
monthCounter = 1;
while(monthCounter < month)
{
julianDate += returnDaysInMonth(year, monthCounter);
monthCounter += 1;
}
julianDate += day;
return julianDate;
}
long returnTotalJulianDay(long year, long month, long day)
{
long totalJulianDay = 0;
long yearCounter = 1;
while(yearCounter < year)
{
totalJulianDay += returnJulianDate(year, month, yearCounter);
yearCounter += 1;
}
return totalJulianDay;
}
long returnDaysInYear(long year)
{
final long DAYSINYEAR = 365;
if(isLeapYear(year))
{
return 366;
}
else
{
return DAYSINYEAR;
}
}
long returnJulianEpochDays(long year, long month, long day)
{
long yearCounter = EPOCHYEAR;
long total = 0;
while(yearCounter < year)
{
total += returnDaysInYear(yearCounter);
yearCounter += 1;
}
total += returnJulianDate(year, month, day);
return total;
}
long returnYear()
{
long dayCounter = 0;
long yearCounter = EPOCHYEAR;
for(dayCounter = this.julianDate; dayCounter > returnDaysInYear(yearCounter); yearCounter++)
{
dayCounter -= returnDaysInYear(yearCounter);
}
return yearCounter;
}
long returnMonth()
{
long julianEpochDays = julianDate;
long yearCounter = EPOCHYEAR;
long monthCounter = 1;
while(julianEpochDays > returnDaysInYear(yearCounter))
{
julianEpochDays -= returnDaysInYear(yearCounter);
yearCounter++;
}
while(julianEpochDays > returnDaysInMonth(yearCounter, monthCounter))
{
julianEpochDays -= returnDaysInMonth(yearCounter, monthCounter);
monthCounter++;
}
return monthCounter;
}
long returnDay()
{
long julianEpochDays = julianDate;
long yearCounter = EPOCHYEAR;
long monthCounter = 1;
while(julianEpochDays > returnDaysInYear(yearCounter))
{
julianEpochDays -= returnDaysInYear(yearCounter);
yearCounter++;
}
while(julianEpochDays > returnDaysInMonth(yearCounter, monthCounter))
{
julianEpochDays -= returnDaysInMonth(yearCounter, monthCounter);
monthCounter++;
}
return julianEpochDays;
}
long returnMonthName()
{
int month = 0;
final int JAN = 1;
final int FEB = 2;
final int MAR = 3;
final int APR = 4;
final int MAY = 5;
final int JUN = 6;
final int JUL = 7;
final int AUG = 8;
final int SEP = 9;
final int OCT = 10;
final int NOV = 11;
final int DEC = 12;
switch(month)
{
case JAN:
return "January";
case FEB:
return "Febuary";
case MAR:
return "March";
case APR:
return "April";
case MAY:
return "May";
case JUN:
return "June";
case JUL:
return "July";
case AUG:
return "August";
case SEP:
return "September";
case OCT:
return "October";
case NOV:
return "November";
case DEC:
return "December";
}
}
}
class utility
{
public char queryForCharacter(String prompt)
{
int typedCharacter = ' ';
try
{
System.out.print(prompt);
typedCharacter = System.in.read();
}
catch(Exception e)
{
}
return (char) typedCharacter;
}
public static long queryForLong(String prompt)
{
Scanner keyboard;
long theNumber;
keyboard = new Scanner(System.in);
System.out.print(prompt);
theNumber = keyboard.nextInt();
return theNumber;
}
}
public class DateDriver
{
public static void main(String[] args)
{
Date aTestDate = null;
aTestDate = new Date(1502, 1, 1);
}
}
Your method returnMonthName() is declared to return a long, but the switch cases return Strings.
Also, the method needs to return something if none of the cases in the switch match.
Your function returns a type of long:
"long returnMonthName() {"
But your are returning a type of "String". i.e. "January".