If string == "sting text" return int [duplicate] - java

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

Related

how can I find which day is it by entering a number between 1 and 7 using only one if statement?

public static String GetDayOfWeek(int day){
String weeks[]={"modnay","Tuesday","Wednesday","Thursday","Friday", "Saturday","Sunday"};
int day1 = day-1 ;
for(int i =0; i<weeks.length ; i++){
if (day1 == weeks[i].lastIndexOf(i)){ // probably here is my mistake
return weeks[day1];
}
}
return null;
}
How can I compare between the input number and the array indexes so I can find which day it is? Are there any other ways to do it using polymorphism? I thought to create a class for each day and extends it to this class but then I will be using more than one if!!
I have been asked to use one and only one if statement and I can't use more than one if statement or a switch statement.
public static String GetDayOfWeek(int day) {
String weeks[] = {"Modnay", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
if (day > weeks.length || day < 0) {
return null;
}
return weeks[day - 1];
}
You can just return the element at the correct index without any looping. You may also want to make the array static. If it is possible for the day to be invalid, you can add an additional check with an if statement.
public static String getDayOfWeek(int day){
String[] weeks = {"Monday","Tuesday","Wednesday","Thursday","Friday", "Saturday","Sunday"};
return day >= 1 && day <= 7 ? weeks[day - 1]: null;
}
On a side note, you should always follow Java naming conventions e.g. the name of your method should be getDayOfWeek instead of GetDayOfWeek.

Checking if an integer argument is defined for a method

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;
}
}

Simple Junit testing with OOP java

Below is a class that represents time using hours and minutes (seconds are not represented).
public class ClassTime {
public static int hour;
public static int minute;
public static String amPm;
//Initializes the object using specified parameter values.
public ClassTime(int hour, int minute, String amPm){
//hour value between 1 and 12, both inclusive.
boolean validHour = false;
if (hour >= 1 && hour <= 12){
validHour = true;
this.hour = hour;
} else {
throw new IllegalArgumentException("Invalid hour value");
}
//minute value between 0 and 59, both inclusive.
boolean validMinute = false;
if (minute >= 0 && minute <= 59){
validMinute = true;
this.minute = minute;
} else {
throw new IllegalArgumentException("Invalid minutes value");
}
//amPm is either "am" or "pm".
if (amPm.equalsIgnoreCase("am")){
this.amPm = amPm;
} else if (amPm.equalsIgnoreCase("pm")){
this.amPm = amPm;
} else {
throw new IllegalArgumentException("Invalid am/pm value");
}
}
/*
* Returns a string using the format "hour:minutes am" or "hour:minutes pm".
* A single space is used in between minutes and am/pm. The minutes always
* appear with two digits (e.g., 0 minutes will be "00").
*/
public String toString(){
String toBeReturned = "hour:" + String.format("%02d", this.minute) +
" " + amPm;
return toBeReturned;
}
/*
* Compares two time objects. Two time objects are considered equal if
* they represent the same time.
*/
public boolean equals(ClassTime obj){
boolean equal = false;
if (obj.minute == this.minute && obj.hour == this.hour &&
obj.amPm.equalsIgnoreCase(this.amPm)){
equal = true;
}
return equal;
}
/*
* Compares two time objects. Returns -1 if the current object is a time
* that precedes the time parameter, 0 if the current object and the time
* parameter represent the same time, and 1 if the current object represents
* a time that is after the time parameter.
*/
public int compareTo(ClassTime obj){
int returnNum = 2;
if(this.amPm.equalsIgnoreCase("am") && obj.amPm.equalsIgnoreCase("pm")){
returnNum = -1;
} else if (this.amPm.equalsIgnoreCase("pm") &&
obj.amPm.equalsIgnoreCase("am")){
returnNum = 1;
} else if (this.amPm.equalsIgnoreCase(obj.amPm)){
if (this.hour < obj.hour){
returnNum = -1;
} else if (this.hour > obj.hour){
returnNum = 1;
} else if (this.hour == obj.hour){
if (this.minute < obj.minute){
returnNum = -1;
} else if (this.minute > obj.minute){
returnNum = 1;
} else if (this.minute == obj.minute){
returnNum = 0;
}
}
}
return returnNum;
}
/*
* Returns a new time object corresponding to the time we will have after
* increasing the time parameter by the specified number of minutes.
*/
public static ClassTime increaseByMinutes(ClassTime obj, int minutes){
//create variables that monitor changes in minutes, hours, and amPm.
int minValue = obj.minute + minutes;
int hourValue = obj.hour;
String amPmValue = obj.amPm;
/*
* increments hour and minutes if the total minutes is below two hours,
* but greater tan or equal to 1 hour.
*/
if(minValue > 59 && minValue < 120){
minValue = minValue % 60;
hourValue = hourValue + 1;
if (hourValue > 12){
hourValue = hourValue % 12;
} else if(hourValue == 12 && amPmValue.equalsIgnoreCase("am")){
amPmValue = "pm";
} else if (hourValue == 12 && amPmValue.equalsIgnoreCase("pm")){
amPmValue = "am";
}
/*
* Increment for when the total amount of minutes is greater
* or equal to 2 hours.
*/
} else if (minValue > 119){
for(int i = 0; i <= (minValue/60); i++){
hourValue++;
if(hourValue > 12){
hourValue = hourValue % 12;
} else if (hourValue == 12 && amPmValue.equalsIgnoreCase("am")){
amPmValue = "pm";
} else if (hourValue == 12 && amPmValue.equalsIgnoreCase("pm")){
amPmValue = "am";
}
}
}
/*
* Create a new ClassTime object with the found values of minutes, hours,
* and amPm Value. This is what will be returned.
*/
ClassTime newObject = new ClassTime(hour, minute, amPm);
newObject.minute = minValue;
newObject.hour = hourValue;
newObject.amPm = amPmValue;
return newObject;
}
public static void main(String[] args) {
}
}
I don't know how to test the constructor or the methods in a JUnit test case. So far the only thing I can come up with for the constructor is:
import static org.junit.Assert.*;
import org.junit.Test;
public class JunitTests {
#Test
public void testClassTime() {
ClassTime object1 = new ClassTime(3, 30, "pm");
}
}
How would I finish doing a test for the constructor and maybe just 1 method. Please don't do all of them.
I suggest you read up on unit testing, your question is a bit too broad.
Basically the idea is that given some situation, when a thing happens, then some conditions should be true. (I personally add comments to my tests to help me think in those terms.)
Here's an abstract example:
Given bread and a toaster
When I put the bread in the toaster and get it out when it's done
Then it should be toasted
Look up JUnit's assertion library to help find good ways to assert conditions. When looking up JUnit examples you'll usually see things like assertTrue(...) or assertNotNull(...), these are static methods from the Assert class, I mention this because you seem like a novice and I don't want you to get confused by examples. Usually all these methods are imported statically in the examples.
What you have in your test case currently is the given, a when could be doing toString() (String actual = object1.toString();). Your then clause would be asserting that the String returned equals what it should, which is probably "3:30 PM" (assertEquals("3:30 PM", actual);). I didn't design your code, so I don't know if that's correct, you may expect it to return `"Hello, World!" In any case, I'd run this one first ;)

Null Pointer Exception for Arraylist? [duplicate]

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.

Result does not show, date validation

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;
}

Categories

Resources