Best Before Puzzle [duplicate] - java

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Spotify puzzle problem
Been working on this puzzle because I am new to Java and would like to learn it. SO, I have been solving this puzzle for Spotify. But everytime I submit it. It says wrong answer. Im pretty sure its right though can anyone see what I am missing. This is the problem. http://www.spotify.com/us/jobs/tech/best-before/
Here is my solution
import java.io.*;
import java.util.Arrays;
public class best_before {
static boolean next;
static String month, day, year;
public static void main(String[] args) throws IOException{
//Setup to grab the input
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String input = "";
input = br.readLine();
//Spilt the input to grab each integer entered by user
String bits = input;
String[] tokens = bits.split("/");
int a_value1 = Integer.parseInt(tokens[0]);
int b_value1 = Integer.parseInt(tokens[1]);
int c_value1 = Integer.parseInt(tokens[2]);
//Sort the array in order from lowest to highest
int[] int_array = new int[] {a_value1, b_value1, c_value1};
Arrays.sort(int_array);
int a_value = int_array[0];
int b_value = int_array[1];
int c_value = int_array[2];
year = Integer.toString(a_value);
month = Integer.toString(b_value);
day = Integer.toString(c_value);
//Check the integers entered to put them in the right order
int check_days = Integer.parseInt(day);
int check_month = Integer.parseInt(month);
int check_year = Integer.parseInt(year);
//Check to make sure none of the values are a negative integer
if(check_days < 0){
System.out.println(input + " is illegal");
System.exit(0);
}
else if(check_month < 0){
System.out.println(input + " is illegal");
System.exit(0);
}
else if(check_year < 0){
System.out.println(input + " is illegal");
System.exit(0);
}
//Will only change the values around if the highest date in the array is bigger than 31
if(check_days > 31){
//Only reorganize if year if larger than month
if(check_month > check_year){
month = Integer.toString(check_year);
}
//Otherwise just keep month at its current value
else{
month = Integer.toString(check_month);
}
//Change date and year around since one is bigger than the other
year = Integer.toString(check_days);
day = Integer.toString(check_month);
}
else if(check_year == 0){
if(check_month < check_days){
month = Integer.toString(check_month);
}
else{
month = Integer.toString(check_days);
}
}
//Get the length so I can zero pad the numbers
int length_year = year.length();
int length_month = month.length();
int length_day = day.length();
//Doing my zero pad thing right here
if(length_year == 1){
year = "200" + year;
}
else if(length_year == 2){
year = "20" + year;
}
else if(length_year == 3){
year = "2" + year;
}
if(length_month == 1){
month = "0" + month;
}
if(length_day == 1){
day = "0" + day;
}
//A last check to make sure everything is Kosher
int last_check = Integer.parseInt(year);
int last_check_month = Integer.parseInt(month);
int last_check_day = Integer.parseInt(day);
//Checking to see if it is a leap year. Is the year Divisible by 4?
if (last_check % 4 == 0) {
// Is the year Divisible by 4 but not 100?
if (last_check % 100 != 0) {
next = true;
}
// Is the year Divisible by 4 and 100 and 400?
else if (last_check % 400 == 0) {
next = true;
}
// It is Divisible by 4 and 100 but not 400!
else {
next = false;
}
}
// It is not divisible by 4.
else {
next = false;
}
//Check to make sure the date is legal and valid :)
if(last_check > 2999 || last_check < 2000)
{
//Date must be between 2000 and 2999 inclusive
System.out.println(input + " is illegal");
}
else if(last_check_month > 12)
{
//Date month must be less than 12
System.out.println(input + " is illegal");
}
else if(last_check_day > 31)
{
//Date day must be less than 31
System.out.println(input + " is illegal");
}
else if(next == false && last_check_day > 28 && last_check_month == 2){
//if next is false and the day is greater than 28 and its not a leap year something is wrong
System.out.println(input + " is illegal");
}
else if(next == true && last_check_day > 29){
//if next is true and the day is greater than 29 and it is a leap year something is wrongs
System.out.println(input + " is illegal");
}
else if(last_check_month == 4 && last_check_day > 30){
System.out.println(input + " is illegal");
}
else if(last_check_month == 6 && last_check_day > 30){
System.out.println(input + " is illegal");
}
else if(last_check_month == 9 && last_check_day > 30){
System.out.println(input + " is illegal");
}
else if(last_check_month == 11 && last_check_day > 30){
System.out.println(input + " is illegal");
}
else if(last_check == 2000){
//Check to make sure there are no other days that are zero too because you cant have two zeros
if(last_check_day == 0 || last_check_month == 0){
System.out.println(input + " is illegal");
}
else{
System.out.print(year + "-" + month + "-" + day);
}
}
else{
System.out.print(year + "-" + month + "-" + day);
}
}
}

Your program fails for the input 31/9/73, where it returns 2073-09-31 instead of 31/9/73 is illegal. Since September only has 30 days, your program should check for September (and a couple of other months), and output the error.
In the updated version, your program still fails the input 1/2/31; it should give 2031-1-2.
By the way, the main intent behind these puzzles is not to solve them, but to solve them elegantly. Try reducing the number of variables, and avoiding duplicate lines etc.

Related

One of my results are messed up

I am working on a project that has the user input the current date as well as their birthday. The whole code calculates their age as well as printing the date. For the current date it should show 11/14/2016, but instead shows 0/14/2016 and I cannot figure out where I went wrong.
Here's the code:
public class BroDoYouEvenAge {
// add in try-catch statements x
// only numeric values x
// leap year
// loop if invalid
// loop if day is invalid
// less than 1 or greater than max day x
// add in no spaces or letters x
// VALIDATION FOR MONTHS x
// loop if invalid
// same year x
// try again x
// loop if invalid
static int cDay;
static int cMonth;
static int bYear;
static int bMonth;
static int bDay;
public static void run() {
prompt();
retry();
}
public static void prompt() {
BufferedReader delta = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.println("Please enter the current year");
String Year = delta.readLine();
int cYear = Integer.parseInt(Year);
// prompts the user for the current month as a numeric value
boolean validmonth = false;
while(!validmonth){
System.out.println("Please enter the current month as a numeric value");
String Month = delta.readLine();
int cMonth = Integer.parseInt(Month);
if (cMonth < 1 || cMonth > 12) {
System.out.println("Your input was invalid");
}else{
validmonth = true;
}
}
// prompts the user for the current day as a numeric value
boolean validday = false;
while (!validday) {
System.out.println("Please enter the current day as a numeric value");
String Day = delta.readLine();
cDay = Integer.parseInt(Day);
if (cDay < 1) {
System.out.println("Your input was invalid");
}else if (cDay > 31) {
System.out.println("Your input was invalid");
}else if (cMonth == 4 && cDay > 30) {
System.out.println("Your answer is invalid");
}else if (cMonth == 6 && cDay > 30) {
System.out.println("Your answer is invalid");
}else if (cMonth == 9 && cDay > 30) {
System.out.println("Your answer is invalid");
}else if (cMonth == 11 && cDay > 30) {
System.out.println("Your answer is invalid");
}else{
validday = true;
}
}
// prompts the user for their birth year
boolean validYear = false;
while(!validYear){
System.out.println("Please enter your birth year");
String Year2 = delta.readLine();
bYear = Integer.parseInt(Year2);
if (bYear > cYear) {
System.out.println("Your answer was invalid");
}else{
validYear = true;
}
}
// does not allow user to input a value greater than their current
// year
// loops if invalid
// prompts the user for their birth month
boolean _validmonth = false;
while(!_validmonth){
System.out.println("Please enter your birth month as a numeric value");
String Month2 = delta.readLine();
bMonth = Integer.parseInt(Month2);
if(bMonth < 1 || bMonth> 12){
System.out.println("Your answer was invalid");
}else{
_validmonth = true;
}
}
// prompts the user for their birth day
boolean _validday = false;
while(!_validday){
System.out.println("Please enter the day you were born as a numeric value");
String Day2 = delta.readLine();
bDay = Integer.parseInt(Day2);
// prints out collected data
if (bMonth == 4 && bDay > 30) {
System.out.println("Your answer is invalid");
}else if (bMonth == 6 && bDay > 30) {
System.out.println("Your answer is invalid");
}else if (bMonth == 9 && bDay > 30) {
System.out.println("Your answer is invalid");
}else if (bMonth == 11 && bDay > 30) {
System.out.println("Your answer is invalid");
}else{
_validday= true;
}
}
System.out.println("The current date is " + cMonth + "/" + cDay + "/" + cYear);
System.out.println("Your birthday is " + bMonth + "/" + bDay + "/" + bYear);
// calculates and prints age
if (cMonth > bMonth) {
int age = cYear - bYear;
System.out.println("You are " + age + " years old ");
} else if (cMonth < bMonth) {
int age = (cYear - bYear);
System.out.println("You are " + age + " years old ");
} else if (cMonth == bMonth && cDay > bDay) {
int age = cYear - bYear;
System.out.println("You are " + age + " years old.");
} else if (cMonth == bMonth && cDay < bDay) {
int age = (cYear - bYear) - 1;
System.out.println("You are " + age + " years old. ");
} else if (cYear == bYear) {
System.out.println("You are not even a year old.");
} else {
System.out.println("Your input was invalid");
}
} catch (IOException IOE) {
} catch (NumberFormatException NFE) {
System.out.println("Please enter a numeric value without spaces, letters, or special characters");
}
}
public static void retry() {
BufferedReader delta = new BufferedReader(new InputStreamReader(System.in));
try {
boolean valid = false;
while (!valid) {
System.out.println("Would you like to try again? 1) Yes or 2) No");
System.out.println("Please enter a number");
String retry = delta.readLine();
int trynum = Integer.parseInt(retry);
if (trynum < 1 || trynum > 2) {
System.out.println("Your input was invalid. Please enter 1 or 2.");
continue;
} else if (trynum == 1) {
prompt();
} else if (trynum == 2) {
System.out.println("Okay then.");
System.exit(0);
} else {
System.out.println("Invalid");
continue;
}
}
} catch (IOException IOE) {
} catch (NumberFormatException NFE) {
System.out.println("Please enter a number");
}
}
}
You are initializing a new cMonth variable when reading the months value on the line
System.out.println("Please enter the current month as a numeric value");
String Month = delta.readLine();
int cMonth = Integer.parseInt(Month);
Just remove the initialisation of the cMonth local variable as you want to refer to a global variable.
System.out.println("Please enter the current month as a numeric value");
String Month = delta.readLine();
cMonth = Integer.parseInt(Month);
Just to provide you the working source code I am pasting working solution:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class BroDoYouEvenAge {
// add in try-catch statements x
// only numeric values x
// leap year
// loop if invalid
// loop if day is invalid
// less than 1 or greater than max day x
// add in no spaces or letters x
// VALIDATION FOR MONTHS x
// loop if invalid
// same year x
// try again x
// loop if invalid
static int cDay;
static int cMonth;
static int bYear;
static int bMonth;
static int bDay;
public static void main(String[] args) {
run();
}
public static void run() {
prompt();
retry();
}
public static void prompt() {
BufferedReader delta = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.println("Please enter the current year");
String Year = delta.readLine();
int cYear = Integer.parseInt(Year);
// prompts the user for the current month as a numeric value
boolean validmonth = false;
while(!validmonth) {
System.out.println("Please enter the current month as a numeric value");
String Month = delta.readLine();
cMonth = Integer.parseInt(Month);
if(cMonth < 1 || cMonth > 12) {
System.out.println("Your input was invalid");
} else {
validmonth = true;
}
}
// prompts the user for the current day as a numeric value
boolean validday = false;
while(!validday) {
System.out.println("Please enter the current day as a numeric value");
String Day = delta.readLine();
cDay = Integer.parseInt(Day);
if(cDay < 1) {
System.out.println("Your input was invalid");
} else if(cDay > 31) {
System.out.println("Your input was invalid");
} else if(cMonth == 4 && cDay > 30) {
System.out.println("Your answer is invalid");
} else if(cMonth == 6 && cDay > 30) {
System.out.println("Your answer is invalid");
} else if(cMonth == 9 && cDay > 30) {
System.out.println("Your answer is invalid");
} else if(cMonth == 11 && cDay > 30) {
System.out.println("Your answer is invalid");
} else {
validday = true;
}
}
// prompts the user for their birth year
boolean validYear = false;
while(!validYear) {
System.out.println("Please enter your birth year");
String Year2 = delta.readLine();
bYear = Integer.parseInt(Year2);
if(bYear > cYear) {
System.out.println("Your answer was invalid");
} else {
validYear = true;
}
}
// does not allow user to input a value greater than their current
// year
// loops if invalid
// prompts the user for their birth month
boolean _validmonth = false;
while(!_validmonth) {
System.out.println("Please enter your birth month as a numeric value");
String Month2 = delta.readLine();
bMonth = Integer.parseInt(Month2);
if(bMonth < 1 || bMonth > 12) {
System.out.println("Your answer was invalid");
} else {
_validmonth = true;
}
}
// prompts the user for their birth day
boolean _validday = false;
while(!_validday) {
System.out.println("Please enter the day you were born as a numeric value");
String Day2 = delta.readLine();
bDay = Integer.parseInt(Day2);
// prints out collected data
if(bMonth == 4 && bDay > 30) {
System.out.println("Your answer is invalid");
} else if(bMonth == 6 && bDay > 30) {
System.out.println("Your answer is invalid");
} else if(bMonth == 9 && bDay > 30) {
System.out.println("Your answer is invalid");
} else if(bMonth == 11 && bDay > 30) {
System.out.println("Your answer is invalid");
} else {
_validday = true;
}
}
System.out.println("The current date is " + cMonth + "/" + cDay + "/" + cYear);
System.out.println("Your birthday is " + bMonth + "/" + bDay + "/" + bYear);
// calculates and prints age
if(cMonth > bMonth) {
int age = cYear - bYear;
System.out.println("You are " + age + " years old ");
} else if(cMonth < bMonth) {
int age = cYear - bYear;
System.out.println("You are " + age + " years old ");
} else if(cMonth == bMonth && cDay > bDay) {
int age = cYear - bYear;
System.out.println("You are " + age + " years old.");
} else if(cMonth == bMonth && cDay < bDay) {
int age = cYear - bYear - 1;
System.out.println("You are " + age + " years old. ");
} else if(cYear == bYear) {
System.out.println("You are not even a year old.");
} else {
System.out.println("Your input was invalid");
}
} catch(IOException IOE) {
} catch(NumberFormatException NFE) {
System.out.println("Please enter a numeric value without spaces, letters, or special characters");
}
}
public static void retry() {
BufferedReader delta = new BufferedReader(new InputStreamReader(System.in));
try {
boolean valid = false;
while(!valid) {
System.out.println("Would you like to try again? 1) Yes or 2) No");
System.out.println("Please enter a number");
String retry = delta.readLine();
int trynum = Integer.parseInt(retry);
if(trynum < 1 || trynum > 2) {
System.out.println("Your input was invalid. Please enter 1 or 2.");
continue;
} else if(trynum == 1) {
prompt();
} else if(trynum == 2) {
System.out.println("Okay then.");
System.exit(0);
} else {
System.out.println("Invalid");
continue;
}
}
} catch(IOException IOE) {
} catch(NumberFormatException NFE) {
System.out.println("Please enter a number");
}
}
}

MIlitary Time Validating

I want to make sure that there are 5 characters in what the user inputs to change it to a military time and pretty much this is the format ##:## (with the colon as well) and this is part of my code, but I cannot make it work.
Any help will be great - thanks.
public Time(String militaryTime)
{
//Check to make sure something was entered
if (militaryTime == null || !militaryTime.matches("^\\d{2}:\\d{2}$"))
{
System.out.println(
"You must enter a valid miliary time." );
}
//Check to make sure there are 5 characters
else
{
//Check to make sure the colon is in the right spot
if (!Character.isDigit(militaryTime.charAt(2)))
{
System.out.println(militaryTime +
" is not a valid miliary time." );
}
//Check to make sure all other characters are digits
else if (!Character.isDigit(militaryTime.charAt(0)))
{
System.out.println(militaryTime +
" is not a valid miliary time." );
}
else if (!Character.isDigit(militaryTime.charAt(0)))
{
System.out.println(militaryTime +
" is not a valid miliary time." );
}
else if (!Character.isDigit(militaryTime.charAt(0)))
{
System.out.println(militaryTime +
" is not a valid miliary time." );
}
else if (!Character.isDigit(militaryTime.charAt(0)))
{
System.out.println(militaryTime +
" is not a valid miliary time." );
}
else
{
//this separates hours and minutes
hours = Integer.parseInt(militaryTime.substring(0,2));
//validate hours and minutes are valid values
if(hours > 23)
{
System.out.println(militaryTime +
" is not a valid miliary time." );
}
else if(minutes > 59)
{
System.out.println(militaryTime +
" is not a valid miliary time." );
}
//convert military time to conventional time
//for afternoon times
else if (hours > 12)
{
hours = hours - 12;
afternoon = true;
System.out.println(this.toString());
}
//account for midnight
else if (hours == 0)
{
hours = 12;
System.out.println(this.toString());
}
//account for noon
else if (hours == 12)
{
afternoon = true;
System.out.println(this.toString());
}
//morning times don't need converting
else
{
System.out.println(this.toString());
}
}
}
}
The simplest way in most languages is to use a regular expression:
if (militaryTime == null || !militaryTime.matches("^\\d{2}:\\d{2}$")) {
System.out.println(militaryTime + " is not a valid military time.");
}
This will not check that the hour is between 0-24 or that the minute is between 0-60, but your code doesn't appear to care either.
Alternately you can use the Java time API:
try {
DateTimeFormatter.ofPattern("HH:mm").parse(militaryTime)
}
catch (DateTimeParseException e) {
System.out.println(militaryTime + " is not a valid military time.");
}
This will verify that it's fully compliant.
try this code
public static boolean isMilitoryTmeString(String militaryTime) {
// Check to make sure something was entered
if (militaryTime == null) {
return false;
}
// Check to make sure there are 5 characters
if (militaryTime.length() != 5) {
return false;
}
// Storing characters into char variable
char hourOne = militaryTime.charAt(0);
char hourTwo = militaryTime.charAt(1);
char colon = militaryTime.charAt(2);
char minuteOne = militaryTime.charAt(3);
char minuteTwo = militaryTime.charAt(4);
//first position of hour must be 0 or 1 or 2
if (hourOne != '0' && hourOne != '1' && hourOne != '2') {
return false;
}
//if first position of hour is 0 or 1 then second
//position must be 0-9
if (hourOne == '0' || hourOne == '1') {
if (hourTwo < '0' || hourTwo > '9') {
return false;
}
//if hourOne equal 2 then second position must be 0-3
} else {
if (hourTwo < '0' || hourTwo > '3') {
return false;
}
}
//third position must be colon
if (colon != ':') {
return false;
}
// fourth position must be 0-5
if (minuteOne < '0' || minuteOne > '5') {
return false;
}
//fifth position must be 0-9
if (minuteTwo < '0' || minuteTwo > '9') {
return false;
}
// String is valid military time
return true;
}

Java - Looping Number Strings

You all were so helpful yesterday in getting over my first hump in this problem that I wanted to see if there's a way I can modify my final product (Apologies if my formatting is off - Still trying to get indentations correct in my IDE.
import javax.swing.JOptionPane;
public class NumberLoops {
public static void main(String[] args) {
String strNum1;
String strNum2;
int intNum;
boolean isValid = true;
boolean isError = false;
strNum1 = JOptionPane.showInputDialog ("Enter Number String");
for (int i=0; i<strNum1.length(); i++) {
char c = strNum1.charAt(i);
if (c == '-'){
JOptionPane.showMessageDialog(null, "Negative Digit Found - Enter Positive Numbers Only", "Error", JOptionPane.INFORMATION_MESSAGE);
isValid = false;
break;
}
}
if (isValid){
for (int i=0; i<strNum1.length(); i++) {
char c = strNum1.charAt(i);
intNum = Character.getNumericValue(c);{
if (intNum > 0 && intNum <= 9){
isError = true;
break;
}
}
}
}
if (isError){
int aDigit,totalNum=0;
char chDigit;
strNum2 = String.valueOf(strNum1);
for (int count=0; count<strNum1.length();count++){
chDigit = strNum2.charAt(count);
aDigit = Character.getNumericValue(chDigit);
totalNum += aDigit;
if (aDigit > 0 && aDigit <= 9){
System.out.print(aDigit + " ");
}
}
System.out.print(" " + "The sum is: " + totalNum);
}
}
}
My question concerns the last loop. It functions as desired by printing to the console if I enter say 123123 into the message prompt, it lists that string as 1 2 3 1 2 3 and then the total of 12.
But that is in the console itself. What I'm trying to wrap my mind around is getting it to display in a message box instead of the console.
I'm guessing I need to create a new string like (incoming pseudocode):
if (aDigit > 0 && aDigit <= 9){
strNum3 = everycharinStr2 + " "
Which is the part I guess I'm not grasping.
FYI, this is a homework assignment so I don't necessarily want an outright answer, but I feel I am so close that I need some extra eyes on it to see if there's anything I can do. (I have read up on arrays and such but we aren't at that point yet so I don't think I'll go down that road quite yet.)
You only have to make a little change in your code:
strNum2 = String.valueOf(strNum1);
String resultString = "";
for (int count=0; count<strNum1.length();count++){
chDigit = strNum2.charAt(count);
aDigit = Character.getNumericValue(chDigit);
totalNum += aDigit;
if (aDigit > 0 && aDigit <= 9){
System.out.print(aDigit + " ");
resultString += aDigit + " ";
}
}
JOptionPane.showMessageDialog(null, resultString);
Create a new String and in each iteration append the number to this String, then show it in a dialog.
The errors are commented out.
//if (intNum > 0 && intNum <= 9){
if (intNum < 0 || intNum > 9){
isError = true;
break;
}
//if (aDigit > 0 && aDigit <= 9){
if (aDigit >= 0 && aDigit <= 9){
System.out.print(aDigit + " ");
//resultString+ = aDigit + " ";
resultString += "" + aDigit;
}
//if (isError) {
if (!isError) {
Just use a JLabel!
Since your already using swing, this would be your best choice. But then you'd need a frame and panel, so if you don't already have that, don't do this.
JLabel label = new JLabel()
label.setText("Random Text!")
You can also do this, with a pop up:
JOptionPane.showMessageDialog(null, "My String!");

Number of Leap Years within two specific years

I have a small problem. I figured out how to solve this program, but I can't get the output to output ALL the leap years in a table format. Instead, the output shoots out the leap years one at a time, which is something I don't want with my program.
What could be the problem?
EDIT:
I'm trying to get all the years to pop out using a "JOptionPane" message box (JOptionPane.showMessageDialog(null, " ");), but I keep getting only one output per box and many boxes... compared to all the outputs in just one box.
Here is the code:
String enterYear = JOptionPane.showInputDialog(null, "Enter the starting year: \nExample: 2015"); // User enters an input (Year)
String enterLastYear = JOptionPane.showInputDialog(null, "Enter the ending year: ");
int i = Integer.parseInt(enterYear);
if (Integer.parseInt(enterYear) < Integer.parseInt(enterLastYear)){
for (i = Integer.parseInt(enterYear); i < Integer.parseInt(enterLastYear); i += 4){
if(i % 400 == 0 || i % 4 == 0) {
JOptionPane.showMessageDialog(null, i + "\n");
}
}
} else {
JOptionPane.showMessageDialog(null, "Error: Starting Year is greater than Ending Year!");
}
}
}
You Simply need to build the message before passing it to the JOptionPane.
Sample Code:
public class LeapYearTest {
public static void main(String[] args) {
LeapYearTest leapYearTest = new LeapYearTest();
leapYearTest.showLeapYears(2000, 2020);
leapYearTest.showLeapYears(2000, 2000);
}
private void showLeapYears(int start, int end) {
StringBuffer msg = new StringBuffer();
if (start < end) {
msg.append("<html><table><tr><td><b>Leap Years</b></td></tr>");
for (int i = start; i < end; i++) {
if(i % 400 == 0 || i % 4 == 0) {
msg.append("<tr><td>" + i + "</td></tr>");
}
}
msg.append("</table></html>");
} else {
msg.append("Error: Starting Year is greater than Ending Year!");
}
JOptionPane.showMessageDialog(null, msg.toString());
}
}
Outputs:
I think you should replace i += 4 with i++. Also correct formula for leap year is
year % 4 == 0 && year % 100 != 0 || year % 400 == 0
I guess you can apply this logic
public void calculateLeapYears(int fromYear,int tillYear){
int count=0;
int firstLeapYear;
if(fromYear% 4==0)
firstLeapYear=fromYear;
else
firstLeapYear=fromYear+(4-fromYear%4);
for(int i=firstLeapYear;i<=tillYear;i+=4)
count++;
System.out.println(count);
}

Finding the count of an variable using switch Statment

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

Categories