+ 1

How do I get the month when I input the number of the corresponding month?

Hi everyone so I'm new, and trying to learn Java. So I have to Write a program that prompts the user for one of the numbers 1, 2, 3, ..., 12 and outputs the corresponding month name January, February, March, ... , December. And this is what I have so far, but when I run it and want to get for example month nine I always get January. please help. And thank you so much. public class Months { private int monthNumber; private String monthString= "January "+ "February "+ "March "+ "April "+ "May "+ "June "+ "July "+ "August "+ "September "+ "October "+ "November "+ "December "; public Months(int m){ monthNumber=m; } public String getMonth(){ int first=0; // int last=10; // return monthString.substring(first,last).trim(); } } class TestMonths{ public static void main(String[] args){ java.util.Scanner sc = new java.util.Scanner(System.in); System.out.print("Enter a month number (1-12): "); int m=sc.nextInt(); Months mo = new Months(m); System.out.println("Month #"+m+" is "+mo.getMonth()); } }

19th Mar 2020, 12:26 AM
Marilyn Gutierrez Solis
Marilyn Gutierrez Solis - avatar
1 Odpowiedź
+ 1
Try using a switch method switch (usersInput) { case 1: System.out.print("January"); break; case 2: System.out.print("February"); break; .........and so on for every month Goodluck.
19th Mar 2020, 11:20 AM
Jason
Jason - avatar