How to add a append a value to existing list - java

List<Person> people = new ArrayList<Person>();
for (Person p : list) {
Array person = new array[];
personList.add(person);
person.setName(list.getname);
person.setLastname(list.getLastname);
person.setAddress(list.address);
people.add(person);
In this code my address is having 5 rows and if I have to add bring all these rows in to one
Example, convert this
Name LastName Address
John Smith 123
LakeViewDrive
Wheeling
chicago
illinois
Scott Raible 456
Discovergateway
lakecook road
chicago
illinois
to
John Smith 123 LakeviewDrive Wheeling chicago Illinois
scott Raible 456 Discovergateway lakecook road chicago Illinois
Please let me know how to append address rows to single value with out changing.

Related

Display the total amount of each products below the table

I'm using itextpdf to display the sql query
SELECT prod_id, prod_name, amt, sum(amt) over(partition by prod_name) as total_amt
FROM items
ORDER BY prod_name;
I was able separate the table according to PROD_NAME, and calculate the total amount of each products by getting the sum(amt) over(partition by prod_name) as total_amt from the sql query. Now, I've been trying to display the total amount of each products below like this:
APPLE
PROD_ID | AMT
11111 12.75
22222 13.75
33333 14.75
Total: 41.25
ORANGE
PROD_ID | AMT
44444 15.75
55555 16.75
Total: 32.5
However, this is the output of my code. The Total amount is displayed after each row.
APPLE
PROD_ID | AMT
11111 12.75
Total: 41.25
22222 13.75
Total: 41.25
33333 14.75
Total: 41.25
ORANGE
PROD_ID | AMT
44444 15.75
Total: 32.5
55555 16.75
Total: 32.5
Here is the snippet of my code:
List<String> prod_Names = new ArrayList<>();
while(rs.next()){
String prodName = rs.getString(2);
if (!prod_Names.contains(prodName)){
prod_Names.add(prodName);
// Displays the Product Name on top of the table
PdfPCell name = new PdfPCell(new Phrase(prodname, bold));
name.setColspan(2);
prod_Table.addCell(name);
// Displays the Row Header
prod_Table.addCell(new Phrase("PROD_ID", header_Bold));
prod_Table.addCell(new Phrase("AMT", header_Bold));
}
String prodId_Values = result.getInt(1);
int amt_Values = result.getInt(3); // amount
int totalAmt = result.getInt(4); // total amount of each products
//Displays the Values
prod_Table.addCell(new Phrase(Integer.toString(prodId_Values), normalFont));
prod_Table.addCell(new Phrase(Integer.toString(amt_Values), normalFont));
// Display Total
prod_Table.addCell(new Phrase("TOTAL:", normalFont));
prod_Table.addCell(new Phrase(Integer.toString(totalAmt), normalFont));
}
I tried putting the Display Total lines inside an if condition just like how I did with the Product Name. I also added another ArrayList called prod_Names2.
if(!prod_Names2.contains(prodName)){
prod_Names2.add(prodName);
// Display Total
prod_Table.addCell(new Phrase("TOTAL:", normalFont));
prod_Table.addCell(new Phrase(Integer.toString(totalAmt), normalFont));
}
The total amount is now only displayed one time, but it's displayed after one row of each products like this. This is the best that I could do:
APPLE
PROD_ID | AMT
11111 12.75
Total: 41.25
22222 13.75
33333 14.75
ORANGE
PROD_ID | AMT
44444 15.75
Total: 32.5
55555 16.75
In Standard SQL you can do what you want using grouping sets:
SELECT prod_id, prod_name, SUM(amt) as amt
FROM items
GROUP BY GROUPING SETS ( (prod_id, prod_name), () )
ORDER BY prod_name NULLS LAST;
Not all databases support exactly this syntax, but most support some variation of it. Then your java code can just read the results from the query.

Is it possible to reverse the order in a listview?

When I get my data from the firebase realtime database it is automatically listed in ascending order, but I'm trying to get the values that I put into an arraylist to be listed in reverse order rather that ascending.
Is it possible to get a reverse order on values when working with a listview ?
Code in use at the moment is:
Query query = userRef.orderByChild("totalNumberOfSteps");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String username = ds.child("username").getValue(String.class);
long totalNumberOfSteps = ds.child("totalNumberOfSteps").getValue(Long.class);
Log.d(TAG , username + " - Steps: " + totalNumberOfSteps);
arrayList.add(new String(username + " - " + "steps: " + totalNumberOfSteps));
arrayAdapter = new ArrayAdapter<>(Leaderboard.this , android.R.layout.simple_list_item_1 , arrayList);
listView.setAdapter(arrayAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG , databaseError.getMessage()); //Don't ignore errors!
}
};
query.addListenerForSingleValueEvent(valueEventListener);}}
The current output of this code is:
John Doe VI - Steps: 0
John Doe III - Steps: 0
John Doe V - Steps: 12
John Doe I - Steps: 79
John Doe IV - Steps: 88
John Doe II - Steps: 111
Preferred output:
John Doe II - Steps: 111
John Doe IV - Steps: 88
John Doe I - Steps: 79
John Doe V - Steps: 12
John Doe III - Steps: 0
John Doe VI - Steps: 0
When adding Collections.reverse(arrayList); to the code, the output is:
John Doe II - Steps: 111
John Doe IV - Steps: 88
John Doe III - Steps: 0
John Doe VI - Steps: 0
John Doe V - Steps: 12
John Doe I - Steps: 79
You can reverse the ArrayList before providing it to the ArrayAdapter by doing so:
Collections.reverse(arrayList);
In your case copy arrayList before reversing it and passing it to the ArrayAdapter's constructor:
ArrayList<> tmpArr = new ArrayList<>(arrayList);
Collections.reverse(tmpArr);
arrayAdapter = new ArrayAdapter<>(Leaderboard.this , android.R.layout.simple_list_item_1 , tmpArr );
Otherwise the arrayList object will get reversed every time onDataChange() gets called and its order will get mixed up.

How to sort blocks of text lines in file?

I have a text file consisting of ID, persons name and surname, bank balance and date of account creation. I somehow need to sort this text file by surname and balance, but I don't know how.
ID:41
Name and surname: Andris Lietis
Balance: 30000 Eur
Created: 31.03.2019
ID:33
Name and surname: Rainis Maize
Balance: 2000 Eur
Created: 32.03.2019
ID:34
Name and surname: Akmens Liepins
Balance: 123 Eur
Created: 29.03.2019
ID:35
Name and surname: Karlis Maiznieks
Balance: 32000 Eur
Created: 04.04.2019
So I was first thinking about somehow reading that file and when I approach one of ID line, I read next three lines and somehow storing those 4 lines in some sort of a block/variable, then doing the same with other blocks. My friend mentioned making objects and comparing, but I don't have any experience with that and as I look up in the google, this really confuses me.
public static void Sakartosana(String nosaukums) throws IOException {
br = new BufferedReader(new FileReader(nosaukums));
String s;
//I understand that I need to somehow sort this with selection.sort
ArrayList<String> al = new ArrayList<String>();
while ((s = br.readLine()) != null) {
if (s.startsWith("ID:")) {
}
}
br.close();
}
This is how I read the line by line, I have many methods with different tasks reading file like this.
The expected result would be like this :
ID:41
Name and surname: Andris Lietis
Balance: 30000 Eur
Created: 31.03.2019
ID:34
Name and surname: Akmens Liepins
Balance: 123 Eur
Created: 29.03.2019
ID:35
Name and surname: Karlis Maiznieks
Balance: 32000 Eur
Created: 04.04.2019
ID:33
Name and surname: Rainis Maize
Balance: 2000 Eur
Created: 32.03.2019

Java encountering runtime errors while trying to read text file

I'm currently trying to write a Java assignment that is supposed to, in order;
Read each line of a prewritten text file
Turn each line into a string
Turn each part of each line into its own individual string/int/double
Assign those variables in an object (Which is part of an array of objects) of a class which I have also created as part of this assignment
Print each variable of the object using one of the class' methods
However, I am repeatedly running into a runtime problem where I am getting this error message;
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at Lab2.main(Lab2.java:27)
This leads me to believe I am probably reading the text file wrong. However, no matter what I do I can't seem to get it to read correctly. It's supposed to read a first name, a last name, three separate components of an address (which it concatenates into one string), a city, a state, a zip code (as an integer), a phone number (as a string) and a dollar amount (as a double).
I believe that the problem might arise from the city names, as some of them have a space between them. I thought I had solved this by setting the delimiter of the Scanner that reads each individual string to a tab (which is what every other element is separated by) but this has either not worked (And is thus trying to turn state names into an integer via the Integer.parseInt() static method) or is not the problem. As I said, I am out of ideas and would be greatly appreciative towards anyone who could help me out here!
I will list the code below. First here is the main file;
public class Lab2
{
public static void main(String[] args) throws IOException
{ String FirstName, LastName, Address1, Address2, Address3, AddressFull, City, State, Phone, ZipString, DonString, line = "blank";
int Zip;
double Donation;
Scanner fileScan = new Scanner(new File("Lab2.txt")), lineScan = new Scanner(line);
lineScan.useDelimiter("\t");
PersonStats[] Donators = new PersonStats[25];
for (int i = 0; i < Donators.length; i++)
{ line = fileScan.nextLine();
FirstName = lineScan.next();
LastName = lineScan.next();
Address1 = lineScan.next();
Address2 = lineScan.next();
Address3 = lineScan.next();
AddressFull = Address1 + " " + Address2 + " " + Address3;
City = lineScan.next();
State = lineScan.next();
ZipString = lineScan.next();
Zip = Integer.parseInt(ZipString);
Phone = lineScan.next();
DonString = lineScan.next();
Donation = Double.parseDouble(DonString);
Donators[i] = new PersonStats(FirstName, LastName, AddressFull, City, State, Zip, Phone, Donation);
Donators[i].PrintOut();
}
}
}
Next, the class file I've written up for the assignment;
public class PersonStats
{ private String FirstName, LastName, Address, City, State, Phone;
private int Zip;
private double Donation;
public PersonStats(String first, String last, String area, String town, String feifdom, int postcode, String telegraph, double given)
{ FirstName = first;
LastName = last;
Address = area;
City = town;
State = feifdom;
Zip = postcode;
Phone = telegraph;
Donation = given;
}
public void PrintOut()
{ System.out.println(FirstName + " " + LastName);
System.out.println(Address);
System.out.println(City + ", " + State + " " + Zip + "\n");
System.out.println(Phone + " " + Donation);
}
}
And then finally the text file the program is supposed to be reading from (Might be a little bit difficult to read, just remember each space except for the ones in city names is actually a tab);
Rick James 8276 Carlos Ave Las Vegas NV 87126 5553451567 23.95
John Gibson 9127 Oak Dr Corvallis OR 97330 5552812313 156.78
Ron Wills 1155 Ivy Pl Atlantic Ga 37339 5552123145 189.56
Rita Jones 1259 Chase Ave Las Vegas NV 87126 5554445671 2145.60
Jason Knight 7154 Pine Dr Gresjam OR 97380 5558124545 3157.44
Clara Swanson 1944 Main Pl Springfield OR 97339 5552123144 212.99
Robert Peck 1866 First Ave Las Vegas NV 87126 5553455425 250.00
Dora Garcia 2179 Fir Dr Corvallis OR 97330 5552812919 350.00
Peter Keck 1465 Circle Pl Gold Beach OR 97339 5552123256 2150.00
Stuart Smith 2387 Sweek Ave Las Vegas NV 87126 5553455489 650.99
Tyler Wild 1313 Spooky Ln Corvallis OR 97330 5552813213 587.45
Laretta Peters 2224 Chase Pl Monmouth OR 97361 5552124465 123.45
Kristi Emry 3465 Cerrito Ave Las Vegas NV 87126 5553455567 3212.65
Kelli Gard 1894 Elm Dr Corvallis OR 97330 5552816678 51.00
Jacob Andrews 8159 Rose Ct Mill City OR 97322 5552127879 64.00
Ryan Perkins 7546 Prince Ave Las Vegas NV 87126 5553451989 13.00
Joshua Gilbert 9278 Monroe Dr Corvallis OR 97330 5552832656 95.00
Miles Crain 4578 Chester Dr Corvallis OR 97331 5552345678 1544.00
Butch Cassidy 5498 Sutton Pl Gresham OR 97380 5416565797 1798.56
Perry Winkle 8185 Shaver Ave Las Vegas NV 87126 5553812346 195.66
Loni Day 4598 Holmen Dr Corvallis OR 97330 5555289741 1878.50
Nikita Benson 1787 Grant Pl Portland OR 97321 5553569898 1500.00
Rusty Krouger 8829 Simeon Ave Las Vegas NV 87126 5555677847 2100.00
Wally Wallace 2898 Wilson Blvd Jackson Center OH 23466 5552222222 2222.22
Joe Jones 1212 Water St Millersburg OR 97366 5555555555 55.55
Again, thanks in advance if there's anyone out there who can help me with this, your advice might save a life!... or at least the score of this lab :S
here is a tip: When using Scanner use the hasNextXXX method before invoking next methods to check if elements exists
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
No Such Element Exception?
Okay, here it is
import java.io.IOException;
import java.io.*;
import java.util.Scanner;
public class Lab2
{
public static void main(String[] args) throws IOException
{ String FirstName, LastName, Address1, Address2, Address3, AddressFull, City, State, Phone, ZipString, DonString, line = "blank";
int Zip;
double Donation;
Scanner fileScan = new Scanner(new File("F:/test.txt")).useDelimiter("\n");
PersonStats[] Donators = new PersonStats[5];
String tempVal="";
int i = 0;
while(fileScan.hasNext())
{
tempVal = fileScan.next(); //Storing person records one at a time in the string line by line
String tempArr[] = tempVal.split("\t"); //Splitting each person record string by tab and storing it in a String array
FirstName = tempArr[0];
LastName = tempArr[1];
Address1 = tempArr[2];
Address2 = tempArr[3];
Address3 = tempArr[4];
AddressFull = Address1 + " " + Address2 + " " + Address3;
City = tempArr[5];
State = tempArr[6];
ZipString = tempArr[7];
Zip = Integer.parseInt(ZipString);
Phone = tempArr[8];
DonString = tempArr[9];
Donation = Double.parseDouble(DonString);
Donators[i] = new PersonStats(FirstName, LastName, AddressFull, City, State, Zip, Phone, Donation);
Donators[i].PrintOut();
i++;
}
}
}
First of all, I would like to point out that your variable names should start with lower case. I did not edit them in the code since they were used in many places. Make an habit to declare String firstName instead of String FirstName
To the code, in your code you had used a "\t" delimter which I replaced with "\n" since in the text file each line holds entire Person details. You could have used "\t" if the donation of the first person and first name of the second person were separated by the same, but they are separated by "\n"
So now Scanner fileScan will read the file line by line which I will store in String tempVal and while(fileScan.hasNext()) assures that the Scanner will keep reading only as long as there are lines to be read.
Now, every line has different information separated by "\t". So I used tempVal.split("\t") to separate them. Also, used a counter int i and removed the for loop. I guess rest of the code is pretty basic and not much different from yours.
**EDIT****
Here is the output
Rick James
8276 Carlos Ave
Las Vegas, NV 87126
5553451567 23.95
John Gibson
9127 Oak Dr
Corvallis, OR 97330
5552812313 156.78
Ron Wills
1155 Ivy Pl
Atlantic, Ga 37339
5552123145 189.56
Rita Jones
1259 Chase Ave
Las Vegas, NV 87126
5554445671 2145.6
Jason Knight
7154 Pine Dr
Gresjam, OR 97380
5558124545 3157.44
And here is the sample text.file that I used.
Rick James 8276 Carlos Ave Las Vegas NV 87126 5553451567 23.95
John Gibson 9127 Oak Dr Corvallis OR 97330 5552812313 156.78
Ron Wills 1155 Ivy Pl Atlantic Ga 37339 5552123145 189.56
Rita Jones 1259 Chase Ave Las Vegas NV 87126 5554445671 2145.60
Jason Knight 7154 Pine Dr Gresjam OR 97380 5558124545 3157.44
Scanner fileScan = new Scanner(new File("Lab2.txt"));
//PersonStats[] Donators = new PersonStats[25];
while(fileScan.hasNext()) {
line = fileScan.nextLine();
String parts[] = line.split("\t");
if(parts.length == 10) {
FirstName = parts[0];
...
}
There are some problems in addion.
First: String ist immutable. So your lineScanner will created with an empty String. If you later change this string, nothing appens for this scanner, because you create a new string with this step.
Second you have to check for an next element. (see my while loop)
To parse your data it is easyer to split the string in parts and use this to fill your Class. But if you want to use the Scanner class, you have to create on instance per line in your file.(in the while loop)

Sort a some words in a string

Assuming there is a file:
Virginia Tyler Taylor Wilson
Ohio Grant Hayes Garfield Harrison_B McKinley Taft Harding
Massachusetts Kennedy Bush_GHW
New_York VanBuren Fillmore Roosevelt_T Roosevelt_F
I need to sort it in order, and below is my code:
TreeMap<String, String> map = new TreeMap<String, String>();
while (infile1.ready()){
String line = infile1.readLine();
String s = line.substring(0, line.indexOf(" "));
String p = line.substring(line.indexOf(" "));
map.put(s, p);
}
for (String p : map.keySet()){
System.out.println(p + " " + map.get(p));
}
My output is:
Massachusetts Kennedy Bush_GHW
New_York VanBuren Fillmore Roosevelt_T Roosevelt_F
Ohio Grant Hayes Garfield Harrison_B McKinley Taft Harding
Virginia Tyler Taylor Wilson
The expected output is:
Massachusetts **Bush_GHW Kennedy**
New_York **Fillmore Roosevelt_F Roosevelt_T VanBuren**
Ohio **Garfield Grant Harding Harrison_B Hayes McKinley Taft**
Virginia **Taylor Tyler Wilson**
The only difference is the order in the value, where I bold it in the expected output.
Is there a fast way to sort String p and puts it into the map?
you can write in short way
Arrays.sort(line.substring(line.indexOf(" ")).split(" "));
try this
String[] ps = line.substring(line.indexOf(" ")).split(" ");
Arrays.sort(ps);
then try combine ps to p with " ";
Massachusetts **Bush_GHW Kennedy**
New_York **Fillmore Roosevelt_F Roosevelt_T VanBuren**
Ohio **Garfield Grant Harding Harrison_B Hayes McKinley Taft**
Virginia **Taylor Tyler Wilson**
In your above expected output how Bush Comes after mass..
So please explore output correctly.

Categories

Resources