Having problems with consistency [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm having issues with my program. Namely in that when I enter a value to say what day it will be a few days from now, it sometimes work, and other times it doesn't. I'm not sure what the problem is... Bear with me I'm still learning.
Thanks in advance
import java.util.*;
public class pooped {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
int day;
int june;
int dates;
System.out.println(" Days of the week are numbered 0 - 6 " +
"From Sunday to Saturday, enter a number now");
day = console.nextInt();
int kill = day;
System.out.println("Enter the number of days forward: ");
dates = console.nextInt();
printday(day);
day = addDay(day);
printday(day);
day = removeDay(day);
printday(day);
dates = count(dates);
printday(kill + dates);
}
public static int count(int dates) {
if (dates > 6){
dates = (dates % 6);
}
System.out.println("That many days out is: ");
return dates;
}
private static int addDay(int day) {
day++;
System.out.println("The next day is: ");
if (day > 6) {
day = 0;
}
return day;
}
private static int removeDay(int day) {
day = day - 2;
System.out.println("The previous day is: ");
if (day == 0) {
day = 6;
}
return day;
}
public static boolean isWeek(int day) {
return day >= 0 && day <= 6;
}
public static void printday(int day) {
switch (day)
{
case 0:
System.out.println("Sunday");
break;
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
default:
break;
}
}
}

You should mod by 7, not 6. Modding by 6 will only yield values 0-5.
dates %= 7;
So, whenever you add or subtract from a variable that should remain between 0-6, perform the above mod, by 7.
Full source
public class Main {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
int day;
int june;
int dates;
System.out.println(" Days of the week are numbered 0 - 6 "
+ "From Sunday to Saturday, enter a number now");
day = console.nextInt();
System.out.println("Enter the number of days forward: ");
dates = console.nextInt();
printday(day);
printday(addDay(day));
printday(removeDay(day));
printday(day + count(dates));
}
public static int count(int dates) {
dates %= 7;
System.out.println("That many days out is: ");
return dates;
}
private static int addDay(int day) {
day++;
day %= 7;
System.out.println("The next day is: ");
return day;
}
private static int removeDay(int day) {
day--;
day += 7;
day %= 7;
System.out.println("The next day is: ");
return day;
}
public static boolean isWeek(int day) {
return day >= 0 && day <= 6;
}
public static void printday(int day) {
switch (day) {
case 0:
System.out.println("Sunday");
break;
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
default:
break;
}
}
}

Related

What to revise to make it implement modularization using methods

I already have these 3 codes made but our prof said to revise it again using methods now. Can you help or can you show me what to revise in each code?
1.)
public class HeadsOrTails {
public static void main(String[] args) {
int Heads = 0;
int Tails = 0;
for(long simulation = 1; simulation <= 2000000; simulation += 1)
{
int FlipResult = FlipCoin();
if(FlipResult == 1)
{
Heads += 1;
}
else if(FlipResult == 0)
{
Tails += 1;
}
}
System.out.println("Numer of heads appeared: " + Heads);
System.out.println("Numer of tails appeared: " + Tails);
}
private static int FlipCoin()
{
return (int) (Math.random() + 0.5);
}
}
2.)
import java.util.Scanner;
public class DecToHex {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a decimal number: ");
int number = input.nextInt();
int rem;
String result = "";
char
hex[]= {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
while(number > 0)
{
rem = number % 16;
result = hex[rem]+result;
number = number/16;
}
System.out.println("Hexadecimal Number: "+result);
}
}
3.)
import java.util.Scanner;
public class DayOfTheWeek {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter Year: (e.g., 2012): ");
int year = input.nextInt();
System.out.print("Enter Month: 1-12: ");
int month = input.nextInt();
System.out.print("Enter the Day of the month: 1-31:");
int day = input.nextInt();
String DayOfTheWeek = ZCAlgo(day, month, year);
System.out.println("Day of the week is "+DayOfTheWeek);
}
public static String ZCAlgo(int day, int month, int year)
{
if (month == 1)
{
month = 13;
year--;
}
if (month == 2)
{
month = 14;
year--;
}
int q = day;
int m = month;
int k = year % 100;
int j = year / 100;
int h = q + 13*(m + 1) / 5 + k + k / 4 + j / 4 + 5 * j;
h = h % 7;
switch (h)
{
case 0: return "Saturday";
case 1: return "Sunday";
case 2: return "Monday";
case 3: return "Tuesday";
case 4: return "Wednesday";
case 5: return "Thurday";
case 6: return "Friday";
}
return "";
}
}
3.)
import java.util.Scanner;
public class DayOfTheWeek {
/* *****************************************************************************
METHOD NAME : main
DESCRIPTION : Executes the main program to test the class
DayOfTheWeek
********************************************************************************/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter Year: (e.g., 2012): ");
int year = input.nextInt();
System.out.print("Enter Month: 1-12: ");
int month = input.nextInt();
System.out.print("Enter the Day of the month: 1-31:");
int day = input.nextInt();
String DayOfTheWeek = ZCAlgo(day, month, year);
System.out.println("Day of the week is "+DayOfTheWeek);
}
public static String ZCAlgo(int day, int month, int year)
{
if (month == 1)
{
month = 13;
year--;
}
if (month == 2)
{
month = 14;
year--;
}
int q = day;
int m = month;
int k = year % 100;
int j = year / 100;
int h = q + 13*(m + 1) / 5 + k + k / 4 + j / 4 + 5 * j;
h = h % 7;
switch (h)
{
case 0: return "Saturday";
case 1: return "Sunday";
case 2: return "Monday";
case 3: return "Tuesday";
case 4: return "Wednesday";
case 5: return "Thurday";
case 6: return "Friday";
}
return "";
}
}
Your professor wants you to avoid typing duplicate code. They want you to minimize the amount of code you have to repeatedly type. For example, look at the main method from your DayOfTheWeek class.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter Year: (e.g., 2012): ");
int year = input.nextInt();
System.out.print("Enter Month: 1-12: ");
int month = input.nextInt();
System.out.print("Enter the Day of the month: 1-31:");
int day = input.nextInt();
//After this is more code below that we don't care about for now
}
You had to do 3 System.out.print() calls. You also did 3 input.nextInt() calls. That's 6 calls total.
Notice how there is a System.out.print() call, and then a input.nextInt() call immediately after? We can slim that down to something like this.
public static int fetchInput(Scanner input, String message) {
System.out.print(message);
return input.nextInt();
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int year = fetchInput(input, "Enter Year: (e.g., 2012): ");
int month = fetchInput(input, "Enter Month: 1-12: ");
int day = fetchInput(input, "Enter the Day of the month: 1-31:");
//After this is more code below that we don't care about for now
}
Now, we only have to type fetchInput() 3 times, which has a call to both System.out.print() and input.nextInt(), giving us a total of 5 calls.
So, 5 is less than 6, which means we have made progress towards our goal, but since it is only one less call, it may not seem significant. But in reality, there's a lot more repeats in your code - I just handed you one of them. On top of that, your professor is teaching you good habits that will help you if you ever become a programmer. What if instead of fetching 3 things, you needed to fetch 20? This is common in the real world, by the way. Using your old style, you would have had to type 20 System.out.print() and 20 input.nextInt() calls at least, putting you at around 40 calls. But doing it this new way, you would only need to type 20 fetchInput() calls, which has a System.out.print() call and an input.nextInt() call within it, putting our total at 22 calls for the new method. 40 vs 22 things to type is an easier to see example of how writing code that minimizes retyping the same thing saves you time.

Java - error in prompts [duplicate]

I have a question that I can't figure it out , Thank you:
Write a program that prompts the user to enter an integer for today's day of the week (Sunday is 0 ,Monday is 1 ,... and Saturday is 6). Also prompt the user to enter the number of days after today for a future day and display the future day of the week .Here is the sample run:
Enter today's day: 1
Enter number of the day elapsed since today:3
Today is monday and the future day is thursday
My try is:
Scanner input = new Scanner(System.in);
System.out.print("Enter today's day (0 - 6): ");
int day = input.nextInt();
System.out.print("Enter the number of days elapsed since today: ");
int elapsed = input.nextInt();
if(day == 0)
{
System.out.println("Sunday");
}
if(day == 1)
{
System.out.println("Monday");
}
if(day == 2)
{
System.out.println("Tuesday");
}
if(day == 3)
{
System.out.println("Wednesday");
}
if(day == 4)
{
System.out.print("Thursday");
}
if(day == 5)
{
System.out.print("Friday");
}
if(day == 6)
{
System.out.print("Saturday");
}
System.out.print("Today is " + day + " and the future day is " + elapsed);
As you need day-number to day-string twice, put it in a separate function. I want to show you a couple of possible approaches. Version 1, basic, simple and tidy:
// isolate the daynumber --> daystring in a function, that's tidier
String dayFor (int daynumber) {
String dayAsString = "ERROR"; // the default return value
switch(dayNumber) {
case 0 :
dayAsString = "Sunday";
break;
case 1 :
dayAsString = "Monday";
break;
// and so on, until
case 6 :
dayAsString = "Saturday";
break;
}
return dayAsString;
}
A much shorter version that uses an array instead of the switch statement:
String dayFor (int daynumber) {
String dayStrings[] = new String[]{"Sunday","Monday", .... "Saturday"};
// notice that daynumber's modulo is used here, to avoid index out of
// bound errors caused by erroneous daynumbers:
return dayStrings[daynumber % 7];
}
It might be tempting to try something along the lines of the following function where each case returns immediately, but having multiple return statements is discouraged. Just showing it here because it is technically possible, and you'll encounter it sometimes
String dayFor (int daynumber) {
switch(dayNumber) {
case 0 :
return "Sunday";
case 1 :
return "Monday";
// and so on, until
case 6 :
return "Saturday";
}
// normally not reached but you need it because the compiler will
// complain otherwise anyways.
return "ERROR";
}
After this rather long intro the main function becomes short and simple. After the input you just need:
// present day + elapsed modulo 7 = the future day
int future = (day + elapsed) % 7;
System.out.print("Today is " + dayFor(day) + " and the future day is " + dayFor(future) );
Don't forget to add code to check your inputs!
You can do it better by using an array to store the the day names.
String[] dayNames = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
Now you can use the user input as the index
int nameIndex = //... get input
//validate input
//dayNames[nameIndex] is the day of the week
Now get the input for number of days to add
int numDays = //...get input
Then just add that many days to compute the index for future day of week
int futureNameIndex = nameIndex; //start with entered day of week index
for(int i=0; i<numDays; i++) {
futureNameIndex++; //increment by 1 for numDays times
if(futureNameIndex == dayNames.length) { //if the index reaches lenght of the array
futureNameIndex = 0; //reset it to 0
}
}
I think you will find that one easier to understand. Finally
//dayNames[futureNameIndex] is the future day of week.
The question gives you the days ranging from 0-6, instead of 1-7(conventional). Now, for example, if the day today is 1(Monday) and the daysElapsed since today is 3, then the day should be Thursday. Since this question has the initial day inclusive, the resulting day will be after 1(Monday),2,3(Wednesday) have passed, that is Thursday.
Let's take an example and apply it to the code below.
day = 1;
daysElased = 3;
else if(day > 0 && day < 7) , which is the case
{
sum = 1(day) + 3(daysElapsed); // sum = 4
}
If sum is in the range of 0-6, each if case can be created corresponding to each day. In the case above, the sum is less than 6, so it will be having its own if clause. Had the sum been greater, for example, days = 1 and daysElapsed = 6, then sum = 1(days) + 6(daysElapsed) = 7.
In this case it will match the clause if(sum > 6), then sum = sum % 7 = 7 % 7 = 0 = Sunday. This means that the days from 1(Monday) to 6(Saturday) have been elapsed, so the day will be Sunday(0).
if(day == 0) // If the present day entered is Zero(0 is for Sunday)
{
sum = daysElapsed; // daysElapsed will be entered by the user
}
else if(day > 0 && day < 7) // If the present day is > 0 but < 7 (1 - 6 days)
{
sum = day + daysElapsed; //
}
if(sum>6) // if 0<= sum <=6 , 6 if cases can be created. If sum > 6 :
{
sum = sum % 7;
}
if(sum == 0)
{
System.out.println("Day is Sunday.");
}
.
.
.
.
else if(sum == 6)
{
System.out.println("Day is Saturday.");
}
As I know, this question is from the book "Introduction To Java Programming". Where this question is asked, you don't have any knowledge of methods, loops, arrays etc. so I will just use Selections.
Here, when I tried to solve with a better way, I could not find any since we cannot use arrays which could be very helpful or methods which is even better. That's why this question is a little redundant in book.
And you really should not use if statements because switch is much better in this case.
System.out.println("Enter today's number (0 for Sunday, 1 for Monday...) :");
int todayNo = in.nextInt();
System.out.println("Enter the number of days elapsed since today:");
int elapsedDay = in.nextInt();
int futureDay = (todayNo + elapsedDay) % 7;
switch (todayNo) {
case 0:
System.out.print("Today is Sunday and");
break;
case 1:
System.out.print("Today is Monday and");
break;
case 2:
System.out.print("Today is Tuesday and");
break;
case 3:
System.out.print("Today is Wednesday and");
break;
case 4:
System.out.print("Today is Thursday and");
break;
case 5:
System.out.print("Today is Friday and");
break;
case 6:
System.out.print("Today is Saturday and");
break;
}
switch (futureDay) {
case 0:
System.out.print(" the future day is Sunday.");
break;
case 1:
System.out.print(" the future day is Monday.");
break;
case 2:
System.out.print(" the future day is Tuesday.");
break;
case 3:
System.out.print(" the future day is Wednesday.");
break;
case 4:
System.out.print(" the future day is Thursday.");
break;
case 5:
System.out.print(" the future day is Friday.");
break;
case 6:
System.out.print(" the future day is Saturday.");
break;
}
Here, the only thing that you maybe don't know is System.out.print();. The only difference with the System.out.println(); is with this method, this one doesn't print on a new line, it prints on the same line which is what we need here. Tinker with it to understand better.
package javaapplication2;
import java.util.Scanner;
public class JavaApplication2 {
public static void main(String[] args) {
int day, eday, fday;
String str, str1;
Scanner S = new Scanner(System.in);
System.out.println("Enter today's day: ");
day = S.nextInt();
System.out.println("Enter the number of days elapsed since today: ");
eday = S.nextInt();
if (day == 0) {
str = "Sunday";
System.out.print("Today is " +str + " and ");
}
else if (day == 1) {
str = "Monday";
System.out.print("Today is " +str + " and ");
}
else if (day == 2) {
str = "Tuesday";
System.out.print("Today is " +str + " and ");
}
else if (day == 3) {
str = "Wednesday";
System.out.print("Today is " +str + " and ");
}
else if (day == 4) {
str = "Thursday";
System.out.print("Today is " +str + " and ");
}
else if (day == 5) {
str = "Friday";
System.out.print("Today is " +str + " and ");
}
else if (day == 6) {
str = "Saturday";
System.out.print("Today is " +str + " and ");
}
fday = day + eday;
if (fday % 7 == 0) {
str1 = "Sunday";
System.out.print("Future day is " +str1);
}
else if (fday % 7 == 1) {
str1 = "Monday";
System.out.print("Future day is " +str1);
}
else if (fday % 7 == 2) {
str1 = "Tuesday";
System.out.print("Future day is " +str1);
}
else if (fday % 7 == 3) {
str1 = "Wednesday";
System.out.print("Future day is " +str1);
}
else if (fday % 7 == 4) {
str1 = "Thursday";
System.out.print("Future day is " +str1);
}
else if (fday % 7 == 5) {
str1 = "Friday";
System.out.print("Future day is " +str1);
}
else if (fday % 7 == 6) {
str1 = "Saturday";
System.out.print("Future day is " +str1);
}
}
The question is from a book titled "Introduction to Java programming" by Y. Daniel Liang. Apart from using the string type, which I believe is covered in the next chapter; the solution I wrote for this exercise uses only what you have been taught so far.
import java.util.Scanner;
public class Exercise_03_06 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter today's day: ");
int todaysDay = input.nextInt();
System.out.print("Enter the number of days elapsed since today: ");
int elapsedDays = input.nextInt();
int futureDay = (todaysDay + elapsedDays) % 7;
String day_of_week = "";
switch (todaysDay) {
case 0: day_of_week = "Sunday"; break;
case 1: day_of_week = "Monday"; break;
case 2: day_of_week = "Tuesday"; break;
case 3: day_of_week = "Wednesday"; break;
case 4: day_of_week = "Thursday"; break;
case 5: day_of_week = "Friday"; break;
case 6: day_of_week = "Saturday";
}
switch (futureDay) {
case 0:
System.out.println("Today is " + day_of_week + " and the future day is Sunday."); break;
case 1:
System.out.println("Today is " + day_of_week + " and the future day is Monday."); break;
case 2:
System.out.println("Today is " + day_of_week + " and the future day is Tuesday."); break;
case 3:
System.out.println("Today is " + day_of_week + " and the future day is Wednesday."); break;
case 4:
System.out.println("Today is " + day_of_week + " and the future day is Thursday."); break;
case 5:
System.out.println("Today is " + day_of_week + " and the future day is Friday."); break;
case 6:
System.out.println("Today is " + day_of_week + " and the future day is Saturday.");
}
}
}
Output:
Enter today's day: 0
Enter the number of days elapsed since today: 31
Today is Sunday and the future day is Wednesday.
Notes:
The first switch statement assigns a day of type string to the variable day_of_week which is later used for printing "today's day".
To obtain the future day, you must find the remainder of the sum of today's day and the number of days elapsed divided by 7.
The last switch statement "matches" a case number that is identical to the number stored within the futureDay variable (which is obtained by performing the mathematical operation noted above).

How to use switch-statement correctly?

I need to write a Java program (class NextDay) that calculates and prints the date of the next day by entering the day, month, and year.
Sample call and output:
Actual Date 12.12.2004
The next day is the 13.12.2004.
The input should also be checked for correctness! If an erroneous date constellation (e.g., 32 12 2007) has been entered, the exception InvalidDateArgumentsException is to be thrown. Define this class in a suitable form as a subclass of the class java.lang.Exception.
I started to creating it but the problem is; i cant tell that < or > in switch statements.What should i do? Here are my classes:
public class Date {
private int day;
private int month;
private int year;
public Date(int day, int month, int year) {
this.day = day;
this.month = month;
this.year = year;
}
public Date getNextDay() throws Exception {
if (isLeapYear() == true) {
switch (month) {
case 1:
day = 31;
break;
case 2:
day = 29;
break;
case 3:
day = 31;
break;
case 4:
day = 30;
break;
case 5:
day = 31;
break;
case 6:
day = 30;
break;
case 7:
day = 31;
break;
case 8:
day = 31;
break;
case 9:
day = 30;
break;
case 10:
day = 31;
break;
case 11:
day = 30;
break;
case 12:
day = 31;
break;
}
}
return new Date(day + 1, month, year);
}
public int getDay() {
return day;
}
public int getMonth() {
return month;
}
public int getYear() {
return year;
}
public boolean isLeapYear() {
if (year % 4 == 0 && year % 100 != 0 && year % 400 == 0) {
return true;
}
return false;
}
public String toString() {
return this.day + "." + this.month + "." + this.year;
}
}
...
public class NextDay {
public static void main(String args[]) throws Exception {
Date dateObj = new Date(20, 5, 2016);
System.out.println("Old Date: " + dateObj.getDay() + "." + dateObj.getMonth() + "." + dateObj.getYear() + ".");
System.out.println("The next day is " + dateObj.getNextDay().toString() + ".");
}
}
You are saying that you want an "or" statement inside switch, right? If you write case labels line by line you get "or statement", like this:
switch(variable){
case 1:
case 2:
case 3: {
//.. when variable equals to 1 or 2 or 3
}
}
So that, you can write your getMaxDaysInMonth method like this:
int getMaxDaysInMonth()
{
int daysInMonth = 0;
switch(month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
daysInMonth = 31;
break;
case 2:
if(isLeapYear())
{
daysInMonth = 29;
}
else
{
daysInMonth = 28;
}
break;
case 4:
case 6:
case 9:
case 11:
daysInMonth = 30;
}
return daysInMonth;
}
Also, you are checking for the leap year incorrectly. Here's the correct way:
boolean isLeapYear(){
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
And here's how you increment a day:
void incrementDate(){
if((day + 1) > getMaxDaysInMonth())
{
day = 1;
if (month == 12)
{
month = 1;
year++;
}else{
month++;
}
} else {
day++;
}
}
EDIT since we can't just use standard classes
If you have to use switch case, you should use it to set max day in current month and then check, if your current day more than this max day:
int maxDay;
switch (month) {
case 1: maxDay = 31; break;
case 2: maxDay = isLeapYear() ? 29 : 28; break;
case 3: maxDay = 31; break;
// ... other months ...
case 12: maxDay = 31; break;
default: throw new InvalidDateArgumentsException();
}
if (isLeapYear()) {
maxDay = 29;
}
if (day > maxDay) {
throw new InvalidDateArgumentsException();
}

Using methods and objects, but no arrays

I was here earlier before, and got pointed in the right direction. But I couldn't get the offered solution to work. It now mostly works, but i'm stuck on one part, and I'm not sure how to proceed. If anyone can point me to the right direction, i'll be grateful. I just need a hint, or pointers to something I'm not seeing.
I'm trying to add a random number of days, and determine what that adds up to. I know I have to have a counter that flips over after 7, but I've tried everything, and keep getting errors
import java.util.*;
public class pooped
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
int day;
System.out.println(" Days of the week are numbered 1-7"+
"From Sunday to Saturday, enter a number now");
day = console.nextInt();
System.out.println(isWeek(day));
printday(day);
}
public static boolean isWeek(int day)
{
return day >= 0 && day <= 7;
}
static Scanner console = new Scanner(System.in);
public static void addDay()
{
int date;
System.out.println("Enter how many days you want to go forward.");
date = console.nextInt();
if (int date > 0)
{
int day = date + 1;
}
}
public static void printday(int day)
{
switch (day) {
case 1:
System.out.println("Sunday");
break;
case 2:
System.out.println("Monday");
break;
case 3:
System.out.println("Tuesday");
break;
case 4:
System.out.println("Wednesday");
break;
case 5:
System.out.println("Thursday");
break;
case 6:
System.out.println("Friday");
break;
case 7:
System.out.println("Saturday");
default:
break;
}
}
}
If you need
a counter that flips over after 7
consider using day = day % 7; in your main method, which gives you the modulo operation.
When you say "I have to have a counter that flips over after 7", do you mean that 7 should roll back to 0, 8 to 1, etc?
If that's the case, you need to look at the modulus operator (%)
You inWeek function looks incorrect. If your day is 0 based, it should be:
public static boolean isWeek(int day)
{
return day >= 0 && day < 7;
}
Otherwise you will have 8 days.

How to incorporate error message in the program below?

I'm an beginner IT11 student and we're supposed to make a program that will read in the number of the day, the month, and the year a person was born.
For example, someone born on September 3, 1982, would enter the numbers
3, 9, and 1982
into three separate JOP.showInputDialogs.
If an incorrect value is entered, the program should give a very specific error message explaining why it is invalid and ask the user to enter the information again. A user should never have to reenter more than one of the values when an invalid entry is made (example, if the day is invalid, the user should only have to reenter the day, not the month or the year).
The program will then tell the person their birthdate with the following format:
You were born September 3, 1982.
The format of the date must be as shown above.
Important
- The program MUST do error checking for invalid months (valid between 1 and 12)
- The program MUST do error checking for invalid years (valid >= 1800)
- The program MUST do error checking for invalid day of month (valid between 1 and maxDay in month (30, 31, 28 or 29))
- The program MUST only allow Feb 29 on LEAP YEARS only.
The part I'm stuck on is incorporating an error message for invalid dates. For example, if I were to input April 31, the program should return an error message saying "April only has 30 days", etc. How do I do that? Here is what I've got so far.
import javax.swing.*;
public class A6DateProgram {
public static void main(String[] args) {
int year = getYearFromUser(); //gets user input for year
int month = getMonthFromUser(); //gets user input for month
int day = getDateFromUser(month, year); //gets user input for date
//tells the user their birthdate
System.out.println("You were born " + Months(month) + " " + day + ", "+ year + " " + ".");
} //main
//asks user for year
public static int getYearFromUser(){
String year; //asks user for year
int year1 = 0;
String errorMessage = "";
boolean isLeap = false;
do{
year = JOptionPane.showInputDialog(errorMessage + "Please enter the year you were born in. (>1800)");
if (year == null) {
System.out.println("You clicked cancel");
System.exit(0);
}
// parse string to an int
try {
year1 = Integer.parseInt(year); //parses recieved number to an int
} catch (Exception e) {
errorMessage = "Invalid integer\n"; //if user does not input valid integer
continue; //continues to condition [while(true);]
} // catch
isLeap = validateYear(year1);
if(year1 < 1800 || year1 > 2400){ //number limitation
errorMessage = "Your number must be greater than 1800 or less than 2400. \n"; //if user does not input a valid integer between limit
continue; //continues to condition [while(true);]
}
break;
} while(true);
return year1;
} //getYearFromUser
public static boolean validateYear(int year){
return (year % 400 == 0 ) ? true : (year%100 == 0)? false : (year % 4 == 0)? true: false;
}
//asks user for month
public static int getMonthFromUser(){
String month;
int num = 0;
String errorMessage = "";
do{
month = JOptionPane.showInputDialog(errorMessage + "Please enter the month you were born in as a valid integer. (ex. January = 1)");
if (month == null) {
System.out.println("You clicked cancel");
System.exit(0);
}
// parse string to an int
try {
num = Integer.parseInt(month);
} catch (Exception e) {
errorMessage = "Invalid integer\n";
continue; //continues to condition [while(true);]
} // catch
if(num > 12 || num < 1){
errorMessage = "A year only has 12 months. \n";
continue; //continues to condition [while(true);]
}
break;
} while(true);
return num;
} //getMonthFromUser
//asks user for date
public static int getDateFromUser(int month, int year){
String date;
int day = 0;
String errorMessage = "";
boolean ToF = false;
do{
date = JOptionPane.showInputDialog(errorMessage + "Please enter the date you were born in. (1-31)");
//user clicks cancel
if (date == null) {
System.out.println("You clicked cancel");
System.exit(0);
}
// parse string to an int
try {
day = Integer.parseInt(date);
} catch (Exception e) {
errorMessage = "Invalid integer\n";
continue; //continues to condition [while(true);]
} // catch
ToF = validate(year, month, day); //giving boolean ToF a method to validate the day
if(ToF == false){
errorMessage = "The month you input does not have that date. \n";
continue; //continues to condition [while(true);]
}
break;
} while(true); //do
return day;
} //getDateFromUser
public static boolean validate(int year, int month, int day){
switch(month){
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
if(day < 1 || day > 31)
return false;
break;
case 2:
if(year%4 == 0 || (year%400 == 0 && year%100 != 0)){
if (day < 1 || day > 29)
return false;
}else{
if (day < 1 || day > 28)
return false;
}
break;
case 4:
case 6:
case 9:
case 11:
if(day < 1 || day > 30)
return false;
break;
}
return true;
} //validate
//resonse to user input for month
public static String Months(int month) {
switch (month) {
case 1: return "January";
case 2: return "Febrary";
case 3: return "March";
case 4: return "April";
case 5: return "May";
case 6: return "June";
case 7: return "July";
case 8: return "August";
case 9: return "September";
case 10: return "October";
case 11: return "November";
case 12: return "December";
default: return "Invalid";
} // switch
} //Months
} //A6DateProgram Class
Try with SimpleDateFormat()
String date = "3";
String month = "9";
String year = "1980";
SimpleDateFormat sdf1 = new SimpleDateFormat("ddMMyyyy");
SimpleDateFormat sdf2 = new SimpleDateFormat("MMMM dd, yyyy");
Date date1 = sdf1.parse((Integer.parseInt(date)<10?"0"+date:date)+(Integer.parseInt(month)<10?"0"+month:month)+year);
String ansStr = sdf2.format(date1);
System.out.println("You were born "+ansStr);
If you enter an invail date it automatically take the next date.
Eaxmple if the input is 29-02-2014 it will take as 01-03-2014

Categories