User input validation using While loop - java

I am having trouble with this Java program validating user input using a while loop. I must use a while loop. The program works fine until the user enters a number that isn't valid which is when it prints Invalid number entered infinitely. Beginner level sorry, but Thank you for the help!
public class monthName {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
String[] monthName = { "January", "February", "March", "April", "May", "June", "July", "August", "September",
"October", "November", "December" };
// monthName[0]="January";
// monthName[1]="February";
// monthName[2]="March";
// monthName[3]="April";
// monthName[4]="May";
// monthName[5]="June";
// monthName[6]="July";
// monthName[7]="August";
// monthName[8]="September";
// monthName[9]="October";
// monthName[10]="November";
// monthName[11]="December";
int monthNumber = 0;
System.out.println("Enter a month number: ");
monthNumber = console.nextInt();
while (monthNumber > monthName.length || monthNumber < 1) {
System.out.println("Invalid number entered");
}
System.out.println("The Month is: " + monthName[monthNumber - 1]);
}
}
EDIT
After switching the while loop of the code to this:
It still does not give the month name
int monthNumber = 0;
System.out.println("Enter a month number: ");
monthNumber = console.nextInt();
while (monthNumber > monthName.length || monthNumber < 1) {
System.out.println("Invalid number entered");
System.out.println("Enter a month number: ");
monthNumber = console.nextInt();
}
System.out.println("The month is: " + monthName);
}
}

Because after you read the number, you start the loop based on value read, but never change the variable, so if while condition is true, it will be true forever. Add another call to nextInt(), like the following:
int monthNumber = 0;
System.out.println("Enter a month number: ");
monthNumber = console.nextInt();
while (monthNumber > monthName.length || monthNumber < 1) {
System.out.println("Invalid number entered");
System.out.println("Enter a month number: ");
monthNumber = console.nextInt();
}

Related

How do I format user input into a date variable?

How do i take the user inputted day, month and year then store in a dd-mm-yyyy format? I can get everything to work except combining them into a date and storing them in the startDate variable. I also don't think startMonth will be accessible as it's in a switch case but I'm very new to java and unsure.
public static void carBookingDates() {
int carNumber;
int startYear;
int startDay;
int startMonth;
int daysInMonth = 0;
int endYear;
int endMonth;
int endDay;
Scanner input = new Scanner(System.in);
System.out.println("To make a booking:");
System.out.printf(" Select a car number from the car list: ");
carNumber = input.nextInt();
System.out.println("");
System.out.println("Enter a booking start date.");
System.out.printf("Please enter the year - for example '2022': ");
startYear = input.nextInt();
while (startYear < 2022 || startYear > 2030) {
System.out.println("Invalid year, please try again: ");
System.out.printf("Please enter the year - for example '2022': ");
startYear = input.nextInt();
}
System.out.printf("Please enter the month - for example '6': ");
startMonth = input.nextInt();
while (startMonth < 1 || startMonth > 12) {
System.out.println("Invalid month, please try again: ");
System.out.printf("Please enter the month - for example '6': ");
startMonth = input.nextInt();
}
switch (startMonth) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
daysInMonth = 31;
break;
case 4:
case 6:
case 9:
case 11:
daysInMonth = 30;
break;
case 2:
if (((startYear % 4 == 0)
&& !(startYear % 100 == 0))
|| (startYear % 400 == 0)) {
daysInMonth = 29;
} else {
daysInMonth = 28;
}
break;
default:
System.out.println("Invalid month.");
break;
}
System.out.printf("Please enter the day number - for"
+ " example '18': ");
startDay = input.nextInt();
while (startDay > daysInMonth || startDay <= 0) {
System.out.println("Invalid day, plese try again");
System.out.printf("Please enter the day number - for"
+ " example '18': ");
startDay = input.nextInt();
LocalDate startDate() = LocalDate.parse(startDay + "-" + StartMonth "-" + startYear);
}
}
First of all, you can use the Java 8 Date Time API to get the number of days in a month instead of using a manual switch case for making the code more readable.
import java.time.YearMonth;
Then:
// 2021 is the year and 2 is the month
int daysInMonth = YearMonth.of(2021,2).lengthOfMonth());
Now to form the date in dd-mm-yyyy format :
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
Then:
// pass your date value here under LocalDate.of method
LocalDate.of(2021,2,16).format(DateTimeFormatter.ofPattern("dd-MM-yyyy"));

How to make scanner read my boolean outcome?

I am making a program with alot of boolean true or false statement, I want the output of the boolean to be read by scanner and want it as some kind of output, Is there way to do it
Ex:
if (day == 1){System.out.print("first");}
if (month == 1){System.out.println("Your birthday is " + day + " January");}
pretty much I ask the user to input an number and it will convert it to the actual month's name and it will tell them their birthday by converting numbers, but when I do the way I am its just going to print it out. I want to make Scanner read the input 1 as first and want it to write as "Your birthday is first January"
You can use a switch statement and set your response string based on the number they entered and use that in your print statement.
String response;
switch(day){
case 1: response = "first";
break;
case 2: response = "second";
break;
/*
And so on...
*/
}
Try with this approach:
public static void main(String[] args) {
final String[] months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
Scanner sc = new Scanner(System.in);
System.out.println("Type month: ");
int month = 0;
while(sc.hasNextInt()) {
month = sc.nextInt();
// get month from 1 to 12
if (month > 0 && month < 12) {
break;
} else {
System.out.println("Type valid month: ");
continue;
}
}
System.out.println("Type day: ");
while (sc.hasNextInt()) {
int day = sc.nextInt();
int numDays = 0;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
numDays = 31; break;
case 4:
case 6:
case 9:
case 11:
numDays = 30; break;
case 2: numDays = 28; break;
}
// get day taking under consideration amount of days in the month
if (day > 0 && day <= numDays) {
System.out.println("Your birthday is " + day + " " + months[month-1]);
return;
} else {
System.out.println("Type valid day: ");
continue;
}
}
}

Inserting a dash (-) when a value is missing

How do I get a '-' to appear on my calendar whenever the value for a day of week is empty?
Here is the code:
public static void printCalander(int month, int year) {
String[] monthNames = {"", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
//showing which month is being displayed on the yearly calendar
System.out.println(" " + monthNames[month] + " " + year);
System.out.println("Su Mo Tu We Th Fr Sa");
for (int index = 0; index < obj1; index++) {
System.out.print(" ");
}
//numDays is showing how many days are needed for the calendar following the user input
for (int count = 1; count <= numDays; count++) {
System.out.printf("%2d ", count);
//if the calendar reaches 7 numbers then it will take a new line
if (((count + obj1) % 7 == 0) || (count == numDays)) {
System.out.println("");
}
}//for
}//end of printCalendar
if i understand correctly u need to make an integer array for week days and use it like a controller like this:
String[] array = new String[7];
//take inputs like this:
for(int i = 0; i<7; i++) {
input = k.nextLine();
if(input.equals(""))
array[i] = "-";
continue;
}
array[i] = input;
}
or save inputs in a array and control it. if it has a null element change it to "-".

Issues finding errors with code please? Cant figure whats wrong

Public class SalesSummary {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//declarations
float month;
float salesAmt ;
final int SIZE = 12;
String[] MONTH = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
float[] sales = new float[SIZE];
char response;
float total;
float avrg;
do{
System.out.printIn ("Enter month");
month = input.nextFloat();
if (month > 1 || month < 12)
System.out.printIn ("Invalid month");
else
month = month - 1;
System.out.printIn ("Enter sales amount");
salesAmt = input.nextFloat();
sales[month] = (sales[month] + salesAmt);
System.out.printIn("Additional data (Y/N)?");
response = input.next().charAt(0);
total = (sales[0] + sales[1] + sales[2] + sales[3] + sales[4] + sales[5] + sales[6] + sales[7] + sales[8] + sales[9] + sales[10] + sales[11]);
avrg = (total / SIZE);
} while (response == 'y');
for (int x = 0; x < MONTH.length; ++x) {
System.out.println("Sales for " + MONTH[x] + " is: " + sales[x] + "Total is" + total + "Average is: " + avrg) ;
}
}
}
I was looking through the code and can't find why it isn't working. I believe it has something to do the with System.out.printIn() statements and the sales[month] = (sales[month] + salesAmt)
This code won't compile. Need to change the following for it to compile successfully at least:
We are using a float (month) variable as an array index, which is not a valid syntax. Need to change type of month to int.
After changing month to int, input.nextFloat(); needs to be changed to input.nextInt();
System.out.printIn needs to be changed to System.out.println
We can check it's behavior (and compare it with expected output) once it compiles and runs fine.

Make program that prints month name according to corresponding number shorter

This program asks a user to input any number equal to or between 1-12. It then converts the number to a message that will be printed (Copy the program to see it yourself). Is there a way to make the code shorter?
import javax.swing.JOptionPane;
public class NumOfMonth {
public static void main(String[] args) {
int num = Integer.parseInt (JOptionPane.showInputDialog ("Enter any number equal to or between 1-12 to display the month"));
switch (num)
{
case 1:
System.out.println ("The name of month number 1 is January");
break;
case 2:
System.out.println ("The name of month number 2 is February");
break;
case 3:
System.out.println ("The name of month number 3 is March");
break;
case 4:
System.out.println ("The name of month number 4 is April");
break;
case 5:
System.out.println ("The name of month number 5 is May");
break;
case 6:
System.out.println ("The name of month number 6 is June");
break;
case 7:
System.out.println ("The name of month number 7 is July");
break;
case 8:
System.out.println ("The name of month number 8 is August");
break;
case 9:
System.out.println ("The name of month number 9 is September");
break;
case 10:
System.out.println ("The name of month number 10 is October");
break;
case 11:
System.out.println ("The name of month number 11 is November");
break;
case 12:
System.out.println ("The name of month number 12 is December");
break;
default:
System.out.println ("You have entered an invalid number");
}
}
}
Yes, using DateFormatSymbols:
return new DateFormatSymbols().getMonths()[num - 1];
getMonths returns array of months strings..
I highly encourage you to check for bounds before accessing the array.
import javax.swing.JOptionPane;
public class NewClass {
public static void main(String[] args) {
String[] months = new String[]{
"",
"JAN",
"FEB",
"MAR",
"APR",
"MAY",
"JUN",
"JUL",
"AUG",
"SEP",
"OCT",
"NOV",
"DEC"
};
int num = Integer.parseInt(JOptionPane.showInputDialog("Enter any number equal to or between 1-12 to display the month"));
if (num >= 1 && num <= 12) {
System.out.println("Name of month is " + months[num]);
} else {
System.out.println("INVALID ENTRY");
}
}
}

Categories

Resources