I am trying to write a program that takes input from a user. The enter a number 1-12 and it returns the month January-December. I have to have all the months in one long string and then use a substring to return the corresponding month.
I am very confused as to how to get an int to correlate to a substring. I would appreciate some general guidelines for doing this. I'm not looking to have the whole program done for me.
Don't use substring(). If you have a csv of month names, use split() to turn the string into an array:
String months = "January,February,etc";
int choice; // 1-12
String monthName = months.split(",")[choice - 1];
Note that java arrays are zero-based, so you must subtract 1 from a 1-12 ranged number when used as an index.
Easier to read would be:
static String[] monthNames = "January,February,etc".split("");
then in your method:
String monthName = monthNames[choice - 1];
When you get the values of the month using your substring, store it in your array of String. And then get the 1 - 12 value by their indexes + 1.
Beside using Split you can use StringTokenizer to parse your string as well.
My Code:
int i = 1;
int month = 0;
while (i == 1) {
System.out.println("Enter your number ");
Scanner input = new Scanner(System.in);
month = input.nextInt();
if (month > 13 || month < 0) {
System.out.println("your number has to be between 1 and 12");
} else {
i = 2;
}
}
List<String> monthList = new ArrayList<>();
StringTokenizer st = new StringTokenizer("January February March April"
+ " May June July August September October November December");
while (st.hasMoreTokens()) {
monthList.add(st.nextToken(" "));
}
System.out.println("the month is " + monthList.get(month - 1));
My Output:
Enter your number
333
your number has to be between 1 and 12
Enter your number
3
the month is March
Related
I am very new to coding and I have a simple question. I want to input day, month and year inside a for loop and after inputting it I want to display all the inputted values on the same time. how to do it.kindly help me.
i have attached the code below.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
for(int i=0;i<n;i++) {
int day = in.nextInt();
String month = in.next();
int year = in.nextInt();
}}
//need to display the entire content from the for loop
//suppose if the n value is 3
//i will be giving 3 inputs
//10 jan 1998
//11 nov 2000
//12 dec 1995
//i want to print all at the same time
Kindly help me with it.
If I understood your question correctly and you just want to print your inputs, just add the following to the loop:
System.out.println(String.format("%d %s %d", day, month, year));
or otherwise, but not as pretty (at least in my opinion):
System.out.println(day + " " + day + " " + month + " " + year);
EDIT
As indicated, you want to print them all at the same time. To do so, you can just save them all in a list or an array for example like the following:
Before the loop:
String[] dates = new String[n];
In the loop:
dates[i] = String.format("%d %s %d", day, month, year);
And then go ahead and insert another loop to print the content of the array:
for(String date: dates){
System.out.println(dates[i]);
}
From what I have gathered, you are looking to set a number on how many dates you'd like the user to enter, take in that number of dates and then print out the dates after the user input.
Here is some basic code that will do that for you
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int numOfInputs = 3; //How many separate dates you would like to enter
int day[] = new int[numOfInputs]; //declaring an integer array day and setting the array size to the value of numOfInputs
String month[] = new String[numOfInputs]; //declaring a string array month and setting the array size to the value of numOfInputs
int year[] = new int[numOfInputs]; //declaring an integer array year and setting the array size to the value of numOfInputs
//get inputs
for(int i=0;i<numOfInputs;i++) {
System.out.println("Please enter a day");
day[i] = sc.nextInt();
System.out.println("Please enter a month");
month[i] = sc.next();
System.out.println("Please enter a year");
year[i] = sc.nextInt();
}
//print content
for(int i=0;i<numOfInputs;i++) {
System.out.println(day[i] + " " + month[i] + " " + year[i]);
}
//close scanner
sc.close();
}
Let me know if this doesn't answer your question or if you need any clarification.
I have an assignment for a class I'm taking in which I have to make a Java console application, and it involves asking the user for a date, parsing that date, and working out what day of the month that date starts on. I have to then print out a calendar to look like this:
Calendar for September 2016
Su Mo Tu We Th Fr Sa
- - - - 1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 -
I have the date, I have the number of the day that the date starts on, (eg. Day= 1 (Monday), Day= 2(Tuesday), etc.)
Now, I can use a very messy looking switch statement with nested if statements that says, depending on the value of Day, and the number of days in that month, print out this pre-made calendar, and I can just pre-make a calendar for every eventual combination of Day and number of days in that month. But I don't want to do that, and I can't figure out an easier way of doing it. Has anybody got any ideas of a tidier, more succinct way of doing it? Would it be something involving 2d arrays?
PS. I'm not allowed to use any date-based library classes available in Java.
well you can use this if you change your mind
public static void main(String args [])
{
// type MM yyyy
Scanner in = new Scanner(System.in);
System.out.print("Enter month and year: MM yyyy ");
int month = in.nextInt();
int year = in.nextInt();
in.close();
// checks valid month
try {
if (month < 1 || month > 12)
throw new Exception("Invalid index for month: " + month);
printCalendarMonthYear(month, year);}
catch (Exception e) {
System.err.println(e.getMessage());
}
}
private static void printCalendarMonthYear(int month, int year) {
Calendar cal = new GregorianCalendar();
cal.clear();
cal.set(year, month - 1, 1); // setting the calendar to the month and year provided as parameters
System.out.println("Calendar for "+ cal.getDisplayName(Calendar.MONTH, Calendar.LONG,
Locale.US) + " " + cal.get(Calendar.YEAR));//to print Calendar for month and year
int firstWeekdayOfMonth = cal.get(Calendar.DAY_OF_WEEK);//which weekday was the first in month
int numberOfMonthDays = cal.getActualMaximum(Calendar.DAY_OF_MONTH); //lengh of days in a month
printCalendar(numberOfMonthDays, firstWeekdayOfMonth);
}
private static void printCalendar(int numberOfMonthDays, int firstWeekdayOfMonth) {
int weekdayIndex = 0;
System.out.println("Su MO Tu We Th Fr Sa"); // The order of days depends on your calendar
for (int day = 1; day < firstWeekdayOfMonth; day++) {
System.out.print(" "); //this loop to print the first day in his correct place
weekdayIndex++;
}
for (int day = 1; day <= numberOfMonthDays; day++) {
if (day<10) // this is just for better visialising because unit number take less space of course than 2
System.out.print(day+" ");
else System.out.print(day);
weekdayIndex++;
if (weekdayIndex == 7) {
weekdayIndex = 0;
System.out.println();
} else {
System.out.print(" ");
}}}
My code needs to calculate the cost of ISP service via 3 different questions.
choice of package (1,2,3)
Which month it is: (1-12)
How many hours used:(x)
I broke the months into 3 separate arrays. One for Feb. with 28 days, one for months with 30 days and one with months that have 31 days. I need to check the number of hours entered and make sure that it does not exceed the amount of hours that are in whichever month they have chosen. I have started to with this:
import java.util.Scanner; //Needed for the scanner class
public class ISP_Cost_Calc
{
public static void main(String[] args)
{
String input; //To hold users input.
char selectPackage; //To hold Internet Package
double hourUsage, totalCharges, addCharges; //Variables
Scanner keyboard = new Scanner(System.in); //Create a Scanner object to collect keyboard input.
int[] twentyeightArray; //List of months with 28 days (that's what the te is for)
twentyeightArray = new int[1]; //Make room for one integer in list
twentyeightArray[0] = 2; //Set the one integer in this list to month number 2
int[] thirtyArray; //List of months with 30 days.
thirtyArray = new int[4];
thirtyArray[0] = 4;
thirtyArray[1] = 6;
thirtyArray[2] = 9;
thirtyArray[3] = 11;
int[] thiryoneArray; //List of months with 31 days.
thiryoneArray = new int[7];
thiryoneArray[0] = 1;
thiryoneArray[1] = 3;
thiryoneArray[2] = 5;
thiryoneArray[3] = 7;
thiryoneArray[4] = 8;
thiryoneArray[5] = 10;
thiryoneArray[6] = 12;
//Prompt the user to select a Internet Package.
System.out.print("Enter your plan (1, 2, 3):");
input = keyboard.nextLine();
selectPackage = input.charAt(0);
//Prompt the user for the month.
System.out.print("Enter your month number (1-12):");
input = keyboard.nextLine();
char monthNum = input.charAt(0);
//Prompt the user for how many hours used.
System.out.print("Enter your hours:");
input = keyboard.nextLine();
hourUsage = Double.parseDouble(input);
//Display pricing for selected package...
switch (selectPackage)
{
case '1':
if (hourUsage > 10)
{
addCharges = hourUsage - 10;
totalCharges = (addCharges * 2.0) + 9.95;
System.out.println("You have used " + hourUsage + " hours and your total is $" + totalCharges + " per month. ");
}
else
{
System.out.println("Your total is $9.95 per month.");
}
break;
case '2':
if (hourUsage > 20 )
{
addCharges = hourUsage - 20;
totalCharges = (addCharges * 1.0) + 13.95;
System.out.println("You have used " + hourUsage + " and your total is $" + totalCharges + " per month.");
}
else
{
System.out.println("Your total is $13.95 per month.");
}
break;
case '3':
System.out.println("Your total is $19.95 per month.");
break;
default:
System.out.println("Invalid Choice.");
}
}
}
So I just need advice with how to incorporate this into my if statements.
Thank you
Instead of using separate arrays to implement your month. You can do this:
int[] month = {31,28,31,30,31,30,31,31,30,31,30,31};
int[] monthLeapYear = {31,29,31,30,31,30,31,31,30,31,30,31};
You can check whether a given year is a leap year first, then choose the right array to use for the month. This way you only need 2 arrays - ever.
and you may have something like this to help you. I also advise you to create some methods in your implementation to modularize your program.
public static Boolean isLeapYear(int year)
{
if(year % 4 == 0 && year % 100 != 0)
return true;
return false;
}
The array is by index 0 - 11. That be can be over come by doing this:
//Let say your current month is 1-12
month[currentMonth-1]
Alternatively add 1 element to your array (so that the elements tally now):
int[] month = {0,31,28,31,30,31,30,31,31,30,31,30,31};
It may be easier if instead of using seperatre arrays for different numbers of days, you use an enum of Months which contains the number of days and the number of hours.
public enum Month {
JANUARY(31),FEBRUARY(28),MARCH(31),APRIL(30),MAY(31),JUNE(30),JULY(31),AUGUST(30),SEPTEMBER(30),OCTOBER(31),
NOVEMBER(30),DECEMBER(31);
private int hours;
private Month(int days){
hours = days*24;
}
public int getHours(){
return hours;
}
}
Using something like that would cut down on the unnecessary array use and combine everything into a single class. This would make it a lot easier to get the number of days and hours in each month.
Instead of creating multiple arrays, just use one array like:
month[0] = 31;
month[1] = 28;//what if leap year?
month[2] = 31;
//and so on
Then you could do something like:
int monthNumber = monthNum - 48;
if (hours > month[monthNumber - 1] * 24) {
//do something
} else {
//else do another thing
}
This is insane.
What is going to happen in 2016 when February will have 29 days instead of 28 days?
Stop using integers to represent hours. Use proper data types like DateTime and TimeSpan.
Get the DateTime at 00:00 of the 1st day of the selected month,
then get the DateTime at 00:00 of the 1st day of the next month,
then calculate the difference of these two to obtain a TimeSpan holding the duration of the selected month.
Then convert your hours to a TimeSpan and compare this against the duration of the selected month.
This will tell you whether the entered number of hours fits within the selected month.
To check conditions based on your months.You can use contains method of arraylist by converting array into arraylist as
Arrays.asList(your1stArray).contains(yourChar)
in your char just add the input no of the month
for eg:
switch (monthNum )
{
case '1':
if (Arrays.asList(your1stArray).contains(yourChar)){
//code goes here
}
case '1':
if (Arrays.asList(your2ndArray).contains(yourChar)){
//code goes here
}
)
)
I Have been playing with this for while, and I can not seem to get my mind around how I can get this task accomplished.
My task :
I need get the last two digits of a year that a user has entered.
Example :
A user enters the July 2 , 2014; I need to get the last two digits of year 2014 which is "14" and divide it by 4. This will give me 3.5; however I will disregard the ".5" and just keep the 3.
Research :
I have been reading my Textbook, and seen one approach that I may be able to use which includes the string builder class. However my book has a very brief description and shows no example which I can constructively use to accomplish me task.
Progress:
This is what I have so far, it is basically a template of how I want my program; I just need some help getting the last 2 digits of a year.
public class DateCalc
{
public static void main (String[] args)
{
String month;
int day;
int year;
Scanner keyboard = new Scanner(System.in);
// receiving input
System.out.print( "Please Enter The Month Of The Date : ");
month = keyboard.nextLine();
// receiving input
System.out.print( "Please Enter The Day Of The Date : ");
day = keyboard.nextInt();
// receiving input
System.out.print( "Please Enter The Year OF The Date : ");
year = keyboard.nextInt();
switch(month)
{
// keys are numbered indexes that I need for this, please disregard
case "January" :
int janKey = 1;
break;
case "February":
int febKey = 4;
break;
case "March":
int marKey = 4;
break;
case "April":
int aprKey = 0;
break;
case "May":
int maykey = 2;
break;
case "June":
int junKey = 5;
break;
case "July":
int julKey = 0;
break;
case "August":
int augKey = 3;
break;
case "September":
int septKey = 6;
break;
case "October":
int octKey = 1;
break;
case "November":
int novKey = 4;
break;
case "December":
int decKey = 4;
break;
// IN MY DEFUALT CASE " inputValidation " WILL BE EXECUTED
default:
JOptionPane.showMessageDialog(null," Invalid Entry Please Try Again " );
}
}
}
You could do something like String yearString = Integer.toString(year).substring(2), which will first convert the integer to a string, then get the substring consisting of everything after the second character. Then to turn it back into an integer, try int yearInt = Integer.parseInt(yearString)
IMHO the cleaner option would be to convert the day,month and year into a Calendar. And then get the two digit year from the calendar.
Something like this:
Calendar cal = Calendar.getInstance();
cal.set(year, month, day);
SimpleDateFormat sdf = new SimpleDateFormat("yy"); // Just the year, with 2 digits
String formattedDate = sdf.format(Calendar.getInstance().getTime());
System.out.println(formattedDate);
One thing you can do is mod the year by 100 to get the last 2 digits. Then you can do whatever math you want with it.
This can be extended to get an arbitrary number of digits; modding a number by 10^n yields the last n digits of the number.
Edit because I was stupid and thought year was a String
String date = "July 2 , 2013";
String year = ""+ date.charAt(date.length()-2) + date.charAt(date.length()-1);
System.out.println(year);
int year2 = Integer.parseInt(year);
System.out.println(year2);
I have a java programming assignment where you have to input a date on a single line and it gives you a numerology (horoscope-like) report based on the date. It is assumed that the user will enter a formatted date, separated with spaces.
I can retrieve the month, day, and year of the input by using in.nextInt(). However, I also have to check that the user used a correct separating character for each part of the date, which means I just have to check whether the user used forward slashes.
When looking at my code below, I currently use charAt() to find the separating characters. The problem is that the date won't always be 14 characters long. So a date in the form of 10 / 17 / 2004 is 14 characters long, but a date of 4 / 7 / 1992 is only 12 characters long, meaning that "slash1" won't always be in.charAt(3), in the latter situation it would be in.charAt(2).
Does java have a method that allows something like in.nextChar()? I know that it doesn't, but how could I just find a next character in the date?
EDIT: I forgot to reflect this originally, but my professor said that we are NOT allowed to use the String.split() method, for some reason. The thing is, I get the month, day, and year perfectly fine. I just need to check that the person used a forward slash to separate the date. If a dash is entered, the date is invalid.
public void getDate()
{
char slash1, slash2;
do
{
System.out.print("Please enter your birth date (mm / dd / yyyy): ");
Scanner in = new Scanner(System.in);
String date = in.nextLine();
month = in.nextInt();
day = in.nextInt();
year = in.nextInt();
slash1 = date.charAt(3);
slash2 = date.charAt(8);
} while (validDate(slash1, slash2) == false);
calcNum();
}
you could consider to split the input date string with " / ", then you get a String array. the next step is converting each string in that array to int.
I would use Scanner just to get a line. Then split() the line on whitespace and check the fields:
import java.util.Scanner;
import java.util.regex.Pattern;
public class GetDate {
int month, day, year;
public static void main(String[] args)
{
GetDate theApp = new GetDate();
theApp.getDate();
}
public void getDate()
{
String date;
do
{
System.out.print("Please enter your birth date (mm / dd / yyyy): ");
Scanner in = new Scanner(System.in);
date = in.nextLine();
} while (validDate(date) == false);
calcNum();
}
boolean validDate(String date)
{
// split the string based on white space
String [] fields = date.split("\\s");
// must have five fields
if ( fields.length != 5 )
{
return false;
}
// must have '/' separators
if ( ! ( fields[1].equals("/") && fields[3].equals("/") ) )
return false;
// must have integer strings
if ( ! ( Pattern.matches("^\\d*$", fields[0]) &&
Pattern.matches("^\\d*$", fields[2]) &&
Pattern.matches("^\\d*$", fields[4]) ) )
return false;
// data was good, convert strings to integer
// should also check for integer within range at this point
month = Integer.parseInt(fields[0]);
day = Integer.parseInt(fields[2]);
year = Integer.parseInt(fields[4]);
return true;
}
void calcNum() {}
}
Rather than thinking about what characters are used as separators, focus on the content you want, which is digits.
This code splits on non digits, do it doesn't matter how many digits are in each group or what characters are used as separators:
String[] parts = input.split("\\D+");
It's also hardly any code, so there's much less chance for a bug.
Now that you have the numerical parts in the String[], you can get on with your calculations.
Here's some code you could use following the above split:
if (parts.length != 3) {
// bad input
}
// assuming date entered in standard format of dd/mm/yyyy
// and not in retarded American format, but it's up to you
int day = Integer.parseInt(parts[0];
int month = Integer.parseInt(parts[1];
int year = Integer.parseInt(parts[2];
Look ahead in the stream to make sure it contains what you expect.
private static final Pattern SLASH = Pattern.compile("\\s*/\\s*");
static SomeTypeYouMadeToHoldCalendarDate getDate() {
while (true) { /* Might want to give user a way to quit. */
String line =
System.console().readLine("Please enter your birth date (mm / dd / yyyy): ");
Scanner in = new Scanner(line);
if (!in.hasNextInt())
continue;
int month = in.nextInt();
if (!in.hasNext(SLASH)
continue;
in.next(SLASH);
...
if (!validDate(month, day, year))
continue;
return new SomeTypeYouMadeToHoldCalendarDate(month, day, year);
}
}
This uses Scanner methods to parse:
import java.util.Scanner;
import java.util.InputMismatchException;
public class TestScanner {
int month, day, year;
public static void main(String[] args)
{
TestScanner theApp = new TestScanner();
theApp.getDate();
theApp.calcNum();
}
public void getDate()
{
int fields = 0;
String delim1 = "";
String delim2 = "";
Scanner in = new Scanner(System.in);
do
{
fields = 0;
System.out.print("Please enter your birth date (mm / dd / yyyy): ");
while ( fields < 5 && in.hasNext() )
{
try {
fields++;
switch (fields)
{
case 1:
month = in.nextInt();
break;
case 3:
day = in.nextInt();
break;
case 5:
year = in.nextInt();
break;
case 2:
delim1 = in.next();
break;
case 4:
delim2 = in.next();
break;
}
}
catch (InputMismatchException e)
{
System.out.println("ERROR: Field " + fields + " must be an integer");
String temp = in.nextLine();
fields = 6;
break;
}
}
} while ( fields != 5 || validDate(delim1, delim2) == false);
in.close();
System.out.println("Input date: " + month + "/" + day + "/" + year);
}
boolean validDate(String delim1, String delim2)
{
if ( ( ! delim1.equals("/") ) || ( ! delim2.equals("/") ) )
{
System.out.println("ERROR: use '/' as the date delimiter");
return false;
}
if ( month < 1 || month > 12 )
{
System.out.println("Invalid month value: " + month);
return false;
}
if ( day < 1 || day > 31 )
{
System.out.println("Invalid day value: " + day);
return false;
}
if ( year < 1 || year > 3000 )
{
System.out.println("Invalid year: " + year);
return false;
}
return true;
}
void calcNum()
{
}
}