how to write in the database with the same persist order - java

I have this code I am persisting like that:
for (int i = 0; i < listofplusieurdrapage.size(); i++) {
persist(listofplusieurdrapage.get(i));
}
I have two values in
litsofplusieurdrapage => litsofplusieurdrapage.get(0) = 1
=>litsofplusieurdrapage.get(1) = 2
but when i check the database I found them in this order:
2
1
and when I add just a system.out.println to the code I have the good order
for (int i = 0; i < listofplusieurdrapage.size(); i++) {
System.out.println(" Persist : " + listofplusieurdrapage.get(i));
persist(listofplusieurdrapage.get(i));
}
1
2
do you have an explication of the problem ?
and how I can keep the good order with out adding the system.out.println to my code ?
public void persist(Object object) {
em.persist(object);
}

There is no ordering in tables, see for example this question and other links there.
If you need an order on the listofplusieurdrapage, you must specify the ordering, see for example this question.

Related

Is there a way to pass back 2 different data types from a method in java?

I am trying to populate an empty array in the first column with ordered numbers and write this back. This works, but I need the row location passed back too for reference in another method.
// Generate a customer/order number.
public static String[][] gen_cust_number(String[][] cust_order, int order_location)
{
for(int row = 0; row < cust_order.length; row++)
{
if (cust_order[row][0] == null)
{
cust_order[row][0] = Integer.toString(row + 1000);
order_location = row;
Gen.p("\n\n\tYour order number is : " + cust_order[row][0]);
break;
}
}
return cust_order;
}
I'm not very familiar with working with objects, pairs, and whatnot as I am still learning but have done some searching on it and am stumped in understanding how to do it.
I'm not 100% sure with what you're trying to achieve, but by reading the code I think what get_cust_number should do is
Generate new order to the very first empty order list.
Return the new order list and its index.
If this is right, you don't have to pass the String[][] back because the reference of this instance is what the caller side already know as it's passed in the parameters.
You can also remove the order_location param as it's never read inside the method.
So what you can do to make it work is to
Remove the order_location from params.
Return the index of added order instead of the array itself.
This results in the following code.
// Generate a customer/order number.
public static int gen_cust_number(String[][] cust_order)
{
for(int row = 0; row < cust_order.length; row++)
{
if (cust_order[row][0] == null)
{
cust_order[row][0] = Integer.toString(row + 1000);
Gen.p("\n\n\tYour order number is : " + cust_order[row][0]);
return row;
}
}
// cust_order is full
return -1;
}
In the calling side, you can do the following:
String[][] cust_order = /* Some orders according to your logic. */;
int cust_order_count = /* Number of the orders generated. */;
// Generate the order and this will be the new number of orders.
cust_order_count = gen_cust_number(cust_order);

Printing a set of conditions between a specified number of elements

As part of a program that generates a text output file, I need to insert a predefined number n (which corresponds to the number of required elements) and automatically create conditions among them.
E.g. for n=3, the elements s1, s2 and s3 are generated. What I want to achieve is to generate the following conditions automatically and print them in a text file:
s1<s2 & s1<s3
s2<=s1 & s2<s3
s3<=s1 & s3<=s2
The above conditions cover all possible combinations between the elements. What I have so far is an ArrayList that holds as many elements as the predefined number n and the following code to produce the required results:
int counter = 0;
ArrayList<String> state = new ArrayList<String>();
for (int i=0; i<=n; i++) {
state.add(i,"s"+1));
}
for (int j=1; j<=n; j++) {
for (int i=0; i<(n-1); i++) {
if (i==(n-2)) {
fw.write(state.get(i)+"<"+state.get(counter));
}
else {
fw.write(state.get(i)+"<"+state.get(counter)+" & ");
}
}
counter++;
}
I know that using the counter in this case is not correct, but I cannot think of a way to correctly represent the different conditions.
UPDATE:
Using the following code for testing purposes I managed to get close to the desired outcome:
ArrayList<String> collectStates = new ArrayList<String>();
String activeState,writtenState;
for (int i=0; i<n; i++) {
for (int j=0; j<state.size(); j++) {
if (state.get(i) != state.get(j)) {
activeState=state.get(i)+"<"+state.get(j);
writtenState=state.get(j)+"<"+state.get(i);
if (collectStates.contains(activeState)) {
System.out.print(state.get(i)+"<="+state.get(j));
}
else {
System.out.print(activeState);
}
if (j!=state.size()-1) {
System.out.print(" & ");
}
collectStates.add(writtenState);
}
}
System.out.print("\n");
}
The output I receive is:
s1<s2 & s1<s3
s2<=s1 & s2<s3
s3<=s1 & s3<=s2 &
The only problem is the extra & at the end of the last line, which I don't know yet how to fix.
I found the answer to my question! In the updated section of the description I performed the following addition to remove the extra & symbol:
Old version:
if (j!=state.size()-1) {
System.out.print(" & ");
}
Updated version:
if ((j!=state.size()-1) && ((j!=state.size()-2) || (i!=state.size()-1))) {
fw.write(" & ");
}
The problem appeared always in the last row of the output conditions, thus the newest fix. The output is now exactly as described in the description.
In further detail, what the program did is to remove the identical values:
s1?s1 & s1?s2 & s1?s3
s2?s1 & s2?s2 & s2?s3
s3?s1 & s3?s2 & s3?s3
So by removing:
s1?s1 & we keep s1?s2 & s1?s3
s2?s2 & we keep s2?s1 & s2?s3
s3?s3 we keep s3?s1 & s3?s2 &
As a result, the addition of the new condition is necessary to remove the extra & in the last row.

Appium: How to iterate over a listview of unknown length?

I have a list view with a hierarchy I theoretically have no knowledge of. I am attempting to accept a String array and create MobileElements for each string in it, but due to the way I've automated (PageFactory) defining my elements via annotations, they cannot use variables. I also don't know that it's valid or proper to define my annotations inside a method.
The code I've written, which obviously does not compile follows:
public void selectLocation(String[] location) {
List<MobileElement> locationsList = new ArrayList<>();
for(int i = 0; i < location.length; i++) {
#iOSFindBy(accessibility = location[i])
#AndroidFindBy(xpath = "//android.widget.TextView[#text='" + location[i] + "']")
locationsList.add(i);
}
for (int i = 0; i < location.length; i++) {
locationsList.get(i).click();
}
}
I'm assuming the proper way to do this is wholly different from the way I've implemented.
My list hierarchy is similar to the following; my end point could vary depending on the branch I go down:
Continent 1
City 1
Room 1
Room 2
City 2
Building 1
Room 1
Room 2
Building 2
Room 1
Room 2
I now look for a matching element. If I don't find it, I swipe further into the list. If the element doesn't exist I obviously run into problems, but not really an issue in my case since that’d be a failing test.
while (!driver.findElementById(currentLocation).isDisplayed()) {
driver.swipe(startX, startY, startX, endY, 100);
}
driver.findElementById(currentLocation).click();
Yes, I also realize .swipe() is deprecated, but it still works for me and I'd rather not rewrite all my code with TouchActions until necessary.
I ended up using the "FindsBys" functions to create an array of all matching elements. I then loop through those elements looking for a match to one of my strings.
#AndroidFindBys({#AndroidFindBy(xpath = "//android.widget.TextView")})
#iOSFindBys({#iOSFindBy(xpath = "//XCUIElementTypeStaticText")})
private List<MobileElement> locationsList;
...
public void selectLocation(String[] location)
{
for(int i = 0; i < locationsList.size(); i++)
for(int p = 0; p < location.length; p++) {
if (locationsList.get(i).getText().equals(location[p])) {
locationsList.get(i).click();
}
}
}
It's not foolproof (if you have duplicate strings at different levels of your hierarchy you may run into issues), but it works for my use-case and should be able to guide anyone looking for a stronger solution.
You can just loop over the elements themselves.
....
for(MobileElement location: locationsList) {
for(int p = 0; p < location.length; p++) {
if (location.getText().equals(location[p])) {
location.click();
}
}
}

Java Selecting certain values from a set

I am reading from a CSV file that contains data about Hills. I can read the data from the file, and have associated column headers with 6 fields. Currently my output prints like:
### County:Argyll and Bute
[48,Deinn a'Choin,Argyll and Bute,768.2,56.281081,-4.659943, 49,Feinn a'Choin,Argyll and Bute,768.5,56.281043,-4.659924, 50,Zeinn a'Choin,Argyll and Bute,768.7,56.281034,-4.659981]
### County:Stirling
[19,Beinn Each,Stirling,813.0,56.313957,-4.262199, 11,Creag Gharbh,Stirling,637.4,56.46677,-4.221506, 7,Meall Buidhe,Stirling,719.0,56.419004,-4.308645]
### County:Aberdeen
[19,Beinn Each,Aberdeen,813.0,56.313957,-4.262199, 11,Creag Gharbh,Aberdeen,637.4,56.46677,-4.221506, 7,Meall Buidhe,Aberdeen,719.0,56.419004,-4.308645]
But I am trying to get my output like:
### County:Argyll and Bute
NameOfHill#1 Height
NameOfHill#2 Height
NameOfHill#3 Height
### County:Stirling
NameOfHill#1 Height
NameOfHill#2 Height
NameOfHill#3 Height
### County:Aberdeen
NameOfHill#1 Height
NameOfHill#2 Height
NameOfHill#3 Height
So technically what I am trying to achieve is, select 3 values from my SET which are actually inside a map and only print out the name and height.
My code currently is:
for (int i = 0; i < 3; i++) {
System.out.println("### County:" + hillsByCounty.keySet().toArray()[i]);
System.out.println(hillsByCounty.get((hillsByCounty.keySet().toArray())[i]));
}
}
I believe i have to use another for loop, and somehow select only 3 values from the Set and use ".getName" and ".getHeight" in my final print statement
I had an idea of something along the lines
Set<Hill> getHills = hillsByCounty.get((hillsByCounty.keySet().toArray())[i]);
for (int j = 0 ; j < 3 ; j++){
//write to somehow code to pull the hill in pos j in this set
System.out.println(h.getName() + " " + h.getHeight());
}
}
}
But what im not sure about is, how to get these set values. My Map value is a set because my previous method initiates like:
public static Map<String, Set<Hill>> hillsByCounty(List<Hill> hills) {
Sets don't have a get method. You could wrap it in a list e.g.
List<Hill> hills = new ArrayList<>(hillsByCounty.get((hillsByCounty.keySet().toArray())[i]));
or use a for-each loop instead. If you need to only print the first 3 you can add a counter to handle that.
int i = 0;
for (Hill h : hills) {
//Can print here with h however you like
if (++i == 3) {
break;
}
}
Looks like you need to learn about the enhanced for loop, also known as the for-each loop.
Your code should be:
int countyCount = 0;
for (Map.Entry<String, Set<Hill>> entry : hillsByCounty(readHills()).entrySet()) {
System.out.println("### County:" + entry.getKey());
int hillCount = 0;
for (Hill hill : entry.getValue()) {
System.out.println(hill.getName() + " " + hill.getHeight());
if (++hillCount == 3)
break;
}
if (++countyCount == 5)
break;
}
In Java 8, you could also use streaming:
hillsByCounty(readHills()).entrySet()
.stream()
.limit(5)
.forEach(entry -> {
System.out.println("### County:" + entry.getKey());
entry.getValue()
.stream()
.limit(3)
.map(h -> h.getName() + " " + h.getHeight())
.forEach(System.out::println);
});
See:
Javadoc - Map.entrySet()
The Java™ Tutorials - The for Statement
StackOverflow - What is the syntax of enhanced for loop in Java?
StackOverflow - Why is enhanced for loop efficient than normal for loop?

Debugging Array and for-loop + if statement

I have built a method which compares objects attributes with user input int. The method then adds all the objects to an array(the assignment demands it to be an Array and not ArrayList). After its added I have a foor-loop which prints out a list of Results for an athlete(in user input), it prints out all results from one category and then another and so forth..
I keep getting a NullPointerException error on the last line which is a System.out.println. I have searched for an answer for hours, and read the NullPointerException posts here but cannot find the issue or solve it.
for (int x = 0; x < category.size(); x++) {
Category c = categories.get(x);
System.out.println("Result in " + c.categoryName() + " for " + matchedAthlete.surName() + " "
+ matchedAthlete.lastName() + ": ");
for (int i = 0; i < individarrayresult.length; i++) {
Result res = individarrayresult[i];
if (res.nameOfCategory().equals(c.categoryName())) {
System.out.println(res.categoryResult());
}
}
}
So the last line of code ( System.out.println ) gets the NullPointerException, I am desperete for help. Below is the Array filled with results from only 1 Athlete.
Result[] individarrayresult = new Result[resultlist.size()];
for (int i = 0; i < resultlist.size(); i++) {
Result res = resultlist.get(i);
if (res.athleteStartNumber() == DSN) {
individarrayresult[i] = res;
}
}
If you have a NullPointerException on that row:
System.out.println(res.categoryResult());
The problem is in the method categoryResult because res is not null, otherwyse the previous test
if (res.nameOfCategory().equals(c.categoryName())) {
must throw the NullPointerException prior of the System.out.
So check the code of categoryResult() or post it.
Perhaps, as T.J. said, that the problem is not on that row but on the previous row and the NullPointerException is related to the value of res. Post the complete StackTrace and row lines of your code to be sure of that answer.
I think you're mistaken, I think you're getting the NPE one line earlier, on this line:
if (res.nameOfCategory().equals(c.categoryName())) {
And the reason you're getting it is there are nulls in your array, because of how you fill it:
Result[] individarrayresult = new Result[resultlist.size()];
for (int i = 0; i < resultlist.size(); i++) {
Result res = resultlist.get(i);
if (res.athleteStartNumber() == DSN) {
individarrayresult[i] = res;
}
}
If res.athleteStartNumber() == DSN is false, you never assign anything to individarrayresult[i], so that array entry keeps its null default.
How to fix it:
Build up a list of matching results:
List<> individResults = new Arraylist<Result>(resultlist.size());
for (int i = 0; i < resultlist.size(); i++) {
Result res = resultlist.get(i);
if (res.athleteStartNumber() == DSN) {
individResults.add(res);
}
}
...and then either use that list directly, or convert it to an array:
Result[] individarrayresult = individResults.toArray(new Result[individResults.size()]);
...and use the resulting array.
(You can also do the same with the nifty new streams stuff in the latest version of Java, but I'm not au fait with them...)
It's possible, of course, that you're getting the NPE on the line you said you are and that there are two problems, and it just happens you've been processing all DSN entries so far. If so, and you fix the other problem, the first time you have a non-DSN entry, you'll run into this problem unless it fix it as well.

Categories

Resources