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};
}
Related
I am new to Java and I have a code to write, but I ran into a problem. The task says:
Write a Java application that reads an int value. If the int value is between 1-12, the corresponding string month will be displayed. Consider if the value entered is a string and if it corresponds to a month of the year, display the numeric value of the month.
I wrote the code until it displays the corresponding month to the read value, but I don't know how to read a string if I declared an integer as a variable which is read from the keyboard. Here's the code:
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
int num;
System.out.println("Enter a number between 1-12: ");
Scanner Obj= new Scanner(System.in);
num=Obj.nextInt();
switch(num)
{
case 1:
System.out.println("Month nr.1 is January");
break;
case 2:
System.out.println("Month nr.2 is February");
break;
case 3:
System.out.println("Month nr.3 is March");
break;
case 4:
System.out.println("Month nr.4 is April");
break;
case 5:
System.out.println("Month nr.5 is May");
break;
case 6:
System.out.println("Month nr.6 is June");
break;
case 7:
System.out.println("Month nr.7 is July");
break;
case 8:
System.out.println("Month nr.8 is August");
break;
case 9:
System.out.println("Month nr.9 is September");
break;
case 10:
System.out.println("Month nr.10 is October");
break;
case 11:
System.out.println("Month nr.11 is November");
break;
case 12:
System.out.println("Month nr.12 is December");
break;
default:
System.out.println("You entered an invalid number!");
}
Obj.close();
}
} ```
* I'm using Eclipse with Java SE11. *
I need some clues how could I read a string as well, to show the corresponding value of month. Thanks!
Instead of declaring an int to read the input declare a String.
String input = scanner.nextLine();
try {
int month = Integer.parseInt(input);
showMonthName(month);
} catch (NumberFormatException e) {
// If the input is not a number then exception would be thrown.
showMonthNumber(input);
}
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! :)
import java.util.Scanner;
public class DaysInMonth
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a year:")
int year = input.nextInt(); enter code here
System.out.print("Enter a month:");
int month = input.nextInt(); enter code here
int days = 0;
boolean isLeapYear = (year % 4 == 0 && year % 100 != 0)||(year % 400 == 0);
switch (month){
case 1:
days = 31;
break;
case 2:
if (isLeapYear)
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;
default:
String response = "Have a Look at what you've done and try again";
System.out.println(response);
System.exit(0);
}
String response = "There are " +days+ " Days in Month "+month+ " of Year " +year+ ".\n";
System.out.println(response); // new line to show the result to the screen.
}
}
Why can't I type in January to get the same output result if I type 1? It should print "There are 31 days in the month of January of Year 2018" I initialized the month so it should read January or any other month.
I know I have int but I am wondering how can I also use January for 1 to get the same output.
You can use Strings in a switch statement to check for several equivalent cases:
switch (monthInput.toLowerCase()) {
case "january":
case "jan":
case "1":
days = 31;
break;
case "february":
case "feb":
case "2":
days = isLeapYear ? 29 : 28;
break;
case "march":
case "mar":
case "3":
days = 31;
break;
// etc.
default:
System.out.println(monthInput + " is not a valid month");
input.close();
System.exit(0);
}
But this means you have to read your input as a String, not as an int...
Scanner input = new Scanner(System.in);
System.out.print("Enter a year:");
int year = input.nextInt(); // enter code here
input.nextLine(); // read the rest of the line (if any)
System.out.print("Enter a month:");
String monthInput = input.nextLine();
Note the use of input.nextLine(); after the .nextInt() — this is because the nextInt() call does not consume all of the input, it only reads the int that you typed for the Year, it does not read the newline (enter key), so you have to read that to be ready to read the next input, which is the month number or name.
I know I have int but I am wondering how can I also use January for 1 to get the same output.
A simple approach is to use name array
// before main.
static final String[] MONTH = "?,Jan,Feb,Mar,Apr,Jun,Jul,Aug,Sep,Oct,Nov,Dec".split(",");
// inside main
String monthStr = MONTH[month];
Add the full month names as needed.
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();
}
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));
}
}