No output is coming out after I input two values - java

I can't seem to get the season to appear when I input a month and a day via the Scanner entity. I have tried many diferent methods, though none of them seem to be working. The code is shown below.
public class Lab7Smalls {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
private int month = 0;
private int day = 0;
String season = "";
String winter = "winter";
String spring = "spring";
String summer = "summer";
String fall = "fall";
System.out.print("Enter a month: ");
month = scan.nextInt();
System.out.print("Enter a day: ");
day = scan.nextInt();
if (month < 0 || month > 12) System.out.println("Not correct");
if(month <= 3){
season = winter;
}
else if(month <= 6){
season = spring;
}
else if(month <= 9){
season = summer;
}
else if(month <= 12){
season = fall;
}
if(month % 3 == 0 && day >= 21){
if(season.equals(winter)){
season = spring;
}
else if(season.equals(spring)){
season = summer;
}
else if(season.equals(summer)){
season = fall;
}
else if(season.equals(winter)){
season = winter;
}
System.out.println("Season: " + season);
}
}
}
The example for the output:
Enter a month: 1
Enter a day: 28

Sorry but this was a little long for a comment,
The System.out.println command is inside if(month % 3 == 0 && day >= 21){....} block, you have entered 1 for the month and as 1%3=1 so of course that if block will not executed and you will see nothing in output, you'll see something if and only if your input data meets the condition of if statement

If the month % 3 != 0 and the day < 21, nothing happens, because there is no else statement. Your code will only print the season if the month % 3 == 0 and the day >=21. You have two options:
The easier option: Move println outside of the if statement.
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int month;
int day;
String season = "";
System.out.print("Enter a month: ");
month = scan.nextInt();
System.out.print("Enter a day: ");
day = scan.nextInt();
String winter = "winter";
String spring = "spring";
String summer = "summer";
String fall = "fall";
if(month <= 3){
season = winter;
}
else if(month <= 6){
season = spring;
}
else if(month <= 9){
season = summer;
}
else if(month <= 12){
season = fall;
}
if(month % 3 == 0 && day >= 21){
if(season.equals(winter)){
season = spring;
}
else if(season.equals(spring)){
season = summer;
}
else if(season.equals(summer)){
season = fall;
}
else if(season.equals(winter)){
season = winter;
}
}
System.out.println("Season: " + season);
}
Option two: Add an else statement. Don't know why you would want to do this, but I'll put it here anyways.
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int month;
int day;
String season = "";
System.out.print("Enter a month: ");
month = scan.nextInt();
System.out.print("Enter a day: ");
day = scan.nextInt();
String winter = "winter";
String spring = "spring";
String summer = "summer";
String fall = "fall";
if(month <= 3){
season = winter;
}
else if(month <= 6){
season = spring;
}
else if(month <= 9){
season = summer;
}
else if(month <= 12){
season = fall;
}
if(month % 3 == 0 && day >= 21){
if(season.equals(winter)){
season = spring;
}
else if(season.equals(spring)){
season = summer;
}
else if(season.equals(summer)){
season = fall;
}
else if(season.equals(winter)){
season = winter;
}
System.out.println("Season: " + season);
}else{
System.out.println("Season: " + season);
}
}

Related

How do i get my new value to go back through the if statements

I'm trying to get the amount of days until the meeting to go back and print out the day the new meeting is on but I keep getting an integer instead of the string.
import java.util.Scanner;
public class NextMeeting {
public static void main(String [] args) {
int day, daysToMeeting = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the day of the week 0-6: ");
day = scan.nextInt();
System.out.println("Enter the days to meeting: ");
daysToMeeting = scan.nextInt();
if (day == 0) {
System.out.println("Today is Sunday");
} else if (day == 1) {
System.out.println("Today is Monday");
}
else if (day == 2) {
System.out.println("Today is Tuesday");
}
else if (day == 3) {
System.out.println("Today is Wednesday");
}
else if (day == 4) {
System.out.println("Today is Thursday");
}
else if (day == 5) {
System.out.println("Today is Friday");
}
else if (day == 6) {
System.out.println("Today is Saturday");
}
System.out.println("Today is: " + day);
if( daysToMeeting >= 6) {
day = daysToMeeting - 7;
}
else {
day = day + 6;
}
System.out.println("Days to the meeting is " + daysToMeeting + " +days.");
System.out.println("Meeting day is : " + Integer.toString(day));
}
}
The output for days is still 3 but we need to get it to print out Wednesday. I don't know how to make that happen.
You can use DayOfWeek enum.
System.out.println("Meeting day is : " + DayOfWeek.of(day).toString());
You can also remove nested if-else statement and use DayOfWeek enum to display "Today is xyz-day".
You are printing out integers because day is an int. It may be inefficient but an easy fix is to create a String variable and in another if-statement block below the daysToMeeting if-else block, assign the String to each corresponding integer, such as
String meetingDay;
if(day == 1){
meetingDay = "Monday";
}
and then print out using the String variable.
System.out.println("Meeting day is : " + meetingDay);
Just create a method which will return the day of week String by passing the day int. Then print the result.
public String intToDayName(int day) {
if(day > 6) {
day = day % 7;
}
if (day == 0) {
return "Sunday";
} else if (day == 1) {
return "Monday";
}
else if (day == 2) {
return "Tuesday";
}
else if (day == 3) {
return "Wednesday";
}
else if (day == 4) {
return "Thursday";
}
else if (day == 5) {
return "Friday";
}
else if (day == 6) {
return "Saturday";
}
return "Error";
}
calling it in your prints:
System.out.println("Meeting day is : " + intToDayName(daysToMeeting));
System.out.println("Today is " + intToDayName(day));
If you actually want your code to go back and print the first if-else statements then I suggest looping.

How do I add error handling to my code?

I'm trying to make it so the user has 3 chances to enter correct input, and after the 3rd try the program should close and I'll give a custom String. If at any point they enter valid data the program should execute. I would like to add error handling to the code:
import java.util.Scanner;
{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int month, day; String season = null;
System.out.print("Enter Month & Day: ");
month = in.nextInt(); day = in.nextInt();
if(1 <= month && month <= 3){
season = "Winter";
if((month == 3) && (21 <= day))
season = "Spring";
} else if (4 <= month && month <=6){
season = "Spring";
if((month == 6) && (21 <= day))
season = "Summer";
} else if (7 <=month && month <=9){
season = "Summer";
if((month == 9) && (21 <= day))
season = "Fall";
} else if (10 <= month && month <= 12){
season = "Fall";
if((month == 12) && (21 <= day))
season = "Winter";
}
System.out.println(season);
}
}
Something like this might help you. Code is self explanatory.
private static final int RETRY_COUNT = 3
retryCount = 0
boolean invalid = true;
while(invalid && retryCount++ < RETRY_COUNT){
try{
invalid = false;
Scanner sc = new Scanner(System.in)
.
.
.
}catch(Exception e){
invalid = true;
}
}

Why doesn't my date validation code work?

my code doesn't return any value and i have no idea why. My assignment requires me to write a code that accepts date in mm/dd/yyyy format and im required to put leap year in. The problem is, i dont get back any input. Im an amateur ad i dont know what is wrong. Im also allowed to use Case statment but I'm not sure how to implement case.
import java.util.Scanner;
public class Question1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in).useDelimiter("/");
System.out.println("Please enter a date in mm/dd/yyyy format: ");
String mm = sc.next();
String dd = sc.next();
String yyyy = sc.next();
int month = Integer.parseInt(mm);
int day = Integer.parseInt(dd);
int year = Integer.parseInt(yyyy);
if (month <= 0 || month>12)
{
System.out.println("invalid month ");
}
if (year%4 != 0 || month == 02 || day >= 29)
{
System.out.println("invalid date");
}
if (month == 4 || month == 6 || month == 9 || month == 11 || day >= 31)
{
System.out.println("Invalid day");
}
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12 || day >=32 )
{
System.out.println("Invalid day");
}
else
{
System.out.println("Valid date");
}
}
}
The code sets the delimiter to /. Then you enter something like 12/25/2016. The first sc.next() call gets the 12. The second one gets the 25. The third... waits, because it doesn't see another / so it doesn't know you're done. If you typed 12/25/2016/ with your current code, it would at least give output, even if that output isn't correct yet.
you want to use switch case then go through the below code:
import java.util.Scanner;
public class Question1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in).useDelimiter("/");
System.out.println("Please enter a date in mm/dd/yyyy/ format: ");
String mm = sc.next();
String dd = sc.next();
String yyyy = sc.next();
int month = Integer.parseInt(mm);
int day = Integer.parseInt(dd);
int year = Integer.parseInt(yyyy);
boolean valid = isValidDate(day,month,year);
if (valid == true)
{
System.out.println("Date is Valid");
}
else
{
System.out.println("Date is InValid");
}
}
public static boolean isValidDate(int day, int month ,int year)
{
boolean monthOk = (month >= 1) && (month <= 12);
boolean dayOk = (day >= 1) && (day <= daysInMonth(year, month));
return (monthOk && dayOk);
}
private static int daysInMonth(int year, int month) {
int daysInMonth;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10: // go through
case 12:
daysInMonth = 31;
break;
case 2:
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) {
daysInMonth = 29;
} else {
daysInMonth = 28;
}
break;
default:
// returns 30 even for nonexistant months
daysInMonth = 30;
}
return daysInMonth;
}
}
take input as 12/25/2016/, not this 12/25/2016.
Here is something to get you started:
final String DELIMITER = "/";
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a date in mm/dd/yyyy format:\n ");
String date = sc.next();
sc.close();
String[] dateParts = date.split(DELIMITER);
//check : if dateParts size is not 3 ....something is wrong
String mm = dateParts[0];
String dd = dateParts[1];
String yyyy = dateParts[2];
System.out.println(mm+" "+ dd +" "+ yyyy);
It seems you have put else in wrong place. Suppose you second condition is getting correct and all other false, then also your program will show it as valid date and same on the opposite side.
For example, say day is 30 for any date, then it will satisfy second condition and it will show you "Invalid date".
You should write if else as follows.
If{
If{
If{
}
}
}else{
}
All if must be in a nested if and then else. Your if else sequence is wrong.

JAVA Find day of the week from user entered date [duplicate]

This question already has answers here:
java get day of week is not accurate
(3 answers)
Closed 6 years ago.
I have this code which is built to find day of the week when user enters date but currently it's not working as expected.
Also, I need to help with setting up loop to ask question again and again until user press "Control + Z" to exit.
Can anyone check and point me out issues. Also help with loop.
import java.util.Calendar;
import java.util.Scanner;
public class CalendarProject {
#SuppressWarnings({ "resource" })
public static void main(String[] args) {
Calendar c = Calendar.getInstance();
Scanner input = new Scanner (System.in);
//Enter the Day
System.out.println("Enter the day in number:");
int day1= input.nextInt( );
//Enter the Month
System.out.println("Enter the Month in number");
int month= input.nextInt( );
//Enter the Year
System.out.println("Enter the Year in number format");
int year= input.nextInt( );
//Display the day
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
System.out.println(String.format("%d/%d/%d",day1,month,year));
System.out.println(c.get(Calendar.DAY_OF_WEEK));
if (dayOfWeek == Calendar.SUNDAY) {
System.out.println("Sunday");
}
else if (dayOfWeek == Calendar.MONDAY) {
System.out.println("Monday");
}
else if (dayOfWeek == Calendar.TUESDAY) {
System.out.println("Tuesday");
}
else if (dayOfWeek == Calendar.WEDNESDAY) {
System.out.println("Wednesday");
}
else if (dayOfWeek == Calendar.THURSDAY) {
System.out.println("Thursday");
}
else if (dayOfWeek == Calendar.FRIDAY) {
System.out.println("Friday");
}
else if (dayOfWeek == Calendar.SATURDAY) {
System.out.println("Saturday");
}
}
}
1.You never set the input date in Calender object,hence it will never work as desired. So you need to use c.setTime(date); Here date is Date object.
2. For loop, you can use do while loop to ask user again and again.
Following is your modified code
public static void main(String[] args) {
Calendar c;
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Scanner input = new Scanner (System.in);
try {
do{
System.out.println("Enter the day in number:");
int day1= input.nextInt();
//Enter the Month
System.out.println("Enter the Month in number");
int month= input.nextInt( );
//Enter the Year
System.out.println("Enter the Year in number format");
int year= input.nextInt( );
Date date = formatter.parse((String.format("%d/%d/%d",day1,month,year)));
System.out.println(date);
c= Calendar.getInstance();
c.setTime(date);
int day = c.get(Calendar.DAY_OF_WEEK);
if (day == Calendar.SUNDAY) {
System.out.println("Sunday");
}
else if (day == Calendar.MONDAY) {
System.out.println("Monday");
}
else if (day == Calendar.TUESDAY) {
System.out.println("Tuesday");
}
else if (day == Calendar.WEDNESDAY) {
System.out.println("Wednesday");
}
else if (day == Calendar.THURSDAY) {
System.out.println("Thursday");
}
else if (day == Calendar.FRIDAY) {
System.out.println("Friday");
}
else if (day == Calendar.SATURDAY) {
System.out.println("Saturday");
}
System.out.println("To exit press CTRL+Z(Windows) or CTRL+D(LINUX), or any key to continue");
input.nextLine();
}while (input.hasNextLine());
}catch(NoSuchElementException n){
System.out.println("NoSuchElementException");
}catch(ParseException pe){
System.out.println("invalid date");
}finally {
input.close();
System.out.println("exiting");
}
}
3. If you are using Java 8, you can get rid of all if else blocks by using java.time.DayOfWeek Enum. Just replace all your if else by following lines
DayOfWeek dayOfWeek = DayOfWeek.of((day+6)%7==0?7:(day+6)%7);
System.out.println(dayOfWeek);
I used ternary operator because DayOfWeek takes MONDAY as value of index 1 and Calender.DAY_OF_WEEk takes SUNDAY as value of index 1

Calculate current Age ; using Java

I am trying to calculate the current age of a user .. but using the format i would like to use has caused some issues for me .
I could just ask separately for the year , month and day but much rather prefer (mm/dd/yyyy)
//Need help turning (mm/dd/yyyy) that the user inputs into:
//yyyy;
//mm;
// dd;
package org.joda.time;
import java.util.Calendar;
import java.util.GregorianCalendar;//needed for leap year
import java.util.Scanner;
import java.io.*;
public class AgeCalculation{
public static void main(String[] args) throws IOException{
int day = 1, month = 0, year = 1, ageYears, ageMonths, ageDays;
Scanner myScanner = new Scanner(System.in);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
Calendar cd = Calendar.getInstance();
try{
System.out.print("Enter your Date of Birth.(mm/dd/yyyy): ");
Dob = myScanner.nextLine() ;
// how to get year , month and date from (mm/dd/yyyy) format?
year = ;
if(year > cd.get(Calendar.YEAR)){
System.out.print("Invalid date of birth.");
System.exit(0);
}
month =
if(month < 1 || month > 12){
System.out.print("Please enter monthe between 1 to 12.");
System.exit(0);
}
else{
month--;
if(year == cd.get(Calendar.YEAR)){
if(month > cd.get(Calendar.MONTH)){
System.out.print("Invalid month!");
System.exit(0);
}
}
}
if(month == 0 || month == 2 || month == 4 || month == 6 || month == 7 ||
month == 9 || month == 11){
if(day > 31 || day < 1){
//leap year data below
System.out.print("Please enter day between 1 to 31.");
System.exit(0);
}
}
else if(month == 3 || month == 5 || month == 8 || month == 10){
if(day > 30 || day < 1){
System.out.print("Please enter day between 1 to 30.");
System.exit(0);
}
}
else{
if(new GregorianCalendar().isLeapYear(year)){
if(day < 1 || day > 29){
System.out.print("Please enter day between 1 to 29.");
System.exit(0);
}
}
else if(day < 1 || day > 28){
System.out.print("Please enter day between 1 to 28.");
System.exit(0);
}
}
if(year == cd.get(Calendar.YEAR)){
if(month == cd.get(Calendar.MONTH)){
if(day > cd.get(Calendar.DAY_OF_MONTH)){
System.out.print("Invalid date!");
System.exit(0);
}
}
}
}
catch(NumberFormatException ne){
System.out.print(ne.getMessage() + " is not a legal entry!");
System.out.print("Please enter number.");
System.exit(0);
}
Calendar bd = new GregorianCalendar(year, month, day);
ageYears = cd.get(Calendar.YEAR) - bd.get(Calendar.YEAR);
if(cd.before(new GregorianCalendar(cd.get(Calendar.YEAR), month, day))){
ageYears--;
ageMonths = (12 - (bd.get(Calendar.MONTH) + 1)) + (bd.get(Calendar.MONTH));
if(day > cd.get(Calendar.DAY_OF_MONTH)){
ageDays = day - cd.get(Calendar.DAY_OF_MONTH);
}
else if(day < cd.get(Calendar.DAY_OF_MONTH)){
ageDays = cd.get(Calendar.DAY_OF_MONTH) - day;
}
else{
ageDays = 0;
}
}
else if(cd.after(new GregorianCalendar(cd.get(Calendar.YEAR), month, day))){
ageMonths = (cd.get(Calendar.MONTH) - (bd.get(Calendar.MONTH)));
if(day > cd.get(Calendar.DAY_OF_MONTH))
ageDays = day - cd.get(Calendar.DAY_OF_MONTH) - day;
else if(day < cd.get(Calendar.DAY_OF_MONTH)){
ageDays = cd.get(Calendar.DAY_OF_MONTH) - day;
}
else
ageDays = 0;
}
else{
ageYears = cd.get(Calendar.YEAR) - bd.get(Calendar.YEAR);
ageMonths = 0;
ageDays = 0;
}
System.out.print("Age of the person : " + ageYears + " year, " + ageMonths +
" months and " + ageDays + " days.");
}
}
Here's a hint as how you could read in and parse the entered date:
SimpleDateFormat f = new SimpleDateFormat("MM/dd/yyyy"); //note that mm is minutes, so you need MM here
Scanner s = new Scanner( System.in );
String dateLine = s.nextLine();
try
{
Date d = f.parse( dateLine );
System.out.println(d);
}
catch( ParseException e )
{
System.out.println("please enter a valid date in format mm/dd/yyyy");
}
That's just an example and should get you started with reading the date correctly.
For getting the years, days and months in between two dates I'd still recommend using JodaTime since that makes life much easier.
Using standard Java facilities, this could help you:
Calendar c = Calendar.getInstance();
c.setTimeInMillis( System.currentTimeMillis() - d.getTime() );
System.out.println( c.get( Calendar.YEAR ) - 1970 ); //since year is based on 1970, subtract that
System.out.println( c.get( Calendar.MONTH ) );
System.out.println( c.get( Calendar.DAY_OF_MONTH ) );
Note that you need to subtract the smaller date from the bigger, i.e. the difference must be positive (which should be true when subtracting birth dates from the current time).
This would give a difference of 0 years, 9 full months and 26 days between Jan 1st 2011 and Oct 26th 2011, and a difference of 21 years and 1 day (since we already started this day) between Oct 26th 1990 and Oct 26th 2011.
If you want to use JodaTime:
String dob = myScanner.nextLine();
DateTimeFormatter format = DateTimeFormatter.forPattern("MM/dd/yyyy");
DateTime dateTimeOfBirth = DateTime.parse(dob, format);
year = dateTimeOfBirth.getYear();
// Etc
try this, it out puts the age into a form field called age in a form called "form", assumes you called your textbox(where DOB is entered) "dob"
var d =document.getElementById('dob').value.split('/');
var today = new Date();
var bday = new Date(d[2],d[1],d[0]);
var age = today.getFullYear() - bday.getFullYear();
if(today.getMonth() < bday.getMonth() || (today.getMonth() == bday.getMonth() && today.getDate() < bday.getDate()))
{
t = age--;
}
else {
t = age
}
form.age.value = t;
}
You'll pobably need something like that:
SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy", Locale.US);
Date date = sdf.parse(timestamp);
Calendar cd = Calendar.getInstance();
cd.setTime(date);

Categories