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).
Related
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.
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;
}
}
}
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
was wondering if anyone could help me change an " If else statement " to a "switch"
Well c the pseudo code is.
Please help .
IF month is 1,2, or 3, season = "Winter
Else if month is 4, 5, or 6, season = "Spring"
Else if month is 7,8, 9, season = "Summer"
Else if month is 10,11, or 12, season = "Fall"
If season is "Winter", season = "Spring"
Else if season is "Spring", season = "Summer"
Else if season is "Summer", season = "Fall"
Else season = "Winter"
2.My code is
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 fall = " fall";
String winter = " winter ";
String summer = " summer";
String spring = " spring";
System.out.print(" Month="+ month +" Day= "+day);
if( month <= 3)
{ System.out.println(" Winter");
season= winter; }
else if ( month <=6)
{ System.out.println(" Spring ");
season=spring; }
else if ( month<= 9)
{ System.out.println(" Summer ");
season= spring; }
else if ( month<=12)
{ System.out.println(" Fall");
season= fall; }
3.I just need to change the 1st part to a switch statement.
This is what I have so far
switch( month )
{ case 1: season= " winter";if ( month <= 3) ;break;
case 2: season= " spring"; if ( month <= 6) ;break;
case 3: season = " summer"; if (month <= 9); break;
case 4: season= " fall"; if (month <= 12); break ;
}
,but it is not working .
IF month is 1,2, or 3, season = "Winter
Would simply become...
String season = "";
switch (month) {
case 1:
case 2:
case 3:
season = "Winter";
break;
case ...: // etc...
}
case will fall through to the next case unless there is a break
Take a look at The switch Statement for more details
How about some integer division?
switch( (month + 2) / 12 ) {
case 1:
// winter
break;
case 2:
// spring
break; // WOOHOO SPRING BREAK!
case 3:
// summer
break;
case 4:
// fall
break; // winter is coming...
default:
break;
}
Hints:
You need two switch statements. One for the first if/else chain, and one for the second. (Though you could easily fold the two chains into one!)
The syntax of a switch statement is illustrated in the Java Tutorial here.
The following statement does nothing:
if ( month <= 3) ;
It says "test if month is less or equal to 3, and then execute the empty statement. This is a "gotcha!" in Java syntax ... and one of the reasons that some people think that you should always use curly brackets with if and loop statements in Java and similar languages.
In this application I have to enter the total sales of every month from Jan 2010 to Dec 2014.(48 inputs)
I need to display the month of the year which has min sales and max sales.
The problem is I am not getting the desired output.
package xxxxxxx;
import java.util.Scanner;
public class test{
public static void main ( String [] args ){
Scanner keyboard = new Scanner( System.in );
int getInt=0;
int count = 0;
int sum = 0;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
double average = 0;
boolean number = true;
int choice=0;
while ( number == true )
{
System.out.println("Enter A Sales for a month : ");
getInt = keyboard.nextInt();
choice++;
if ( getInt < 0 )
number = false;
else
{
if ( getInt > max )
max = getInt;
if ( getInt <= min )
min = getInt;
sum += getInt;
count++;
}
}
int maxy=choice%12;
switch(maxy){
case 1 :
System.out.println("It's Month is : "+" Januray of 2010 !"+max);
break;
case 2 :
System.out.println("It's Month is : "+" Februray of 2010 !"+max);
break;
case 3 :
System.out.println("It's month is : "+" March of 2010 !"+max);
break;
case 4 :
System.out.println("It's month is : "+" April of 2010 !"+max);
break;
case 5 :
System.out.println("It's month is : "+" May of 2010 ! "+max);
.
.
.
}
average = ( sum ) / ( count );
System.out.println( "Sum = " + sum );
System.out.println( "Average = " + average );
System.out.println( "Max = " + max );
System.out.println( "Minimum = " + min );
}
}
I believe what you're wanting is the following if you have to use a switch and don't want to use something like a Date formatting class:
int year = 2010 + choice / 12;
int month = 1 + choice % 12;
switch (month) {
case 1: System.out.println("January " + year);
break;
case 2: System.out.println("February " + year);
break;
// so on
}
BTW I don't see anything in your code that restricts the # of inputs to 48 like you say is a spec. You can easily add this to your while loop:
while (number == true && count < 48) {
}
And further reduce it to:
while (number && count < 48) {
}
Because booleans are a boolean themselves you do not need to check if (value == true) and if (value == false), rather you should check if (value) and if (!value).
However your number variable is actually redundant and can be removed entirely if you use a break. I also think you mean to exit before incrementing choice IE looks like the user enters a negative number to end early. If you increment the control this will screw up your average. It looks like you created your second variable count for this purpose but I don't think you need it. You just need to refactor.
I also recommend checking count before doing your average. In your code right now the user can abort the loop immediately and you'll get a divide by zero.
do {
System.out.println("Enter a sales for the month: ");
getInt = keyboard.nextInt();
if (getInt < 0) break;
if (getInt > max) max = getInt;
if (getInt < min) min = getInt;
sum += getInt;
count++;
} while (count < 48);
if (count == 0) {
System.out.println("No sales ever!");
return;
}
int year = 2010 + count / 12;
int month = 1 + count % 12;
To get the current month just use this
int month = Calendar.getInstance().get(Calendar.MONTH) + 1;
and the year is
int year = Calendar.getInstance().get(Calendar.YEAR);
putting it all together
private static String getMonthName(int month) {
switch (month - 1) {
case Calendar.JANUARY: return "January";
case Calendar.FEBRUARY: return "February";
case Calendar.MARCH: return "March";
case Calendar.APRIL: return "April";
case Calendar.MAY: return "May";
case Calendar.JUNE: return "June";
case Calendar.JULY: return "July";
case Calendar.AUGUST: return "August";
case Calendar.SEPTEMBER: return "September";
case Calendar.OCTOBER: return "October";
case Calendar.NOVEMBER: return "November";
case Calendar.DECEMBER: return "December";
default:
System.err.println("month " + month
+ " unknown, use January.");
return "January";
}
}
public static void main(String[] args)
throws IOException {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, -48);
for (int i = 0; i <= 48; i++) {
int month = cal.get(Calendar.MONTH) + 1;
int year = cal.get(Calendar.YEAR);
System.out.println(getMonthName(month) + " " + year);
cal.add(Calendar.MONTH, 1);
}
}