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();
}
Related
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! :)
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};
}
Is this possible to achieve or have i wrongly understood this question?
This is the question:
Implement a class MyDate that has integer data members to store month, day,
and year. The class should have a three-parameter constructor that allows the
date to be set at the time a new MyDate object is created. If the user creates a
MyDate object without passing any arguments, or if any of the values passed
are invalid, the default values of 1, 1, 2001 (i.e., January 1, 2001) should be
used. The class should have member functions to print the date in the following
formats:
3/15/10
March 15, 2010
15 March 2010
Demonstrate the usage of class MyDate by writing a class TestMyDate with a
main method that declares an object of type MyDate and displays it using all
the 3 formats.
Input Validation: Only accept values between 1 and 12 for the month, between
1 and 31 for the day, and between 1950 and 2020 for the year.
I've implemented this question but i can't seem to validate user input when the value is inserted at the time a new object is created. How can i do this? Please don't tell me to do research because i have done it. If Google could provide me with the answer i wouldn't have come here. Please help me.
Here's my codes:
The MyDate class:
package Number1;
public class MyDate {
private int month;
private int day;
private int year;
public MyDate()
{
month = 1;
day = 1;
year = 2001;
}
public MyDate(int m,int d,int y)
{
this.month = m;
this.day = d;
this.year = y;
}
public int getMonth()
{
return month;
}
public int getDay()
{
return day;
}
public int getYear()
{
return year;
}
public void Format1()
{
int m,d,y,afterM;
m = getMonth();
d = getDay();
y = getYear();
afterM = y % 100;
System.out.println(""+m+"/"+d+"/"+afterM);
}
public void Format2()
{
int m,d,y;
String word = null;
m = getMonth();
d = getDay();
y = getYear();
switch(m)
{
case 1:
{
word = "January";
break;
}
case 2:
{
word = "February";
break;
}
case 3:
{
word = "March";
break;
}
case 4:
{
word = "April";
break;
}
case 5:
{
word = "May";
break;
}
case 6:
{
word = "June";
break;
}
case 7:
{
word = "July";
break;
}
case 8:
{
word = "August";
break;
}
case 9:
{
word = "September";
break;
}
case 10:
{
word = "October";
break;
}
case 11:
{
word = "November";
break;
}
case 12:
{
word = "December";
break;
}
default:
{
System.out.println("Please enter a number between 1-12");
break;
}
}
System.out.println(""+word+" "+d+","+y);
}
public void Format3()
{
int m,d,y;
String word = null;
m = getMonth();
d = getDay();
y = getYear();
switch(m)
{
case 1:
{
word = "January";
break;
}
case 2:
{
word = "February";
break;
}
case 3:
{
word = "March";
break;
}
case 4:
{
word = "April";
break;
}
case 5:
{
word = "May";
break;
}
case 6:
{
word = "June";
break;
}
case 7:
{
word = "July";
break;
}
case 8:
{
word = "August";
break;
}
case 9:
{
word = "September";
break;
}
case 10:
{
word = "October";
break;
}
case 11:
{
word = "November";
break;
}
case 12:
{
word = "December";
break;
}
default:
{
System.out.println("Please enter a number between 1-12");
break;
}
}
System.out.println(""+d+" "+word+" "+y);
}
}
The main TestMyDate:
package Number1;
public class TestMyDate {
public static void main(String[] args) {
MyDate D = new MyDate(7,23,2013);
D.Format1();
System.out.println();
D.Format2();
System.out.println();
D.Format3();
}
}
These codes only returns the dates in these different formats. Thanks for trying to help.
I think you can do the validation and throw new IllegalArgumentException("illegal date") in MyDate() to make all the client code strictly conform the rule:
public MyDate(int m,int d,int y)
{
// do some validate here
if (!validate(m, d, y))
throw new IllegalArgumentException("illegal date")
this.month = m;
this.day = d;
this.year = y;
}
private boolean validate(int m, int d, int y){
// use here as the central place of your validation (Format1(), Format2(), Format3(), ...)
}
I suggest you
input the values you need to read
validate the inputs are you go.
only once you have valid data create the object.
I suggest you don't use a class to input it's own values. This is making the class overly complicated.
I also suggest you use arrays instead of long switch statements. You can replace your switch statements with two lines of code.
You need to run your validation in the constructor before assigning them to the member variables. Your best bet would be to create private methods that return a bool so you can reuse the logic in the event that you add setters to those properties.
public MyDate(int m, int d, int y)
{
if (monthIsValid(m)) {
this.month = m;
}
if (dayIsValid(d)) {
this.day = d;
}
if (yearIsValid(y)) {
this.year = y;
}
}
Having the switch statement is fine, though I'd only have it in a single place, and call it from both Format methods.
In this code:
Can anyone explain me .. why we need to return "Error" ?
And in some integer methods (not in this code) .. why return 0 is used?
package chapter4;
import java.util.Scanner;
class DateThirdTry
{
private String month;
private int day;
private int year; //a four digit number.
public void setDate(int newMonth, int newDay, int newYear)
{
month = monthString(newMonth);
day = newDay;
year = newYear;
}
public void writeOutput()
{
System.out.println(month + " " + day + ", " + year);
}
public String monthString(int monthNumber)
{
switch (monthNumber)
{
case 1:
return "January";
case 2:
return "February";
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:
System.out.println("Fatal Error");
System.exit(0);
return "Error"; //to keep the compiler happy
}
}
}
class DateThirdTryDemo
{
public static void main(String[] args)
{
DateThirdTry date = new DateThirdTry( );
int year = 1882;
date.setDate(6, 17, year);
date.writeOutput( );
}
}
1) Java will give a compiler error if a function has an exit path that doesn't return a value. Not returning a value is illegal in Java. Arguably a Good Thing.
2) In this case, your function calls "System.exit()" instead of returning a value. You know the program isn't going to execute the 'return "Error"', but you need to add it to satisfy the compiler.
3) The appropriate thing to do, however, is to throw an exception.
It's easy, your method monthString() returns a... String:
public String monthString(int monthNumber)
So, you have to return a String, and not an int, so you can't return 0.
If your method was returning an int, you could return 0.
But, in your case, you should maybe throw an exception instead of returning "Error" and using System.exit() like that:
public String monthString(int monthNumber) throws IllegalArgumentException {
and throw it:
default:
System.out.println("Fatal Error");
throw new IllegalArgumentException("Incorrect month number");
Or even better, you can directly use what is provided by Java to implement your function:
public static String monthString(final int monthNumber) {
final Calendar c = Calendar.getInstance();
c.set(Calendar.MONTH, monthNumber-1);
return c.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.ENGLISH);
}
I'm working on a Java class for a Month object but it does not return the actual month, can you help?
Here is the Private methods class:
public class Month
{
private static int numInstantiated = 0;
private int monthNumber = 0;
public Month()
{
monthNumber = 1;
numInstantiated++;
}
public Month(int num)
{
monthNumber = num;
numInstantiated++;
}
public void setMonth(int newMonth)
{
monthNumber = newMonth;
}
public int getMonth()
{
return monthNumber;
}
public String toString()
{
switch(monthNumber)
{
case 1: return "January";
case 2: return "February";
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 "No month specified";
}
}
}
And here is the main:
import java.util.Scanner;
public class UseMonth
{
public static void main(String[] args)
{
Scanner kbd = new Scanner(System.in);
Month m1 = new Month();
Integer newMonth;
//kbd.nextLine();
System.out.print("Please enter a numeric representaion of the Month? (ex. 1 for January)");
newMonth = kbd.nextInt();
m1.setMonth(newMonth);
System.out.println("You entered: " + newMonth + ", which is the month of " + m1.getMonth());
}
}
Thanks in advance - Fred
Well, you're calling getMonth() which returns an int. You'll want to call m1.toString(), which returns the string representation you're trying to print.
This would be a perfect opportunity to use an enum:
enum Month {
January,
February,
March,
April,
May,
June,
July,
August,
September,
October,
November,
December;
public static Month get(int n) {
return Month.values()[n-1];
}
}
public void test() {
for (int i = 1; i <= 12; i++) {
System.out.println("Month " + i + " = " + Month.get(i));
}
}
try this..
System.out.println("You entered: " + newMonth + ", which is the month of " + m1.toString());
in your main class.
You have ovewritten the toString method. If you just call your getMonth method, this one does not call automatically the toString method, so it will return the number of the month.
If you want yo see the name of the month, you must do one of this two options:
Change your getMonth method:
public String getMonth()
{
return this.toString(monthNumber);
}
Or in your main method, change the System Out call:
System.out.println("You entered: " + newMonth + ", which is the month of " + m1.toString(m1.getMonth()));
Hope it helps!!
Replace the final line of your code with this :
System.out.println("You entered: " + newMonth + ", which is the month of " + m1.toString());
In your existing code, m1.getMonth() will return you the number of the month.
Using m1.toString() will give the respective String equivalent of the entered Integer number.
Hope this helps.
I think all the previous answers are correct and have provided you with a good feedback/answers. There's more than one way to skin a cat. So, I have cleaned up your code a and remove some of the unnecessary method and I have also tested the program to make sure it works for you. Here are the the two classes for you.
public class Month {
private static int numInstantiated = 0;
public Month() {
numInstantiated++;
getMonthTextual(numInstantiated);
}
public String getMonthTextual(int monthNumber) {
switch (monthNumber) {
case 1:
return "January";
case 2:
return "February";
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 "No month specified";
}
}
}
here is the main class:
import java.util.Scanner;
public class test {
public static void main(String[] args)
{
Scanner kbd = new Scanner(System.in);
Month m1 = new Month();
Integer newMonth;
//kbd.nextLine();
System.out.print("Please enter a numeric representaion of the Month? (ex. 1 for January)");
newMonth = kbd.nextInt();
System.out.println("You entered: " + newMonth + ", which is the month of " + m1.getMonthTextual(newMonth));
}
}