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;
}
Related
This is on day four of advent of code part two...
I tried out the sample input they gave and it was correct and I used the input I have and comes out wrong every time
What I see 1
What I see 2
There is more below but its what happens after you solve the first part
Advent of code day 4
Puzzle input
The input differs by user but the code should be the same no matter the input
byr (Birth Year) - four digits; at least 1920 and at most 2002.
iyr (Issue Year) - four digits; at least 2010 and at most 2020.
eyr (Expiration Year) - four digits; at least 2020 and at most 2030.
hgt (Height) - a number followed by either cm or in:
If cm, the number must be at least 150 and at most 193.
If in, the number must be at least 59 and at most 76.
hcl (Hair Color) - a # followed by exactly six characters 0-9 or a-f.
ecl (Eye Color) - exactly one of: amb blu brn gry grn hzl oth.
pid (Passport ID) - a nine-digit number, including leading zeroes.
cid (Country ID) - ignored, missing or not.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
File inputText = new File("src/input.txt");
Scanner sc = new Scanner(inputText);
ArrayList<ArrayList> ids = new ArrayList<>();
ArrayList<ArrayList> attributes = new ArrayList<>();
while (sc.hasNextLine()) {
String builtString = "";
String input = "1";
while(input.length() != 0 && sc.hasNextLine()) {
input = sc.nextLine();
builtString += input + " ";
}
String[] temp = builtString.split(" ");
ArrayList<String> tempIds = new ArrayList<>();
ArrayList<String> tempAttributes = new ArrayList<>();
for (String i : temp) {
tempIds.add(i.split(":")[0]);
tempAttributes.add(i.split(":")[1]);
}
ids.add(tempIds);
attributes.add(tempAttributes);
}
System.out.println(ids);
System.out.println(attributes);
int valid = 0;
for (int a = 0; a < ids.size(); a++) {
int has = 0;
for (int j = 0; j < ids.get(a).size(); j++) {
String id = ids.get(a).get(j).toString();
String attribute = attributes.get(a).get(j).toString();
if (id.contains("ecl")) {
if (attribute.contains("blu") || attribute.contains("brn") || attribute.contains("gry") || attribute.contains("grn") || attribute.contains("hzl") || attribute.contains("oth")) {
System.out.println(attribute + " is an eye color");
has++;
} else {
System.out.println(attribute + " is not an eye color");
}
has++;
}
if (id.contains("pid")) {
if (attribute.length() == 9) {
try {
Integer.parseInt(attribute);
System.out.println(attribute + " of pid attribute is valid ");
has++;
} catch (Exception e) {
System.out.println(attribute + " of pid attribute is not valid");
}
}
has++;
}
if (id.contains("eyr")) {
int at = Integer.parseInt(attribute);
if (at >= 2020 && at <= 2030) {
System.out.println(attribute + " attribute of eyr is valid");
has++;
} else {
System.out.println(attribute + " attribute of eyr is not valid");
}
has++;
}
if (id.contains("hcl")) {
boolean isValid = false;
if (attribute.contains("#")) {
for (char c : attribute.toCharArray()) {
if (attribute.length() == 7) {
if ((c >= 'a' && c <= 'f') || c == '#') {
isValid = true;
} else if (Character.isDigit(c)) {
isValid = true;
} else {
isValid = false;
break;
}
}
}
}
if (isValid) {
has++;
}
System.out.println(attribute + " hcl is " + isValid);
has++;
}
if (id.contains("byr")) {
int date = Integer.parseInt(attribute);
if (date >= 1920 && date <= 2002) {
System.out.println(attribute + " byr attribute is valid");
has++;
} else {
System.out.println(attribute + " byr attribute is not valid");
}
has++;
}
if (id.contains("iyr")) {
int date = Integer.parseInt(attribute);
if (date >= 2010 && date <= 2020) {
has++;
} else {
System.out.println(attribute + " iyr is false");
}
has++;
}
if (id.contains("hgt")) {
boolean isValid = false;
String type = attribute.replaceAll("[^A-Za-z]", "");
int amount = Integer.parseInt(attribute.replaceAll("[^0-9]", ""));
if (type.equals("in")) {
if (amount >= 59 && amount <= 76) {
isValid = true;
has++;
}
} else if (type.equals("cm")) {
if (amount >= 150 && amount <= 193) {
isValid = true;
has++;
}
}
System.out.println(attribute + " hgt is " + isValid);
has++;
}
}
System.out.println();
if (has >= 14) {
valid++;
}
}
System.out.println(valid);
System.out.println("End");
}
}
you forgot the 'amb' eye colour. If you add this to the if statement on line 41 it should work
if (attribute.contains("amb") || attribute.contains("blu") || attribute.contains("brn") || attribute.contains("gry") || attribute.contains("grn") || attribute.contains("hzl") || attribute.contains("oth")) {
Made a program that prints if a number is weird or not. If the number is odd, it's weird. If the number is even and inclusively between 2 and 5, it is not weird. If it's even and inclusively between 6 and 20, it's weird, and if it's even and greater than 20, it's not weird. The problem I'm having here is that instead of the output displaying "This number is weird/not weird", I get "Weird" or "Not Weird" on one line, followed by "This number is 0" if it's even, or "This number is 1" if it's odd.
public Weird(int num)
{
n = num;
}
public int EvenOrOdd()
{
int check = n % 2;
int answer = n / 2;
if (check == 0 && answer >= 2 && answer <= 5)
{
System.out.println("Not Weird");
}
else if (check == 0 && answer >= 6 && answer <= 20)
{
System.out.println("Weird");
}
else if (check == 0 && answer > 20)
{
System.out.println("Not Weird");
}
else if (check != 0)
{
System.out.println("Weird");
}
return check;
}
public static void main(String[] args)
{
Weird w = new Weird(32);
Weird a = new Weird(21);
System.out.println("This number is " + w.EvenOrOdd());
System.out.println("This number is " + a.EvenOrOdd());
}
You actually return int which is value of check field. This is either 1 or 0.
When you call this line-
System.out.println("This number is " + w.EvenOrOdd());
System.out.println("This number is " + a.EvenOrOdd());
It prints either This number is 0 or This number is 1.
You can get desired output by two ways-
Way 1-
Change return type of method to void EvenOrOdd() like-
public void EvenOrOdd()
{
int check = n % 2;
int answer = n / 2;
if (check == 0 && n >= 2 && n<= 5)
{
System.out.println("Not Weird");
}
else if (check == 0 && n>= 6 && n<= 20)
{
System.out.println("Weird");
}
else if (check == 0 && n> 20)
{
System.out.println("Not Weird");
}
else if (check != 0)
{
System.out.println("Weird");
}
}
and call method in main as-
public static void main(String[] args)
{
Weird w = new Weird(32);
Weird a = new Weird(21);
w.EvenOrOdd();
a.EvenOrOdd();
}
Way 2- Change return type of method to String as-
public String EvenOrOdd()
{
int check = n % 2;
int answer = n / 2;
if (check == 0 && n>= 2 && n<= 5)
{
return "Not Weird";
}
else if (check == 0 && n>= 6 && n<= 20)
{
return "Weird";
}
else if (check == 0 && n> 20)
{
return "Not Weird";
}
else
{
return "Weird";
}
}
And main method remains same-
public static void main(String[] args)
{
Weird w = new Weird(32);
Weird a = new Weird(21);
System.out.println("This number is " + w.EvenOrOdd());
System.out.println("This number is " + a.EvenOrOdd());
}
You should return that string rather than printing it. In your function, you are returning an int but rather you should write a String. Besides that everything looks good but you can decrease the number of check like below:
public Weird(int num)
{
n = num;
}
public String EvenOrOdd()
{
int check = n % 2;
if (check == 1 || (check == 0 && n >= 6 && n <= 20)) {
return "Weird";
}else{
return "Not Weird";
}
}
public static void main(String[] args)
{
Weird w = new Weird(32);
Weird a = new Weird(21);
System.out.println("This number is " + w.EvenOrOdd());
System.out.println("This number is " + a.EvenOrOdd());
}
The value you return from a method will kind of "replace" the method call. Because you returned check:
return check;
The calls:
System.out.println("This number is " + w.EvenOrOdd());
System.out.println("This number is " + a.EvenOrOdd());
are basically:
System.out.println("This number is " + 0);
System.out.println("This number is " + 1);
You seem to be confused about returning and printing. Your method should look like this:
public String EvenOrOdd()
{
int check = n % 2;
int answer = n / 2;
if (check == 0 && n >= 2 && n <= 5)
{
return "Not Weird";
}
else if (check == 0 && n >= 6 && n <= 20)
{
return "Weird";
}
else if (check == 0 && n > 20)
{
return "Not Weird";
}
else
{
return "Weird";
}
}
Now the two calls is basically:
System.out.println("This number is " + "Weird");
System.out.println("This number is " + "Not Weird");
Can someone explain how I can end the program after hitting the 'capacity exceeded' message without using a break or system.exit, but continue to prompt for 'leaving' and 'entering' if the message is not reached?
Also, for the 'capacity exceeded' message it also displays the totalPeople. totalPeople in this section becomes however many people I enter to leave or enter. How can I make so it's the totalPeople stored before I enter the leave or enter values to make it exceed capacity?
int numLeaving = Integer.parseInt(JOptionPane.showInputDialog("number leaving"));
int numEntering = Integer.parseInt(JOptionPane.showInputDialog("number entering:"));
while (totalPeople <= 65 && totalPeople >= 0) {
try {
if (numLeaving >= 0 && numEntering >= 0) {
totalPeople = (totalPeople + numEntering) - numLeaving;
JOptionPane.showMessageDialog(null,"Total people = " + totalPeople);
}
else {
JOptionPane.showMessageDialog(null,"Invalid data");
}
}
catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null,"Enter numbers only");
}
if (totalPeople > 65) {
JOptionPane.showMessageDialog(null,"Capacity exceeded\n" + "Total people = " + totalPeople);
}
numLeaving = Integer.parseInt(JOptionPane.showInputDialog("number leaving"));
numEntering = Integer.parseInt(JOptionPane.showInputDialog("number entering:"));
}
I think you should save your limit of people that could enter in a constant. Like this:
static final int maximumPeople = 65;
So now you can use it for conditions in your loops and whatever you want:
while (totalPeople <= maximumPeople && totalPeople >= 0)
{
//code
}
if (totalPeople > maximumPeople) {
//code
}
And another variable that you are going to modify, in your case, totalPeople. In this case, you can show your message of the total of people that can enter:
if (totalPeople > maximumPeople)
{
JOptionPane.showMessageDialog(null,"Capacity exceeded\n" + "Total people = " + maximumPeople);
}
But it also will leaves your loop because you are using totalPeople (the real number of people that has entered).
I expect it will be helpful for you!
To do not continue looping, we have to make the looping condition false:
if (totalPeople > 65) {
JOptionPane.showMessageDialog(null,"Capacity exceeded\n" + "Total people = " + totalPeople);
totalPeople = -1;
}
The rest of loop code will be executed, but it will not entering while loop again.
If you want to keep the value of totalPeople, the easiest way is to add a boolean variable and use it in the condition of looping:
boolean exit= false;
while (totalPeople <= 65 && totalPeople >= 0 && !exit) {
// ..
if (totalPeople > 65) {
JOptionPane.showMessageDialog(null,"Capacity exceeded\n" + "Total people = " + totalPeople);
exit= true;
}
// ..
Put the current code in a while loop and store the totalPeople in another variable.
I have this code:
import java.util.*;
import java.io.*;
public class LetterPattern{
// value for letter when there is no match
public static final char UNRECOGNIZED_LETTER = ' ';
// size of pattern array
public static final int PATTERN_SIZE = 10;
// size of grid array
public static final int GRID_SIZE = PATTERN_SIZE + 2;
/*
To hold the pattern, its features, and the letter
it represents. If the pattern does not match any
of the letter specifications, then the letter char
is a blank.
*/
int[][] grid;
int
massbottom,
corners,
tees;
char
letter;
// default constructor
// grid will be created as a 12x12 array of 0's
// the integer data members are initialized to 0
// by default already; letter is set to ' '
public LetterPattern()
{
grid = new int[GRID_SIZE][GRID_SIZE];
letter = UNRECOGNIZED_LETTER;
}
/*
precondition: assumes sc is not null and has a least one
more line of text in it.
postcondition: grid is loaded with 0's and 1's according to
the discussion in the project description based on what
remains in the input Scanner sc.
YOU HAVE TO CODE THIS.
*/
public void loadPattern(Scanner sc)
{
int r = 1; //row number
while(sc.hasNextLine())
{
//read in line
String gridFill = sc.nextLine();
for(int i = 0; i < GRID_SIZE; i++)
{
if(gridFill.charAt(i) == '*')
{
grid[r][i] = 1;
}
else if(gridFill.charAt(i) == '$')
{
//ignore rest of the line, fill it with 0s
for(int k = i; k < GRID_SIZE; k++)
{
grid[r][k] = 0;
}
}
else
{
grid[r][i] = 0;
}
}
r++;
if( r == 12)
{
break;
}
}
sc.close();
}
/*
precondition: assumes the grid array is not null and is a 12x12
array with 0's and 1's.
postcondition: the instance specific data members, massbottom,
corners, and tees are calculated from the current contents of
grid according to the project specification.
YOU HAVE TO CODE THIS.
*/
public void extractFeatures()
{
//read in row by row, looking for corners and tees, if it is last row, then do massbottom.
for(int row = 1; row < PATTERN_SIZE + 1; row++)
{
for(int column = 1; column < PATTERN_SIZE +1; column++)
{
int squareValue = grid[row][column];
if(row == PATTERN_SIZE)
{
//count 1s for the massbottom
if(squareValue == 1)
{
massbottom++;
}
}
if(squareValue == 1)
{ //look for corners/tees
//check north of vertex
int northSquare = grid[row-1][column];
//check south of vertex
int southSquare = grid[row+1][column];
//check east of vertex
int eastSquare = grid[row][column+1];
//check west of vertex
int westSquare = grid[row][column-1];
int sumSquares = westSquare + eastSquare + southSquare + northSquare;
//Counts the squares around the vertex, if there are only 2 "1's", then it is a corner, if three then a tee.
//any more or less is invalid.
if(sumSquares == 2)
{
//checks for valid corner
if(westSquare == 1 && northSquare == 1)
{
corners++;
break;
}
else if(westSquare == 1 && southSquare == 1)
{
corners++;
break;
}
else if(southSquare == 1 && eastSquare == 1)
{
corners++;
break;
}
else if(eastSquare ==1 && northSquare == 1)
{
corners++;
break;
}
}
else if(sumSquares == 3)
{
//checks for valid tee
if(westSquare == 1 && northSquare == 1 && southSquare == 1)
{
tees++;
break;
}
else if(westSquare == 1 && southSquare == 1 && eastSquare == 1)
{
tees++;
break;
}
else if(southSquare == 1 && eastSquare == 1 && northSquare == 1)
{
tees++;
break;
}
else if(eastSquare ==1 && northSquare == 1 && westSquare == 1)
{
tees++;
break;
}
}
}
}
}
}
/*
precondition: assumes the massbottom, corners, and tees
data members have been correctly calculated from the
current contents of the grid.
postcondition: letter is assigned either the UNRECOGNIZED_LETTER
value if the features do not match any of the letter features,
or the letter whose features are matched.
YOU HAVE TO CODE THIS.
*/
public void classifyLetter()
{
//massbottom of 1 possible letters are "F', "I", "P", "T", and "Y".
if(massbottom == 1)
{ //check for number of corners and tees to validate a letter
if(corners == 1 && tees == 1)
{
letter = 'F';
}
else if(corners == 0 && tees == 0)
{
letter = 'I';
}
else if(corners == 3 && tees == 1)
{
letter = 'P';
}
else if(corners == 0 && tees == 1)
{
letter = 'T';
}
else if(corners == 2 && tees == 1)
{
letter = 'Y';
}
}
//massbottom of 2 possible letters are "A", "H", and "M"
else if(massbottom == 2)
{ //check for number of corners and tees to validate a letter
if(corners == 2 && tees == 2)
{
letter = 'A';
}
else if(corners == 0 && tees == 2)
{
letter = 'H';
}
else if(corners == 2 && tees == 1)
{
letter = 'M';
}
}
//massbottom > 2 possible letters are "B", "C", "E", "G", "L", and "S".
else if(massbottom > 2)
{ //check for number of corners and tees to validate a letter
if(corners == 4 && tees == 2)
{
letter = 'B';
}
else if(corners == 2 && tees == 0)
{
letter = 'C';
}
else if(corners == 2 && tees == 1)
{
letter = 'E';
}
else if(corners == 3 && tees == 1)
{
letter = 'G';
}
else if(corners == 1 && tees == 0)
{
letter = 'L';
}
else if(corners == 4 && tees == 0)
{
letter = 'S';
}
}
else
{
letter = UNRECOGNIZED_LETTER;
}
}
// getter functions for the massbottom, tees, corners, and
// the matching letter
public int getMassbottom(){ return massbottom;}
public int getCorners(){ return corners;}
public int getTees(){ return tees;}
public char getLetter(){ return letter;}
/*
pre: grid is not null
post: grid is not modified its full contents(all 12 rows of 12 columns)
has been printed to the screen, line by line
YOU MUST CODE THIS.
*/
public void printPatternToScreen()
{
//print out the grid
for (int i = 0; i < GRID_SIZE; i++)
{
for (int j = 0; j < GRID_SIZE; j++)
{
System.out.print(" " + grid[i][j]);
}
System.out.println("");
}
}
/*
pre: grid, massbottom, corners, tees, and letter are all
consistently loaded;
patternNum indicates which number pattern this is from the
input file
post: the values of massbottom, corners, tees, and letter are
reported to standard out labeled with patternNum
*/
public void reportResultsToStdout(int patternNum){
System.out.println("\nResults for pattern# " + patternNum + "\n");
printPatternToScreen();
System.out.println("\n Massbottom = " + massbottom
+ "\n Num of Corners = " + corners +
"\n Num of Tees = " + tees);
System.out.print("\n These feature values ");
if (letter == LetterPattern.UNRECOGNIZED_LETTER)
System.out.println("do not match any letter.");
else
System.out.println("match " + letter);
}
/*
This main can be used to obtain your output.
It sets up a Scanner instance from a command line argument,
creates a LetterPattern instance, and repeatedly loads the
LetterPattern instance from the Scanner and
analyzes it. It displays the results to the standard out.
*/
public static void main(String[] args){
Scanner src;
LetterPattern lp = new LetterPattern();
int
patternNumber = 1;
if (args.length > 0){
try{
src = new Scanner(new File(args[0]));
while (src.hasNextLine()){
lp.loadPattern(src);
lp.extractFeatures();
lp.classifyLetter();
lp.reportResultsToStdout(patternNumber);
patternNumber++;
}
}
catch(NullPointerException e){
System.out.println("The file name may have been a null string.\nProgram Terminating." + e);
}
catch(FileNotFoundException e){
System.out.println("No file with the name " + args[0]
+ "\nProgram terminating." + e);
}
}
else // args is empty
System.out.println("You must supply the input file name on"
+ " the command line.");
}
}
I am trying to get my "letters.txt" file to be read in from the command line via eclipse. I've done some research and found out how to input the command line argument via Run configurations. Now when I go to run it, all I get is this message
Program terminating.java.io.FileNotFoundException: letters.txt (The system cannot find the file specified)
I have my file located in the same level folder where src and bin is located. ( Letter_Pattern > bin | src |classpath| letters)
Also, I did copy my java file over to my laptop and remade a project, and then just imported the java file in. Will that have affected something?
When running the program with a full path filename "D:\path\to\file\letters.txt" it's seems to work. Don't forget double quotes in case of space in one of your folder name.
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.