How to make scanner read my boolean outcome? - java

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;
}
}
}

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 use strings as the same as inputting int?

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.

User input validation using While loop

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();
}

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");
}
}
}

Okay, so my code is compiled but the if/else statement is not working

I think it might be due the switch statement.
Do I have make the both them switch statements for them to work out.
import java.util.Scanner;
public class mylab
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int month;
int day;
String season= "seasons";
System.out.print("type a two digit month");
System.out.print(" and day");
month = in.nextInt();
day = in.nextInt();
String winter = " winter ";
String summer = " summer";
String spring = " spring";
System.out.print(" Month="+ month +" Day= "+day);
switch (month) {
case 1:
month = 1; System.out.println(" Winter");
break;
case 2:
month = 2; System.out.println(" Winter");
break;
case 3:
month= 3;System.out.println(" Winter");
break;
case 4:
month= 4;System.out.println(" Spring");
break;
case 5:
month = 5;System.out.println(" Spring");
break;
case 6:
month = 6 ;System.out.println(" Spring");
break;
case 7:
month = 7 ;System.out.println(" Summer");
break;
case 8:
month = 8;System.out.println(" Summer");
break;
case 9:
month = 9;System.out.println(" Summer");
break;
case 10:
month = 10;System.out.println(" Fall");
break;
case 11:
month = 11;System.out.println(" Fall");
break;
case 12:
month = 12;System.out.println(" Fall");
break;
}
How , do I make this part work with the switch statement
the pseudo code for this portion is If month is divisible by 3 and day >= 21, If season is "Winter", season = "Spring",Else if season is "Spring", season = "Summer",Else if season is "Summer", season = "Fall"
Else season = "Winter"
if (month % 3 == 0 && day >= 21)
{
if ( season.equals(winter) )
System.out.println(" Spring");
else if ( season.equals(spring) )
System.out.println ( "Summer" );
else if ( season.equals(summer) )
System.out.println ( " fall");
else if ( season.equals(winter) )
System.out.println( " winter");
}
}
}
This is how I'd probably write it (if I absolutely had to keep the switch and I didn't care to check user input):
import java.util.Scanner;
public class mylab {
public static void main(String[] args) {
int month, day;
Scanner in = new Scanner(System.in);
System.out.print("Type a two digit month: ");
month = in.nextInt();
System.out.print("Type a two digit day: ");
day = in.nextInt();
System.out.print(" Month="+ month +" Day= "+day+" ");
if(month%3==0 && day>=21) {
month++;
if(month>12) month=1;
}
switch (month) {
case 1: case 2: case 3: System.out.println("Winter"); break;
case 4: case 5: case 6: System.out.println("Spring"); break;
case 7: case 8: case 9: System.out.println("Summer"); break;
case 10: case 11: case 12: System.out.println("Fall"); break;
}
}
}

Categories

Resources