(Java) An Array of a class - java

I have a class here which gives me back a date in a certain order
what i want to do is make an array of this class with four type of Dates.
May 16, 1984
November 14, 1978
September 21, 1980
July 3, 1987
How can I fit these dates in the Array ????
public class DateArray {
private String month;
private int day;
private int year;
public DateArray(String n, int d, int y){
month = n;
day = d;
year = y;
}
public String toString(){
return month + "/" + day + "/" + year;
}
This is what my Main looks like right now:
DateArray date = new DateArray("jan", 5, 20);
String s = date.toString();
System.out.println(s);
DateArray [] dates = new DateArray[3];
for(int i =0; i<dates.length; i++)
{
System.out.println(dates[i]);
}

You haven't set any values for the array elements in your code example. You need something similar to
dates[0] = new DateArray(month, day, year);
for each element. Also, I suggest that naming a type 'Array' that isn't an array might be confusing.

First, based on your expected results, your DateArray.toString() should look something like1
#Override
public String toString() {
return month + " " + day + ", " + year;
}
Then you can create and display your array with something like
public static void main(String[] args) {
DateArray[] dates = new DateArray[] { new DateArray("May", 16, 1984),
new DateArray("November", 14, 1978),
new DateArray("September", 21, 1980), new DateArray("July", 3, 1987) };
for (DateArray da : dates) {
System.out.println(da);
}
}
And I get (as requested)
May 16, 1984
November 14, 1978
September 21, 1980
July 3, 1987
1The Override annotation can help you if you think you're correctly overriding a super-type method but you aren't. I suggest you always use it.

Related

Bad Operand types for binary operator && when trying to calculate birthdate from current date

I am trying to get a user to input YR MON DAY and then system calculate the current age based on the provided input and show the age on the screen.
Here is the beginning to my code:
static void checkAgeFormat(int current_date, int current_month,
int current_year, int birth_date,
int birth_month, int birth_year) {
int f = 0;
if(current_date <= 01 && current_date => 31) {
System.out.println("Invalid current_date");
f = 1;
}
I am getting a "Bad Operand types for binary operator &&" I cannot figure out why, and I am fairly new to coding.
Thanks for any help
It is >= not => so if(current_date<=1 && current_date>=31)
(don't use 0 as prefix for numbers, it causes them to be interpreted as octal)
What are you trying to return here? The amount of days left before someones birthdate? You could use the between() method of Period class for that.
static void checkAgeFormat(int current_date, int current_month,
int current_year, int birth_date,
int birth_month, int birth_year) {
LocalDate birthDate = LocalDate.of(birth_year, birth_month, birth_date);
long daysLeft = Period.between(LocalDate.now(), birthDate).get(ChronoUnit.DAYS);
}
As I have already mentioned in the comment, the issue is because of the bad symbol, => for the operator. It should be >=. Check this to learn more about operators.
Apart from that, I can see a serious problem with your logic. The way you are validating the date values is a naive way to do it. I suggest you do it using OOTB APIs as shown below:
import java.time.DateTimeException;
import java.time.LocalDate;
public class Main {
public static void main(String[] args) {
// Tests
checkAgeFormat(45, 10, 2017, 10, 10, 2010);
checkAgeFormat(30, 2, 2017, 10, 10, 2010);
checkAgeFormat(31, 4, 2017, 10, 10, 2010);
checkAgeFormat(30, 15, 2017, 10, 10, 2010);
checkAgeFormat(30, 4, 2020, 10, 10, 2010);
}
static void checkAgeFormat(int current_day, int current_month, int current_year, int birth_day, int birth_month,
int birth_year) {
int f = 0;
LocalDate currentDate, birthDate;
try {
currentDate = LocalDate.of(current_year, current_month, current_day);
birthDate = LocalDate.of(birth_year, birth_month, birth_day);
System.out.println("If you see this line printed, the date values are correct.");
// ...Rest of the code
} catch (DateTimeException e) {
System.out.println(e.getMessage());
f = 1;
}
// ...Rest of code
}
}
Output:
Invalid value for DayOfMonth (valid values 1 - 28/31): 45
Invalid date 'FEBRUARY 30'
Invalid date 'APRIL 31'
Invalid value for MonthOfYear (valid values 1 - 12): 15
If you see this line printed, the date values are correct.
isn't it easier to write a function where the user will provide year, month and the day and it will return how old is the user? Below is an example of a function that does it.
public static int getYears(int year, int month, int day)
{
LocalDate yearOfBirth = LocalDate.of(year, month, day);
LocalDate currentDate = LocalDate.now();
Period period = Period.between(yearOfBirth, currentDate);
return period.getYears();
}
you are getting the error because
you are using if (current_date <= 01 && current_date =>31) instead of
if (current_date <= 01 && current_date >=31)
after editing your code will be:
static void checkAgeFormat(int current_date, int current_month, int current_year, int birth_date, int birth_month, int birth_year) {
int f=0
if (current_date <= 01 && current_date >=31){
System.out.println("Invalid current_date");
f=1;
}
}

Find the remaining months in a year

I am trying to find a way to get an array of month for a year(Ex:2017)
The array to be the remaining months in a year only
Is this possible, What is the best way to achieve this
I searched for the answer couldn't find it
ex:{"October","November","December"}
What I have done so far: I am able to get current year
Date now = new Date();
int year = now.getYear();
You should better use new API LocalDate rather than Date, it's easier to use
first, you need to get the current date : here it's 07/10/201
you need to find out many month there is until the end of the year : here it's 2
then you create an array of the size + 1 (+1 is for current month) : here size is 3
then you fill the array with the month of date you have + i month
LocalDate date = LocalDate.now();
int nbMonthRemain = 12 - date.getMonth().getValue();
String[] monthsRemaining = new String[nbMonthRemain + 1];
for (int i = 0; i < monthsRemaining.length; i++) {
monthsRemaining[i] = date.plusMonths(i).getMonth().toString();
}
System.out.println(Arrays.toString(monthsRemaining)); // [OCTOBER, NOVEMBER, DECEMBER]
Tips :
Replace .toString() by :
.getDisplayName(TextStyle.FULL, Locale.ENGLISH); to get [October, November, December]
.getDisplayName(TextStyle.FULL_STANDALONE, Locale.ENGLISH); to get [10, 11, 12]
.getDisplayName(TextStyle.SHORT, Locale.ENGLISH); to get [Oct, Nov, Dec]
...
Use GregorianCalendar.getInstance().get(Calendar.MONTH) to get current month number (For oct you will get 9)
i believe something like below code could help
import java.text.DateFormatSymbols;
import java.util.List;
import java.util.ArrayList;
public List GetLeftMonth(Integer Mon_num){
List<String> monthsList = new ArrayList<String>();
String[] months = new DateFormatSymbols().getMonths();
for (int i = Mon_num; i < months.length; i++) {
String month = months[i];
System.out.println("month = " + month);
monthsList .add(months[i]);
}
return monthsList;
}
public static void main(String[] args) {
LocalDate now = LocalDate.now();
int currentMonth = now.getMonthValue();
int monthsInAYear = 12;
int monthsRemaining = monthsInAYear - currentMonth;
System.out.println(monthsRemaining); // 2
for (int i = currentMonth; i <= monthsInAYear; i++) {
System.out.println(getMonthName(i)); // OCTOBER NOVEMBER DECEMBER
}
}
private static Month getMonthName(int monthValue) {
return Month.of(monthValue);
}
Don't forget to import import java.time.LocalDate;
import java.time.Month;
As already said, don't use java.util.Date but java.time.LocalDate instead, since it is (arguably) easier to work with.

Identify numbers in one String

I have made this method to get birthday, but I wonder if I can identify the numbers for the months and days in one String
for example
930421 is correct
931360 is not correct
public void setFirst(String firstn, int y, int m,int d) {
first = firstn;
if (first.length() == 6){
System.out.println("Your birthday is :" +first);
}else {
System.out.println("error");
}
}
You can use SimpleDateFormat with a pattern such as yyMMdd. Make sure to use setLenient(false) to make the parser "strict" so it will actually raise an Exception on invalid dates.
SimpleDateFormat format = new SimpleDateFormat("yyMMdd");
format.setLenient(false);
Example:
System.out.println(format.parse("930421"));
System.out.println(format.parse("931360"));
Output:
Wed Apr 21 00:00:00 CEST 1993
Exception in thread "main" java.text.ParseException: Unparseable date: "931360"
at java.text.DateFormat.parse(DateFormat.java:366)
at Test.main(Test.java:12)
You can use it like this:
try {
Date date = format.parse(dateString);
System.out.println("Your birthday is " + date);
} catch (ParseException e) {
System.out.println("That's not a date");
}
Here is your answer.
It's working as per your expectation :)
static boolean dob = true;
public static void main(String[] args) {
setFirst("931360", 0, 0, 0);
setFirst("930421", 0, 0, 0);
}
public static void setFirst(String firstn, int y, int m,int d) {
String first = firstn;
if (first.length() == 6){
y=Integer.parseInt(first.substring(0, 2));
if(y<0 || y>99)
{dob=false;}
m=Integer.parseInt(first.substring(2, 4));
if(m<1 || m>12)
{dob=false;}
d=Integer.parseInt(first.substring(4, 6));
if(d<0 || d>31)
{dob=false;}
if(dob)
{System.out.println("Your birthday is :" +first);}
}if(!dob) {
System.out.println("error");
}
}
Assuming your date format is yy-mm-dd, you could just: (simple-minded but easy to implement solution)
1) use String.substring to get the string segments you need (e.g. first 2 digits for yy),
2) parse an integer out of them with Integer.parseInt
3) and check them against a range (e.g. for yy it could be between 20 and 99).
Please note that yy is a representation that is quite prone to error (e.g. 1910 and 2010 are represented in the same way) so you should really consider using yyyy instead.

Stuck in a while loop; calc days between two dates

I've actually been browsing for quite a while on this site, sadly without much progress. Thanks to a lot of extremely useful answers, I've learned quite a bunch of stuff though!
I'm learning Java since ... about 4 days (I guess?) so I'm not very experienced in the methods I can use.
There's this assignment we got at our univ. We shall write a program that returns how many days have passed between two dates. The only restriction is to keep the program as simple as possible, we're not allowed to use "complicated methods".
Sadly, my program is kind of stuck. If I try it out e.g. the dates 23 01 1994 and 07 04 1997, it counts only up to 01 01 1997 and suddenly stops. I have no idea why that happens, I even doubt if I fully understood what I wrote there.
Anyways, here's my code:
import java.util.Arrays;
import java.util.Scanner;
public class Datecalc {
public static int yearcounter,monthcounter,daycounter,days;
public static int[] input() {
Scanner input = new Scanner(System.in);
//Eingabe der Daten
String day1 = input.next();
String month1 = input.next();
String year1 = input.next();
String day2 = input.next();
String month2 = input.next();
String year2 = input.next();
int day1int = Integer.parseInt(day1);
int month1int = Integer.parseInt(month1);
int year1int = Integer.parseInt(year1);
int day2int = Integer.parseInt(day2);
int month2int = Integer.parseInt(month2);
int year2int = Integer.parseInt(year2);
int [] eingabe = new int [6];
eingabe[0] = day1int;
eingabe[1] = month1int;
eingabe[2] = year1int;
eingabe[3] = day2int;
eingabe[4] = month2int;
eingabe[5] = year2int;
return eingabe;
// put everything into an array to be able to use it in the main method
}
public static void main(String[] args) {
int[] eingabe = input();
days=0;
daycounter = eingabe[0];
monthcounter = eingabe[1];
yearcounter = eingabe[2];
Integer[] einunddreissig = {1,3,5,7,8,10,12}; //months with 31 days
Integer[] dreissig = {4,6,9,11}; // months with 30 days
while (daycounter != eingabe[3] && monthcounter != eingabe[4] && yearcounter != eingabe[5] ) {
// if its a month that has 31 days
if ( Arrays.asList(einunddreissig).contains(monthcounter) ) {
for (int i = daycounter; i <= 31; i++) {
days++;
}
daycounter=1;
monthcounter++;
}
// if its a month with 30 days
if ( Arrays.asList(dreissig).contains(monthcounter) ) {
for (int i = daycounter; i <= 30; i++) {
days++;
daycounter++;
}
daycounter=1;
monthcounter++;
// february
} else if ( monthcounter == 2) {
for (int i = daycounter; i <= 28; i++) {
days++;
}
daycounter=1;
monthcounter++;
} else if (monthcounter==13) {
monthcounter=1;
yearcounter++;
}
}
// checking how many days were counted and comparing the input (eingabe[something]) to how far the daycounter reached
System.out.println(" "+days);
System.out.println(" "+daycounter+" "+monthcounter+" "+yearcounter);
System.out.println(eingabe[3]+" "+eingabe[4]+" "+eingabe[5]);
}
}
I hope there is somebody who might be so kind to give me a hint how to fix that.
I would separate this out into two different functions, one that counts the days until the end of the current year and another which counts the days since the beginning of the current year. Then you can put the total days in terms of those values.
First write a generic sum() function:
public static int sum(int[] a, int start, int end){
int sum = 0;
for(int i = start; i < end; i++) sum += a[i];
return sum;
}
Then use the sum() function to easily compute daysToEnd and daysFromStart:
static int[] daysInMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
public static int daysToEnd(int day, int month){
return sum(daysInMonth, month - 1, 12) - day;
}
public static int daysFromStart(int day, int month){
return sum(daysInMonth, 0, month - 1) + day;
}
public static void main(String... args){
int[] date1 = {23, 1, 1994};
int[] date2 = {1, 1, 1997};
// This actually works for same or different years
int days = daysToEnd(date1[0], date1[1]) +
365*(date2[2] - date1[2] - 1) +
daysFromStart(date2[0], date2[1]);
System.out.println(days);
}
Do you have to use loops? Here's some food for thought -- imagine this as a simple algebra problem. In your program, each date is modeled as a collection of quantities, each of a different unit. Once you obtain uniform units, you can just do the arithmetic.
In the UNIX world we use an agreed-upon reference date called the "epoch", 12:00 AM on 01 January, 1970 as a reference date. Kind of like "tare" on a balance. All other dates can be represented as some number of seconds relative to that time.
I would construct the passed in user input to java.util.Date type. But I am assuming line by line input. You can construct a string using StringBuilder if you want to get day,mth,year separately.
try{
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
DateFormat df = new SimpleDateFormat ("dd/MM/yyyy");
System.out.println("Enter Date1");
String dateSt1= br.readLine(); // Accepts date1 as string
System.out.println("Enter Date2");
String dateSt2= br.readLine(); // Accepts date2 as string
Date date1=df.parse(dateSt1); // Date String to Date
Date date2=df.parse(dateSt2);
}catch(IOException ex)
}catch(ParseExceptionOfSomesort pex)
}
then use this to get the difference in days -
int diffInDays = (int)( (date2.getTime() - date1.getTime())
/ (1000 * 60 * 60 * 24) )
If you get this in negative, that means the second date is before first date.
Think: Do I have to do it using a loop or hasn't java already added some utility method to do date compare?
What makes something "complicated" though? Writing too many lines of code or using existing java library?

how to create time array

I have an arraylist arr which contains a series of number, like 07, 52, 25, 10, 19, 55, 15, 18, 41. In this list first item is hour, second is minute and third is second, like 07:52:25.
Now I want to create a time array in which i can insert these values and do some arithmetic operation like difference between first index and second index, which gives me the time difference. So how can i do that?
ArrayList arr = new ArrayList();
StringTokenizer st = new StringTokenizer(line, ":Mode set - Out of Service In Service");
while(st.hasMoreTokens()){
arr.add(st.nextToken());
}
Ok i think i understand what you want your code to do. Heres how i would do it.
public class DateHandler
{
public DateHandler(int seconds, int minutes, int hours)
{
this.seconds = seconds;
this.minutes = minutes;
this.hours = hours;
}
public String toString()
{
return "Seconds: "+seconds+" Minutes: "+minutes+" Hours: "+hours;
}
public int seconds;
public int minutes;
public int hours;
}
public class Main
{
public static void main(String args[])
{
int[] data = {07, 52, 25, 10, 19, 55, 15, 18, 41}
int numberOfDates = data.length/3//Divide by 3 because there are 3 numbers per date
ArrayList<DateHandler> dates = new ArrayList<DateHandler>(numberOfDates);
for(int x=0;x<numberOfDates;x++)
{
int index = x*3;
DateHandler date = new DateHandler(data[index],data[index+1],data[index+2]);
System.out.println("added date: "+date.toString());
dates.add(date);
}
//here you can do your calculations.
}
}
I hope this helped!
I would use split to tokenise. You can read any amount of times from multi-line data
BufferedReader br =
String line;
List<Integer> times = new ArrayList<Integer>();
while((line = br.readLine()) != null) {
String[] timesArr = line.split(", ?");
for(int i=0;i<timesArr.length-2;i+=3)
times.add(Integer.parseInt(times[i]) * 3600 +
Integer.parseInt(times[i+1]) * 60 +
Integer.parseInt(times[i+2]));
}
br.close();
System.out.println(times); // prints three times in seconds.
// difference between times
for(int i=0;i<times.size()-1;i++)
System.out.println("Between "+i+" and "+(i+1)+
" was "+(times.get(i+1)-times.get(i))+" seconds.");
If this array (you said "arraylist arr" right?)
07, 52, 25, 10, 19, 55, 15, 18, 41
means
7:52:25, 10:19:55 and 15:18:41
Then you can use SimpleDateformat to "convert" a string to a date.
SimpleDateFormat can parse ("convert") a String to a Date, and to format a Date to a String (actually a StringBuffer).
In your case, you loop through your ArrayList group the hours, minutes and seconds, and use SimpleDateFormat to parse them:
int index = 0;
String tempTime = "";
ArrayList<Date> dateList = new ArrayList<Date>();
//assuming hour in format 0-23, if 1-24 use k in place of h
SimpleDateFormat dateFormat = new SimpleDateFormat("h-m-s-");
for(String timeeElement : timeArrayList)
{
tempTime += timeeElement;
tempTime += "-"; //To handle situations when there is only one digit.
index++;
if(index % 3 == 0)
{
Date d = dateFormat.parse(tempTime, new ParsePosition(0));
dateList.add(d);
tempTime = "";
}
}
You have a list of dates to play with now

Categories