So I am kinda new to java and was given a program to do.
a. Create one or more arrays to hold the names of the months and the number of days in each month. Assume that February always has 28 days.
b. Display the contents of the array(s).
c. Ask the user for a number to represent the month: 1 = Jan, 2 = Feb, etc. Search for the corresponding month and display the name of the month and the number of days. If the number is not found, display an error message.
d. Ask the user for the name of a month. Search for the corresponding month and display the number of the month and the number of days. If the month is not found, display an error message.
I have done a-c but i am having trouble with d.
package array;
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
int [] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // Array holds number of days in month
String [] months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; // array holds months
for (int index = 0; index < months.length; index++) // loop to display number of days in month
{
System.out.println(months[index] + " has " + // displays number of days in month
days[index] + " days ");
}
Scanner keyboard = new Scanner(System.in); // creates scanner
System.out.println("Enter a number to represent the month");
int search = keyboard.nextInt(); // saves user value into search
search--; // subtracts 1 from user input to account for the index of 0
if(search > months.length)
System.out.println("Can not find number"); // yes if search is more then months display error
else
System.out.println( months[search] + " has " + days[search] + " days "); // no if search is less then months display contents
Scanner string = new Scanner(System.in); //creates new scanner
System.out.println("Enter the name of the month");
String input = string.nextLine(); // saves user strin in to input
for (int index = 0; index < months.length; index++) //loop to compare user input to months array
{
if(input.equals(months[index])) // yes display month and days
System.out.println(months[index] + " has " + // displays number of days in month
days[index] + " days ");
else
if(!(input.equals(months[index]))) // no display error
System.out.println("can not find month");
}
}
}
Its kinda hard to explain the problem but if you run it you will see when it asks the user to input the name of the month that is where the error occurs. Any help would be appreciated.