public void askForDate(Scanner in) {
System.out.println("Please enter the date that the vehicle entered the car park in this format dd/mm/yyyy :");
String enteredDate = in.nextLine();
//This array will hold the 3 elements of which the date is made up of, day, month and year, and this method returns it.
String[] dateEnteredSplit = enteredDate.split("/");
//I am using the split method to seperate each number, which returns an array, so I am assigning that array to the dateEnteredSplit array.
//dateEnteredSplit = enteredDate.split("/");
//So now the first element holds the day, second the month, and the third element holds the year.
//System.out.println(Arrays.toString(dateEnteredSplit));
//Assigning each element and converting them to integers.
int day = Integer.parseInt(dateEnteredSplit[0]);
int month = Integer.parseInt(dateEnteredSplit[1]);
int year = Integer.parseInt(dateEnteredSplit[2]);
**System.out.println("day: " + day + " month: " + month + " year: " + year);**
//The loop will be entered if any of the values are wrong. which will use recursion to call this method again for a chance to enter the date again.
while (!(day >= 1 && day <= 31) || !(month >= 1 && month <= 12) || !(year > 1000 && year < 5000)) {
**System.out.println("day: " + day + " month: " + month + " year: " + year);**
//Im calling these methods to inform which one specifially was wrong so they know what they need to change.
this.setDay(day);
this.setMonth(month);
this.setYear(year);
dateEnteredSplit[0] = "0";
askForDate(in);
}
//I then assign any correct value into the object attribute because the while loop is either finished or not entered at all.
//No need to use setDay etc. here because the checks have been done above in the while loop.
this.day = day;
this.month = month;
this.year = year;
}
Ok that is a method in a class. It asks for input in the format dd/mm/yyyy
If the first time I input 12/1/1996 it works, but if I enter a wrong date for example like this first, 123/123/123 and the enter a correct date for example 12/1/1996, it still enters the loop.
After debugging, the first line that is bold, the values are different from the second line that is bold, its like the values are changing by their own.
What is the problem here? I have been trying to find out in the past 1 hour.
Thanks in advance!
The problem very likely is in the way you are trying to combine recursive and iterative approach to update values (there is a while loop, that call the function recursively, which may also trigger while loop in next level of call and the previous one will continue calling itself recursively and you will end up with just mess)
There is no real reason to do that recursively, I would do iterative only approach, something like this:
public void askForDate(Scanner in) {
System.out.println("Please enter the date that the vehicle entered the car park in this format dd/mm/yyyy :");
int day, month, year;
do { // We use do-while to get the first read without condition, although setting date to invalid value (like day = 0) and then running standard while loop will work just as fine
String[] dateEnteredSplit = in.nextLine().split("/");
//Assigning each element and converting them to integers.
day = Integer.parseInt(dateEnteredSplit[0]);
month = Integer.parseInt(dateEnteredSplit[1]);
year = Integer.parseInt(dateEnteredSplit[2]);
} while (!(day >= 1 && day <= 31) || !(month >= 1 && month <= 12) || !(year > 1000 && year < 5000));
// Now day month and year variables are set correctly and we can do stuff with it
}
If you insist or recursive approach, the correct way would be to call the function just once:
public void askForDate(Scanner in) {
System.out.println("Please enter the date that the vehicle entered the car park in this format dd/mm/yyyy :");
int day, month, year;
String[] dateEnteredSplit = in.nextLine().split("/");
//Assigning each element and converting them to integers.
day = Integer.parseInt(dateEnteredSplit[0]);
month = Integer.parseInt(dateEnteredSplit[1]);
year = Integer.parseInt(dateEnteredSplit[2]);
if (!(day >= 1 && day <= 31) || !(month >= 1 && month <= 12) || !(year > 1000 && year < 5000)) askForDate(in);
// You need to save day/month/year variables to other than local scope (like this.day = day)
// Otherwise it would just somewhere in recursion stack and you wouldn't be able to use it
}
Just to be complete, keep in mind that date string could be wrong in other way that just number out of range. What if user types 1. 2. 3456 or a/b/c or not even something very different like Hello
At your snippet of code would crash (either throw NumberFormatException when trying to parse non-integer or ArrayIndexOutOfBoundsException when accessing dateEnteredSplit array at element that doesnt exists (there are no '/' in 'Hello'))
Here is what happens. Wrong values on a first while loop iteration make a call to askForDate possible. You receive a second prompt and provide correct input. The second call of askForDate ends as expected. The execution returns again to a while loop, where you still have the first wrongly set values and the process starts again.
If you really do want to use recursion here, you should return a value from your function (dates or boolean flag) and check it in a while loop condition.
Related
I want to create a Java Program that takes a date as input (27,2,2019) and print out what day it was. I am just assuming the usage of Gregorian Calender only. The reference is 1,1,1 which is a Monday. I am unable to complete this. Can someone help me out please. I also took leap years to account. Also, in this project, I am not allowed to import any packages so I should do it normally.
public class sortday
{
public static void main (String [] args)
{
sortdayoftheyear(1,1,2019);
}
public static void sortdayoftheyear(int day, int month, int year)
{
final int [] months = {31,28,31,30,31,30,31,31,30,31,30,31};
{
final int monthnum = 12;
int totaldays=0;
int newmon = month-1; //find which month it is
int monthdays = months[newmon]; // find days of the month
for (int i = 1; i < year; i++)
{
if (i%100 != 0 && i%4 == 0 && i%400 == 0) //check for leap year
{
totaldays = i*366;
}
else
totaldays = i*365;
}
totaldays += (day) + (newmon*monthdays);
if (totaldays%7 == 4)
System.out.println("Sunday");
if (totaldays%7 == 5)
System.out.println("Monday");
if (totaldays%7 == 6)
System.out.println("Tuesday");
if (totaldays%7 == 0)
System.out.println("Wednesday");
if (totaldays%7 == 1)
System.out.println("Thursday");
if (totaldays%7 == 2)
System.out.println("Friday");
if (totaldays%7 == 3)
System.out.println("Saturday");
System.out.println("It had been " + totaldays + " since January 1,AD");
}
}
}
There seems to be more than one bug in your code. I have spotted:
Each time through your for loop you are assigning a new value to totaldays. In this way only the last time through the loop has any effect in the end. I believe you intended every iteration to contribute.
As yole said in a comment, newmon*monthdays is incorrect for the total number of days in the first newmon months of the year. I even think that for February 13 your are counting 13 + 1 * 28, which can’t be right. One suggestion is you loop through the months and add up their lengths.
If the entered year is a leap year, you are always counting 28 days in February. You want to count 29 sometimes. An auxiliary method to determine whether a year is a leap year would come in handy.
If your reference date of January 1, 1 is a Monday, I think you want to print this when the modulo operation in the end yields 1. You are printing Thursday in this case.
I can’t tell if there may be more.
Issues without functional consequences that you should nevertheless want to fix include:
You are not using the constant monthnum, so delete it.
You have a superfluous set of braces around the code piece from the mentioned constant down to System.out.println. Delete those too.
Get your indentation right so you and I can read your code.
When writing code for others to read (including Stack Overflow users), respect the naming conventions. Call the class SortDay or FindDayOfWeek. The method sortDayOfTheYear or printDayOfWeek.
I'm working on a program for school to take a year input from the user and check to see if it is a leap year or not. It should also check to see if the year is prior to 1582 and return an error if it is. I'm having an issue that if the user enters a year between [1582, 1599] that the program halts and doesn't print anything. If I change the value to 1600 it doesn't return anything between [1600, 1639]. Not sure why this behavior is happening. Any help would be appreciated.
import java.util.Scanner;
public class Leapyear {
public static void main(String[] args) {
Scanner Jeff = new Scanner(System.in);
//System.out.print("Run Leapyear progra? Enter true or false: ");
//boolean RunLoop$ = Jeff.nextBoolean();
System.out.print("\nPlease enter a year: ");
int Year = Jeff.nextInt();
//while(RunLoop$ = true)
if (Year <= 1582)
System.out.println("The entered year is prior to the Gregorian Callandar");
else
if (Year % 4 == 0)
if (Year % 400 + Year % 100 == 0)
System.out.println("The entered year is a leapyear");
else
System.out.println("The Entered year is not a leapyear");
}
}
Your if statements are incorrect. I second David's comment and strongly advise to use brackets for every if statement (which is also recommended in the - albeit ancient, but mostly still valid - Code Conventions for the Java Programming Language).
Furthermore, switching to a decent IDE and/or making use of its source code formatting support will greatly help you with these kinds of issues.
A simple (automatic) cleanup leads to the following snippet for your if statements, which is fully equivalent in terms of application logic:
if (Year <= 1582) {
System.out.println("The entered year is prior to the Gregorian Callandar");
} else if ((Year % 4) == 0) {
if (((Year % 400) + (Year % 100)) == 0) {
System.out.println("The entered year is a leapyear");
} else {
System.out.println("The Entered year is not a leapyear");
}
} // else?
You can now clearly see that there won't be any output if Year is greater than 1582 but not divisible by 4.
if you don't use the {} curly brackets for every if and else statement then it will only consider the first line after the condition so in
else
[empty line]
if (Year %4 ==0)
[empty line]
means after else it will do nothing the same after the if because only the first line under it is considered which is empty.
Another problem you'll be having is that your while loop will go forever :) since the boolean value will always remain true. If you want to make user insert a new value each time then just insert at the end of the while loop.
System.out.print("add another year ? ");
RunLoop$ = Jeff.nextBoolean();
Year = Jeff.nextInt();`
or add Jeff.hasnextInt()in the while loop condition instead removing the Boolean entirely so when user enters anything other than an int value the loop breaks.while(Jeff.hasnextInt()) and at the end of the loop.
System.out.print("add another year ? ");
Year = Jeff.nextInt();`
private String twoDigits(int value) {
String result = "";
{
if ((mMinute >= 0) && (mMinute <= 9) && (mSecond >= 0) && (mSecond <= 9)) {
tempmin = ("0" + mMinute );
tempsec = ("0" + mSecond );
} else
tempmin = (mMinute + "");
tempsec = (mSecond + " ");
return tempin+tempsec;
This just doubles the output that I'm looking for and I was wondering, whether or not the issue was with the return statement or the actual method.
I need to call back to this method, twoDigits(mMinute)+":"+twoDigits(mSecond) to get the code to display the time, but instead of being able to display 10:09:08 I keep displaying 10:0908:0908
I was wondering how I should fix my code.
Since there are a lot of tiny mistakes in your code, I'll suggest a slightly different approach. Not sure if this method works, in what I assume is Java, but give it a shot:
private String twoDigits(int value)
{
return value <= 9 ? "0" + value : value;
}
This is actually an if/else abbreviation. Return the following: If value <= 9 then add a zero before the value, else the value.
If there's a risk of negative values being received, you could add this:
return (value >= 0 && value <= 9) ? "0" + value : value;
First, there's Paul's comment about the {} after else to encompass both rows. Then, you are not actually using the value received by the function but rather some global variables (mMinute and mSecond). You create but never use result. Furthermore, your if statement says that if both mMinute AND mSecond are between 0 and 9 then both should be fixed. Since you should use value you only have to check that variable's range and edit it accordingly. On the row tempsec = (mSecond + " "); you add a space.. mistake? Finally, you misspelled tempmin on the return row.
Good luck.
Note that your method has a value parameter. You should use this rather than directly access the fields in your class. Perhaps it might help for you to think about the purpose of the twoDigits() method. It seems to me that it is supposed to take an int value and pad it with a leading zero if the input is only a single digit. Note that my description in the previous sentence does not refer to the member variables that represent minutes and seconds; it only refers to the input value.
Hello. I want to create a function that generates ascending numbers.
For example, if today's date is June 21st, 2013 then the numbers will be 130621001.
The last three digits are ascending numbers, and it'll reset back to 001 on each date.
I can figure out on how to make the date digits, but I'm stuck with those last three digits.
Thank you in advance.
try this, good luck
public static String NextNumber(String currentNumber) {
//assume yymmddnnn
String sDateNum = currentNumber.substring(0, 6);
String sCurrentNum = currentNumber.substring(6,9);
int i = Integer.valueOf("1" + sCurrentNum);
i++;
return sDateNum + String.valueOf(i).substring(1, 4);
}
System.out.println(NextNumber("130621001"));
The real question is how you know what your previous answer was.
today = myDateFormatter(System.currentTimeMillis());
if (today.equals(oldDay)) count++;
else count == 0;
oldDay = today;
If this is a long running process, oldDay and count can be simple fields in your class. If the process exits and restarts, you will need to get your old answers from somewhere and set them to the largest value.
I am trying to set up part of a program that allows a person to view transactions of an account based on the date of the transaction. The user enters the month day and year to view transactions and that is compared to the date that is connected to a given transaction. I am having difficult writing the lines of code that determine if the date is equal
if(aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.MONTH).compareTo(month)==0){
if(aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.DAY_OF_MONTH).compareTo(day)==0){
if(aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.YEAR).compareTo(year)==0){
The error that I am receiving is "cannot invoke compareTo(int) on the primitive type int"
see full code below:
System.out.println("Enter the account number of the account that you want to view transactions for");
number=keyboard.nextLong();
System.out.println("Enter the month day and year of the date that the transactions were completed");
int month=keyboard.nextInt()-1;
int day=keyboard.nextInt();
int year=keyboard.nextInt();
found=false;
try{
for(int i=0;i<aBank.getAccounts().size();i++){
if (aBank.getAccounts().get(i).getAccountNumber().compareTo(number)==0){
found=true;
System.out.println("Below is a list of transactions completed on "+month+ "/" +day+ "/" +year);
for (int j=0;j<aBank.getAccounts().get(i).getTransaction().size();j++){
if(aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.MONTH).compareTo(month)==0){
if(aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.DAY_OF_MONTH).compareTo(day)==0){
if(aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.YEAR).compareTo(year)==0){
aBank.getAccounts().get(i).getTransaction().get(j).toString();
break;
}
}
}
}
For primitive values you can just use ==
aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.YEAR)==year
Just use:
aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.MONTH) == month
If all of the XYZ.getTransDate() returns Calendar, then
XYZ.getTransDate().get(SOMETHING) returns primitive int. Primitives do not have comapreTo method, just use ==
so instead of XYZ.getTransDate().get(MONTH).compareTo(month) == 0 use
XYZ.getTransDate().get(MONTH) == month
This should work:
Calendar transDate = aBank.getAccounts().get(i).getTransaction().get(j).getTransDate();
if (transDate.get(Calendar.YEAR) == year &&
transDate.get(Calendar.MONTH) == month &&
transDate.get(Calendar.DAY_OF_MONTH) == day) {
// do something
}
Even better if you use something like Apache Commons Lang:
if (DateUtils.isSameDay(aBank.getAccounts().get(i).getTransaction().get(j).getTransDate(),
Calendar.getInstance().set(year, month, day)) {
...
}