I was developing this java program that tells the user the number of days in their birth month and the number of days until their birthday, the former part works and the number of days until their birthday works if it's less than three months away but I can't figure out why it doesn't work after that point
import java.util.*;
public class Jack_Dennin_HW2
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("What month of the year is it?(1-12)");
int month = (sc.nextInt()-1);
System.out.println("What day of the month?");
int day = sc.nextInt();
System.out.println("What month is your birthday?(1-12)");
int bmonth = (sc.nextInt()-1);
System.out.println("What day of that month is your birthday?");
int bday = sc.nextInt();
Date today = new Date(month, day);
Date birthday = new Date(bmonth, bday);
int sum = (today.daysInMonth()-day+bday);
System.out.println("There are "+birthday.daysInMonth()+" days in your birth month");
if (month==bmonth)
{
if(day==bday)
{
System.out.println("Happy Birthday!");
}
else if(bday>day)
{
System.out.println("Your birthday is "+(bday-day)+" days away");
}
else
{
System.out.println("Your birthday is "+(365+bday-day)+" days away");
}
}
else
{
for(int i = month+1; i==(bmonth-1)%12; i++)
{
Date n = new Date(i%12,1);
sum=(sum+n.daysInMonth());
}
System.out.println("There are "+sum+" days until your birthday");
}
}
}
class Date
{
private int month;
private int day;
public Date(int month2, int day2)
{
month = month2;
day = day2;
}
public int getMonth()
{
return(month);
}
public int getDay()
{
return(day);
}
public String toString()
{
String day2;
if (day%10==day)
{
day2 = "0"+day;
}
else
{
day2 = day+"";
}
return(month+"/"+day2);
}
public int daysInMonth()
{
switch(month)
{
case 0: return(31);
case 1: return(28);
case 2: return(31);
case 3: return(30);
case 4: return(31);
case 5: return(30);
case 6: return(31);
case 7: return(31);
case 8: return(30);
case 9: return(31);
case 10: return(30);
case 11: return(31);
default: return(-1);
}
}
}
This is because of this line:
for(int i = month+1; i==(bmonth-1)%12; i++)
Specifically, i==(bmonth-1)%12.
Lets take two dates: 1st of January and 1st of February. In that case, month=0, i=0+1=1, i==1%12 is true, and you drop into the for statement and calculate the days correctly.
Lets take another two dates: 1st of January and 1st of April. In that case, month=0, i=1, but i==2%12 is false, so you do not drop into the for statement and therefore do not calculate the correct sum.
Since this is homework, I will not tell you the solution, but the line that needs to be fixed is i==(bmonth-1)%12. Its a very simple fix.
P.S. Take some time to learn how to use a debugger! :)
Related
Hello I'm new in using java
i just need some advice..
this is what i need to do:
the user inputted the date 8/15/2018, the console should have the output: "Hello! This is day 15 of the month of August in the year of our Lord 2018."
this is my code
package newdate;
import java.util.Scanner;
public class NewDate {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the date in mm/dd/yyyy: ");
String str=sc.next();
switch (str) {
case 1: str.substring(0,2) = "January";
break;
case 2: str.substring(0,2) = "February";
break;
case 3: str.substring(0,2) = "March";
break;
case 4: str.substring(0,2) = "April";
break;
case 5: str.substring(0,2) = "May";
break;
case 6: str.substring(0,2) = "June";
break;
case 7: str.substring(0,2) = "July";
break;
case 8: str.substring(0,2) = "August";
break;
case 9: str.substring(0,2) = "September";
break;
case 10: str.substring(0,2) = "October";
break;
case 11: str.substring(0,2) = "November";
break;
case 12: str.substring(0,2) = "December";
break;
default: str.substring(0,2) = "Invalid month";
break;
}
System.out.println("Hello! This is day " + str.substring(3,5) +" of the month of " + str.substring(0,2) +" in the year of our Lord" + str.substring(6,10));
}
}
the problem is the data type, i want the month which is a number will be replace by a string(month)
example: 11 = November
how can i do it?
First, for real world programming one would use LocalDate from the standard library for holding a date and DateTimeFormatter for parsing the user entered date in a LocalDate. See the link at the bottom.
Most fundamentally, with your code you need a separate String variable for the name of the month. You cannot assign this back into the string you already have. Just declare String monthName; and assign it the proper value in your switch startement.
Also when str is a string and 1 is an int, you cannot switch on str and use 1 as a case label. The straightforward fix is to switch on str.substring(0,2) (the month number as string) and use "01", "02", etc. as case labels. Another common solution would be to parse the month number into an int (see the other link below or search for how to do it) and then keep you case labels 1, 2, etc., as they are.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Question: How do I convert a String to an int in Java?
Hello dear junior developer :)
my suggestion is:
first define an enumeration for month names:
enum MonthName{
January(0),
February(1),
March(2),
April(3),
May(4),
June(5),
July(6),
August(7),
September(8),
October(9),
November(10),
December(11);
private int number;
MonthName(int number){
this.number=number;
}
public static String findName(int number){
for(MonthName monthName:MonthName.values()){
if(monthName.number==number){
return monthName.name();
}
}
throw new RuntimeException("Invalid Month!");
}
}
then define a class for your desire format:
class MyDateFormat{
private int day;
private String month;
private int year;
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
public String getMonth() {
return month;
}
public void setMonth(String month) {
this.month = month;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
}
and finally create a method for separating your input string (8/15/2018):
public MyDateFormat getFormatedDate(String dateString) throws ParseException {
SimpleDateFormat dateFormat=new SimpleDateFormat("MM/dd/yyyy");
Date date = dateFormat.parse(dateString);
Calendar calendar=Calendar.getInstance();
calendar.setTime(date);
MyDateFormat myDateFormat=new MyDateFormat();
myDateFormat.setDay(calendar.get(Calendar.DAY_OF_MONTH));
myDateFormat.setMonth(MonthName.findName(calendar.get(Calendar.MONTH)));
myDateFormat.setYear(calendar.get(Calendar.YEAR));
return myDateFormat;
}
Good Luck :)
Please try this.
try {
String str ="8/15/2018";
Date date=new SimpleDateFormat("MM/dd/yyyy").parse(str);
System.out.println("Hello! This is day " + new SimpleDateFormat("dd").format(date) +" of the month of " + new SimpleDateFormat("MMMM").format(date) +" in the year of our Lord " + new SimpleDateFormat("yyyy").format(date));
} catch (ParseException e) {
e.printStackTrace();
}
This question already has answers here:
returning multiple values in Java
(6 answers)
Closed 6 years ago.
I have the following below code. I need to return month and year values from "getInput" method. Getting error as unreachable statement. I am using BlueJ IDE. How to get tow return values now. Please help.
public class CalendarTester
{
public static void main(String[] args) { //method call for testing valid inputs from the user
nputValidate();
}
public static void InputValidate(){ //Method to call functions for validation of inputs
String UserInput="";
UserInput=getInput();
ValidateInput(UserInput);
}
public static String getInput(){ // To read user input
Scanner scanner=new Scanner(System.in);
System.out.println("Please enter the year (eg - 2016):");
String year = scanner.next();
System.out.println("Please enter the month (eg - 10):");
String month = scanner.next();
return year;
return month;
}
public static boolean ValidateInput(String toValidation){ // Method to validate inputs
boolean Pass=false;
String finalString=toValidation.replaceAll("\\s+","");
String matchingString="[0-9]{4,6}";
if(finalString.matches(matchingString)){
String Month=finalString.substring(0, 3);
String Year = finalString.substring(0, 4);
int month=Integer.parseInt(Month);
int year=Integer.parseInt(Year);
if(month>0 && month<=12){
if(year>999 & year<=10000){
Pass=true;
Calendar calender = new Calendar();
boolean isLeapYear=calender.isLeapYear((short) year);
if(isLeapYear){
System.out.println("The given year " +year+ " is a leap Year");
}else{
System.out.println("The given year " +year+ " is not a leap Year");
}
byte TotalDaysInMonth=calender.TotalDaysOfMonth((byte) month,(short) year);
System.out.println("Total days in the month " +month+ "are "+TotalDaysInMonth);
byte week=calender.firstDayOfYear((short) year);
String FirstDayOfWeek ="";
switch (week) { //Case for first day of the week
case 0:
FirstDayOfWeek="Mon";
break;
case 1:
FirstDayOfWeek="Tue";
break;
case 2:
FirstDayOfWeek="Wed";
break;
case 3:
FirstDayOfWeek="Thur";
break;
case 4:
FirstDayOfWeek="Fri";
break;
case 5:
FirstDayOfWeek="Sat";
break;
case 6:
FirstDayOfWeek="Sun";
break;
default:
FirstDayOfWeek="Invalid week input";
break;
}
System.out.println("The first day of the year"+year+"is "+FirstDayOfWeek);
byte firstmonthday = calender.firstDayOfMonth((byte) month,(short) year);
String dayName = "";
switch(firstmonthday)//to print the first day of the month
{
case 0: dayName = "Sat"; break;
case 1: dayName = "Sun"; break;
case 2: dayName = "Mon"; break;
case 3: dayName = "Tue"; break;
case 4: dayName = "Wed"; break;
case 5: dayName = "Thur"; break;
default: dayName = "Fri"; break;
}
System.out.println("The first day of the month" +month+ "is " + dayName);
calender.printMonth((byte) month,(short) year);
}else{
System.out.println("Invalid year input");
Pass=false;
InputValidate();
}
}
else if(month<=0 || month>12){ //validates the month entered
System.out.println("Invalid month input");
Pass=false;
InputValidate();
}
}
return Pass;
}
}
The Java-idiomatic way of doing this is to make a new class containing the things that you want to return as members:
public static class Foo
{
String year;
String month;
}
and return an instance of that.
You'll find this is the approach that scales best. Eventually you'll end up adding all sorts of other functionality to this class.
You might even notice that it's too similar to some of the standard classes (java.util.Date and the newer java.time.LocalDate), and ditch the whole thing altogether.
return 1 array containing the 2 values
Try using Array, you can assign 2 or more values :
public static String[] getInput(){ // To read user input
Scanner scanner=new Scanner(System.in);
System.out.println("Please enter the year (eg - 2016):");
String year = scanner.next();
System.out.println("Please enter the month (eg - 10):");
String month = scanner.next();
return new String[]{year,month};
}
We're supposed to make a program in computer science that figures out what day of the week you were born on. We were given these instructions.
1) Start with the last two digits of the year in which you were born.
2) Divide the above number by 4, dropping the remainder if there is one.
3) Find the number associated with the month in which you were born in the Table of Months.
4) On which day of the month is your birthday?
5) Find the sum of the four numbers obtained in steps 1 through 4.
6) Divide the sum by the number 7. The day that corresponds to the remainder in the Table of Days is the day of the week you were born on.
Table of Months Table of Days
January 1 (0 in leap year) Sunday 1
February 4 (3 in leap year) Monday 2
March 4 Tuesday 3
April 0 Wednesday 4
May 2 Thursday 5
June 5 Friday 6
July 0 Saturday 0
August 3
September 6
October 1
November 4
December 6
I've been having trouble with is incomparable types: int and boolean, i don't know what the problem is, ive tried changing variables to boolean, but it doesn't solve anything.
package LeapYear;
import java.util.*;
public class Birthday
{
static Scanner in= new Scanner(System.in);
public static void main (String []args)
{
int year=getYear();
int month=getMonth(year);
int day=getDay();
int total=computeDay(day, month, year);
int dayofbirth=dayOfWeek(day,month,year);
}//end main
public static int getYear()
{
System.out.println("Please enter the last two digits of the year you were born:");
int y=in.nextInt();
return y;
}
public static int getMonth(int year)
{
int m;
System.out.println("Please select the month in which you were born:"+
"1.)Januaryn\n"+
"2.)February\n"+
"3.)March\n"+
"4.)April\n"+
"5.)May\n"+
"6.)June\n"+
"7.)July\n"+
"8.)August\n"+
"9.)September\n"+
"10.)October\n"+
"11.)November\n"+
"12.)December\n");
m=in.nextInt();
System.out.println("You entered " + m);
switch(m)
{
case 1: if(year ==true)
return 0;
else
return 1 ;
break;
case 2:if(year == true)
return 3;
else
return 4;
break;
case 3:return 4;
break;
case 4:return 0;
break;
case 5:return 2;
break;
case 6:return 5;
break;
case 7:return 0;
break;
case 8:return 3;
break;
case 9:return 6;
break;
case 10:return 1;
break;
case 11:return 4;
break;
case 12:return 6;
break;
}//end case
}//end getMonth
public static int getDay()
{
int d;
System.out.println("Please enter the day on which you were born");
d=in.nextInt();
return d;
}//end getDay
public static int computeDay(int day, int month, int year)
{
int weekday;
int y2=year/4;
int m2= month + y2 + day;
int total=m2/7;
return total;
}//end computeDay
public static int dayOfWeek(int day, int month, int year, int total)
{
int dob;
switch(dob)
{
case 1:if (total=1)
System.out.println("You were born on a Sunday");
break;
case 2:if (total=2)
System.out.println("You were born on a Monday");
break;
case 3: if (total=3)
System.out.println("You were born on a Tuesday");
break;
case 4: if(total=4)
System.out.println("You were born on a Wednesday");
break;
case 5: if(total=5);
System.out.println("You were born on a Thursday");
break;
case 6: if (total=6);
System.out.println("You were born on a Friday");
break;
case 7: if (total=7);
System.out.println("You were born on a Saturday");
break;
}
}//end dayOfWeek
}//end class
if(year == true) cannot compile because an integer cannot be true. Do something useful with that statement like:
if(year < 50)
{
System.out.println("Wow, you're old!");
return 0;
}
Because you are only getting the last two digits of their year of birth, you will have trouble deciding if the user was born in the year 1905 or 2005. This is an unlikely case, but you would not be able to decipher whether the user was born this century or the last. If it is acceptable not to know, don't change it. If not, you will need to get more information from the user.
I have a project due soon. We have to write a program that asks for a year and prints out a calendar. We can only use one while, one for, and one switch loop. (and no arrays! ugh) Im having trouble figuring out how to print out the days of each month, starting with the first day of the first week, as most months will not start on Sunday.
import java.util.*;
import java.util.Calendar;
class Lab2 {
public static void main(String[] args) {
Scanner user = new Scanner(System.in);
System.out.print("What year do you want to view? ");
int year = user.nextInt();
System.out.printf("%12d\n", year);
System.out.println();
boolean leap = isLeap(year);
int firstDay = JulianDate(year);
monthLoop(year, firstDay, leap);
}
public static boolean isLeap(int year) {
boolean verdict = false;
if (year % 100 == 0 && year % 400 == 0) {
verdict = true;
}
if(year % 100 != 0 && year % 4 == 0) {
verdict = true;
}
return verdict;
}
public static int JulianDate(int year) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.DAY_OF_YEAR, 1);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
return dayOfWeek;
}
public static void monthLoop(int year, int firstDay, boolean leap) {
for(int i=1; i <= 12; i++) {
switch (i) {
case 1: System.out.printf("%13s\n", "January");
break;
case 2: System.out.printf("%13s\n", "February");
break;
case 3: System.out.printf("%12s\n", "March");
break;
case 4: System.out.printf("%12s\n", "April");
break;
case 5: System.out.printf("%11s\n", "May");
break;
case 6: System.out.printf("%11s\n", "June");
break;
case 7: System.out.printf("%11s\n", "July");
break;
case 8: System.out.printf("%13s\n", "August");
break;
case 9: System.out.printf("%14s\n", "September");
break;
case 10: System.out.printf("%13s\n", "October");
break;
case 11: System.out.printf("%14s\n", "November");
break;
case 12: System.out.printf("%14s\n", "December");
break;
}
System.out.println("S M Tu W Th F S");
}
}
}
You would get the day of the week, as in this post, of the first day of the month and then start the counter from there.
How to get the day of the week in Java
For instance, if the day of the week was 5, you would put 4 "blanks" before the first date. The trick is that when you are doing your mod, to determine if there should be a new line, it would be
(dayofMonth + firstDayOfWeekOfMonth) % 7
i am making a program that reads in the month 1-12 and the start day, 1-7 for sunday, monday, etc. it prints the first week fine but im having problems printing the rest of the days after the first week. it wont format the output to have a space between the rest of the days, only the first day after the first week.
side note: Keyboard is a class i have included in my project
heres my code:
import java.io.*;
public class CalendarMonth
{
static final int WEEK = 7;
public static void main(String[] args) throws IOException
{
String proceed;
char repeatCheck;
int days;
String leapYear;
char leapYearCheck;
int startDay;
do
{
days = getDays();
System.out.println(days);
System.out.println("Please enter a number 1-7 that the month starts on: (1 for sunday, 2 for monday, etc)");
startDay = Keyboard.readInt();
while(startDay < 1 || startDay > 7)
{
System.out.println("You did not enter a number 1-7, Try again: ");
startDay = Keyboard.readInt();
}
System.out.println(" s m t w th f sa");
printMonth(days,startDay);
System.out.println("\nWould you like to print another month?");
proceed = Keyboard.readString();
repeatCheck = proceed.charAt(0);
}while(repeatCheck == 'y');
}
public static int getDays() throws IOException
{
int month;
String leapYear;
int startDay;
int days = 0;
char leapYearCheck;
System.out.println("Please input a number 1-12 to print the corresponding month: ");
month = Keyboard.readInt();
while (month < 1 || month > 12)
{
System.out.println("You did not put a number 1-12, Try again: ");
month = Keyboard.readInt();
}
switch(month)
{
case 1: days = 31;
break;
case 2:
System.out.println("is it a leap year? ");
leapYear = Keyboard.readString();
leapYearCheck = leapYear.charAt(0);
while(leapYearCheck != 'y' && leapYearCheck != 'n')
{
System.out.println("you did not enter a yes or no answer, is it a leap year?");
leapYear = Keyboard.readString();
leapYearCheck = leapYear.charAt(0);
}
if (leapYearCheck == 'y')
{
days= 29;
}
else
{
days = 28;
}
break;
case 3: days = 31;
break;
case 4: days = 30;
break;
case 5: days = 31;
break;
case 6: days = 30;
break;
case 7: days = 31;
break;
case 8: days = 31;
break;
case 9: days = 30;
break;
case 10: days = 31;
break;
case 11: days = 30;
break;
case 12: days = 31;
break;
}
return days;
}
public static void printMonth(int days, int startDay)
{
int count;
count = startDay;
for (int counter = 1; counter <= 7; counter++)
{
if (counter < startDay)
{
System.out.print(" ");
count = count-1;
}
else
{
System.out.printf("%2d", count);
count++;
}
}
//int restOfTheMonth = (WEEK - startDay);
System.out.println();
for(int restOfTheMonth = count; restOfTheMonth <= days; restOfTheMonth++)
{
if (restOfTheMonth%WEEK==0)
{
System.out.println();
}
System.out.printf("%2d", restOfTheMonth);
}
}
}