There are two methods of same class .I want to compare two variables value by using assertion .
here are the two methods
//Method 1
public void Edit_window() throws InterruptedException {
collection_title.clear();
// driver.wait(2000);
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date date = new Date();
collection_title.sendKeys(dateFormat.format(date));
}
//Method 2
public void name_collection()
{
String updated_title=col_title.getText() ;
System.out.println("the title eof the collectio is " + updated_title) ;
System.out.println("the value is" + date) ;
}
So if you can see there is one variable "date " and it contains the current date. I want to that variable value and compare with the variable value "updated_title" which is defined in the method 2 . Any input please !
You can basically change the return type of the methods to String type and then add assertion. Sample below:
public String Edit_window() throws InterruptedException {
collection_title.clear();
// driver.wait(2000);
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date date = new Date();
collection_title.sendKeys(dateFormat.format(date));
return dateFormat.format(date);
}
public String name_collection()
{
String updated_title=col_title.getText() ;
System.out.println("the title eof the collectio is " + updated_title) ;
System.out.println("the value is" + date) ;
return date;
}
//And then for assertion you can basically: Assert.asserEquals(classObject.Edit_window(), classObject.name_collection);
Hope the solution provided by the Mrunal is works for you. I will suggest you to create a public class and store the Reusable values such as id, email, autogenerated numbers etc. So that you should be able to access anywhere from your framework.
we can't say that always we will only do the comparison in the same class. So please try to create the class as below and use it to store the values.
public class Repovalues {
private string id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
Related
Assume that I have a data input like this:
018492114,51863406,X0,1,20160218
018529816,51864472,X0,1,20150603
018543434,51864629,X0,1,20150702
018543464,51864990,N5+,1,2015063
018530309,51865142,X0,1,20150603
I want only to convert the 5 column's element to Date format because it was imported as a string. And I want to do a sorting operation by DA_PRM_CTR_ORDER variable (the end column).
Note that I am using arraylist object defined as Personne and I am using Comparable interface to use Comparable method for sorting:
this is my class personne which includes the needed object:
public class Personne implements Comparable {
private String IDC_PSE_PCL;
private String IDC_CD_NOT;
private String CD_NOTE;
private String IDT_ETT_PSE;
private String DA_PRM_CTR_ORDER;
public Personne(String IDC_PSE_PCL, String IDC_CD_NOT,
String DA_PRM_CTR_ORDER, String IDT_ETT_PSE, String CD_NOTE) {
this.IDC_PSE_PCL = IDC_PSE_PCL;
this.IDC_CD_NOT = IDC_CD_NOT;
this.IDT_ETT_PSE = IDT_ETT_PSE;
this.CD_NOTE = CD_NOTE;
this.DA_PRM_CTR_ORDER = DA_PRM_CTR_ORDER;
}
public String getIDC_CD_NOT() {
return this.IDC_CD_NOT;
}
public String getIDC_PSE_PCL() {
return this.IDC_PSE_PCL;
}
public String getDA_PRM_CTR_ORDER() {
return this.DA_PRM_CTR_ORDER;
}
public String getIDT_ETT_PSE() {
return this.IDT_ETT_PSE;
}
public String getCD_NOTE() {
return this.CD_NOTE;
}
#Override
public int compareTo(Object o) {
Personne other = (Personne) o;
DateFormat df = new SimpleDateFormat("yyyyMMdd");
Date converted = (Date) df.parse(other.getDA_PRM_CTR_ORDER());
int res = this.DA_PRM_CTR_ORDER.compareTo(converted);
// Si Egalite des dates
if (res == 0) {
res = IDT_ETT_PSE.compareTo(other.getIDT_ETT_PSE());
}
return res;
}
My problem is in the line:
int res = this.DA_PRM_CTR_ORDER.compareTo(converted);
when I want to sort by DA_PRM_CTR_ORDER values but it show me this problem:
The method compareTo(String) in the type String is not applicable for
the arguments (Date)
How can I resolve this issue please?
A quick fix could be to parse this.DA_PRM_CTR_ORDER to Date too. So the line you highlighted would look like:
int res = df.parse(this.DA_PRM_CTR_ORDER).compareTo(converted);
you should use Date.compareTo(Date) instead of String.compareTo(Date).
suggestion:
Long currentDate = Long.parseLong(this.DA_PRM_CTR_ORDER);
return currentDate.compareTo(Long.parseLong(other.getDA_PRM_CTR_ORDER()));
It would be better if you compare the timestamp of two dates to compare.
Date self = (Date) df.parse(this.getDA_PRM_CTR_ORDER());
String ConvertedTs = String.valueOf(converted.getTime());
String selfTs = String.valueOf(self.getTime());
int res = selfTs.compareTo(ConvertedTs);
I'm just learning about get and set methods at uni. I feel like I am literally following the lecturer's notes word by word but I am getting errors:
getZone(Station) in railwayStation cannot be applied to
java.lang.String
on the line with the code
int zone = getZone(station);
getWheelchair(Station) in railwayStation cannot be applied to
java.lang.String
on the line with the code:
boolean wheelchair = getWheelchair(station);
What I was trying to do was create "train station" records and store information using set methods. I then later wanted to retrieve this information using get methods but I am getting the above errors. What did I do wrong?
//importing input functionality
import java.util.Scanner;
//creating a new record type station that holds records of stations
class Station {
String stationName;
int zone;
boolean wheelchair;
}
public class railwayStation {
public static void main(String []p) {
//creating stations using set methods
createStation("Bristol", 1,false);
createStation("Reading", 2, true);
createStation("York", 3,true);
System.out.print("What station do you need to know about? ");
//create scanner for input
Scanner scanner = new Scanner(System.in);
String inputStation = scanner.nextLine();
getInfo(inputStation);
}
//creating set method
public static Station createStation(String stationName, int zone, boolean wheelchair) {
Station myStation = new Station();
myStation.stationName = stationName;
myStation.zone = zone;
myStation.wheelchair = wheelchair;
return myStation;
}
//creating get methods
//getting station name
public static String getName(Station myStation) {
return myStation.stationName;
}
//getting station zone
public static int getZone(Station myStation) {
return myStation.zone;
}
//getting station wheelchair status
public static boolean getWheelchair(Station myStation) {
return myStation.wheelchair;
}
public static void getInfo(String station) {
if(station.equals("Bristol")) {
//get info using get methods
int zone = getZone(station);
boolean wheelchair = getWheelchair(station);
if(wheelchair == false) {
System.out.println(station + "is operated in zone " + zone + " and has no step free access");
} else {
System.out.println(station + "is operated in zone " + zone + " and has step free access");
}
}
}
}
I have a List of String arrays of the form
List<String[]> currentLoadAddressLocations = new ArrayList<>();
That gets set and parsed through a JSONObject Array
try {
JSONObject dataObject = new JSONObject(data);
JSONArray dataObjArray = dataObject.getJSONArray("stops");
Log.i(TAG, dataObjArray.toString());
for (int i = 0; i < dataObjArray.length(); i++) {
JSONObject addressAndLocation = dataObjArray.getJSONObject(i);
addressGPointJSON.add(addressAndLocation.getString("address"));
locationGPointJSON.add(addressAndLocation.getString("location"));
cityGPointJSON.add(addressAndLocation.getString("city"));
stateGPointJSON.add(addressAndLocation.getString("state"));
fromGPointJSON.add(addressAndLocation.getString("from"));
latGPointJSON.add(reverseGeocoderLatLong(addressGPointJSON.get(i) + ", " + cityGPointJSON.get(i) + ", " + stateGPointJSON.get(0), true));
longGPointJSON.add(reverseGeocoderLatLong(addressGPointJSON.get(i) + ", " + cityGPointJSON.get(i) + ", " + stateGPointJSON.get(0), false));
currentLoadAddressLocations.add(i,
new String[]{
fromGPointJSON.get(i),
addressGPointJSON.get(i),
locationGPointJSON.get(i),
cityGPointJSON.get(i),
stateGPointJSON.get(i),
latGPointJSON.get(i),
longGPointJSON.get(i)
});
} // end of for loop
} // end of try catch block
catch(JSONException e){
e.printStackTrace();
}
Currently, the code gives me back the data structure that I need, a String[] of the form
["2017-03-30 21:00:00", "Address example 123", "Location Example", "CITY", "STATE", "lat", "long"]
repeated depending on how many stops where in the JSON object that was returned. I need to find a way to sort the first value of the array from top to bottom inside the currentLoadAddressLocations array by time, so if one of the dates is "2017-03-30 15:00:00" and the other is "2017-03-30 14:00:00" then the one that is before takes precedence and moves the date to the top of the currenLoadAddressLocations array while at the same time araging the second one to be below. I am having a hard time trying to find a method of doing so. Currently I know that I can compare dates if I parse the dates as:
Date from = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).parse("2017-03-30 21:00:00");
But do not know how to work around this issue while looping through the currentLoadAddressLocations List. Further more, I do not know how to access the values in order to compare them. I can loop through the selection by using
for(String[] array: currentLoadAddressLocations){
for(String s: array){
Log.i(TAG,"ITEM: " + s);
}
}
But since they are inside a String array they cannot be changed into a date format unless I change them and then parse them back to strings.
Any suggestions will be greatly appreciated.
The answer is you should convert your String[] into a AddressDateLocation class array. Once you do that, it will be much easier to sort you data the way you want
public class AddressDateLocation implements Comparable<AddressDateLocation> {
Date date;
String address;
String location;
public void setDate(Date d) {}
public Date getDate() ...
public void setLocation(String loc) ...
public String getLocation() ...
public void setAddress(String addr) ...
public String getDate() ...
public int compareTo(AddressDateLocation other) ...
}
The data structure you need is likely not an array of String's, unless the order of the pieces ends up in a public API. You'd better keep the information in the native JSONObject, that has Map semantics. Then you can simply order by timestamp with:
List<JSONObject> currentLoadAddressLocations = TODO(/* implement this */);
currentLoadAddressLocations.sort((o1, o2) -> {
return o1.getString("date").compareTo(o2.getString("date"))
});
Note: the date format suggested in the question makes it possible to compare timestamps using their textual representation.
You could make the dates into LocalDateTime objects and use the compareTo method.
I would use the List#sort function like so:
currentLoadAddressLocations.sort((sa1, sa2) -> { // sa = String Array
try {
String pattern = "yyyy-MM-dd HH:mm:ss";
return new SimpleDateFormat(pattern, Locale.US).parse(sa1[0])
.compareTo(new SimpleDateFormat(pattern, Locale.US).parse(sa2[0]));
} catch (ParseException e) {
// If your dates are all valid you shouldn't come here.
e.printStackTrace();
return -1; // move all parse ParseExceptions to the first positions
}
});
I need a timezone display values as follows :
(UTC + 05:30) Chennai, Kolkata, Mumbai, New Delhi
But by using following method I am getting bit different output. How should I get the timezone display name as above ? (if required, I can use JODA).
public class TimeZoneUtil {
private static final String TIMEZONE_ID_PREFIXES =
"^(Africa|America|Asia|Atlantic|Australia|Europe|Indian|Pacific)/.*";
private static List<TimeZone> timeZones;
public static List<TimeZone> getTimeZones() {
if (timeZones == null) {
timeZones = new ArrayList<TimeZone>();
final String[] timeZoneIds = TimeZone.getAvailableIDs();
for (final String id : timeZoneIds) {
if (id.matches(TIMEZONE_ID_PREFIXES)) {
timeZones.add(TimeZone.getTimeZone(id));
}
}
Collections.sort(timeZones, new Comparator<TimeZone>() {
public int compare(final TimeZone t1, final TimeZone t2) {
return t1.getID().compareTo(t2.getID());
}
});
}
return timeZones;
}
public static String getName(TimeZone timeZone) {
return timeZone.getID().replaceAll("_", " ") + " - " + timeZone.getDisplayName();
}
public static void main(String[] args) {
timeZones = getTimeZones();
for (TimeZone timeZone : timeZones) {
System.out.println(getName(timeZone));
}
}
}
This code may do the trick for you:
public static void main(String[] args) {
for (String timeZoneId: TimeZone.getAvailableIDs()) {
TimeZone timeZone = TimeZone.getTimeZone(timeZoneId);
// Filter out timezone IDs such as "GMT+3"; more thorough filtering is required though
if (!timeZoneId.matches(".*/.*")) {
continue;
}
String region = timeZoneId.replaceAll(".*/", "").replaceAll("_", " ");
int hours = Math.abs(timeZone.getRawOffset()) / 3600000;
int minutes = Math.abs(timeZone.getRawOffset() / 60000) % 60;
String sign = timeZone.getRawOffset() >= 0 ? "+" : "-";
String timeZonePretty = String.format("(UTC %s %02d:%02d) %s", sign, hours, minutes, region);
System.out.println(timeZonePretty);
}
}
The output looks like this:
(UTC + 09:00) Tokyo
There are, however, a few caveats:
I only filter out timezones whose ID matches the format "continent/region" (e.g. "America/New_York"). You would have to do a more thorough filtering process to get rid of outputs such as (UTC - 08:00) GMT+8 though.
You should read the documentation for TimeZone.getRawOffSet() and understand what it's doing. For example, it doesn't DST effects into consideration.
On the whole, you should know that this is a messy approach, primarily because the timezone ID can be of so many different formats. Maybe you could restrict yourself down to the timezones that matter for your application, and just have a key value mapping of timezone IDs to display names?
I am writing a credit card program. I want the program to use the current date every time the method is used to make a purchase and put the date into the array
private GregorianCalendar transDate;
public CreditCard(double amount,String storeName, GregorianCalendar transDate) {
this.amount=amount;
this.storeName=storeName;
transDate=new GregorianCalendar();
}
public void purchase(double amount, String storeName, GregorianCalendar date)throws Exception
{
if (numPurchases<purchases.length)
if (amount >0 )
if(amount+balance<=creditLimit)
if( GregorianCalendar.getInstance().getTimeInMillis()<=expDate.getTimeInMillis())
{
balance+=amount;
transDate=getTransDate();
purchases[numPurchases] = new CreditCard(amount, storeName,transDate);
numPurchases++;
}
else
{
throw new Exception("card expired");
}
else{
throw new Exception("insufficient credit");
}
else{
throw new Exception("invalid amount");
}
else{
throw new Exception("exceeded number of allowed purchases");
}
}
I would like to display the information in String info
info+="Purchases:\n";
for(int index=0;index<numPurchases;index++){
info+="["+(index+1)+"] ";
info+=transDate.get(Calendar.YEAR)+"\t";
info+= purchases[index].getStoreName()+"\t";
info+=(formatter.format(purchases[index].getPurchase()))+"\n" ;
}
how do I need to set up the code to use the current date and add it to the array and display it in the string
Why don't you use a List implementation instead of an array? You can override the toString method to print it the way you want.
final SimpleDateFormat formatter = new SimpleDateFormat("dd MM yyyy");
List<Calendar> dates = new ArrayList<Calendar>() {
private static final long serialVersionUID = -5079502477457556887L;
#Override
public String toString() {
Iterator<Calendar> i = iterator();
if (!i.hasNext())
return "[]";
StringBuilder sb = new StringBuilder();
sb.append('[');
for (;;) {
Calendar c = i.next();
sb.append(formatter.format(c.getTime()));
if (! i.hasNext())
return sb.append(']').toString();
sb.append(", ");
}
}
};
dates.add(Calendar.getInstance());
dates.add(Calendar.getInstance());
System.out.println(dates);
What does your getTransDate() function do? Ideally it should return the transDate variable of CreditCard object. To calculate transDate for a purchase, you are better off renaming the method to calculateTransDate() or something like that.
Once you have getTransDate() method returning the transDate, your info string can be :
info+="Purchases:\n";
for(int index=0;index<numPurchases;index++){
info+="["+(index+1)+"] ";
info+=purchases[index].getTransDate().get(Calendar.YEAR)+"\t";
info+= purchases[index].getStoreName()+"\t";
info+=(formatter.format(purchases[index].getPurchase()))+"\n"
}