java invert values in object constructor - java

I've question, I create an object with values like this: Edge edge = new Edge(vertice1, vertice2, weight); and add this to myEdgesList.add(edge);`
Is there any way in Java to create the same list but with inverted line1 with line2 like this: Edge edge = new Edge(vertice2, vertice1, weight); and add it to the same list.
LinkedList<Edge> edgesList = new LinkedList<>();
LinkedList<Edge> secondInverted = new LinkedList<>();
CSVReader reader = null;
try {
reader = new CSVReader(new FileReader(csvFile));
String[] line;
while ((line = reader.readNext()) != null) {
Vertex one = findVertexByName(verticesList, line[0]);
Vertex second = findVertexByName(verticesList, line[1]);
edgesList.add(new Edge(one, second, Integer.parseInt(line[2])));
secondInverted.add(new Edge(second, one, Integer.parseInt(line[2])));
}
} catch (IOException e) {
e.printStackTrace();
}
List<Edge> newList = new ArrayList<>(edgesList);
newList.addAll(edgesList);
return newList;
Thank you in advance!

I don't really get your problem. You want to add shape once with line1 and line2 as parameters and then once more with line2 and line1 as parameters?
Like
Shape s1 = new Shape(line1, line2, weight);
Shape s2 = new Shape(line2, line1, weight);
list.add(s1);
list.add(s2);

You can achieve this in multiple ways, depending when You are creating the new list.
If You want to make them simultaneously, create both shapes:
Shape shape = new Shape(line1, line2, weight);
Shape shape2 = new Shape(line2, line1, weight);
myShapeList.add(shape);
myShapeList2.add(shape2);
If you want to make it later on, You could either:
1. clone Your myShapeList, and loop through it swapping the attributes ( if You have a setter and getter in Your object )
2. Create a new myShapeList2, and for(i=0;i<myShapeList.size();i++) create a new Shape, with line1 = myShapeList[i].line2 and line2 = myShapeList[i].line1, and add it in the new list.
They could be predefined ( like when You make Your First list ), or You can get them with a getter in your object.
Post Your code if You try to make some progress and have any issues.
UPDATE
To return a joint new list consisting both Your lists try:
List<Edge> newList = new ArrayList<>(edgesList);
newList.addAll(secondInverted);
List<Edge> invertedList = new ArrayList<>(secondInverted);
You can check out more info about joining lists here, or here.

Related

Putting lists into a map

I have no idea why in every Value in my Map is putted the same last record.
The Key is ok, but in every iteration my list is putted into everyone record in map.
I dont understand why..
Could someone help ?
HashMap<Long, LinesEntity> xlsMapped = new HashMap<>();
MapEntity mapEntity = new MapEntity();
LinesEntity linesEntity = new LinesEntity();
ArrayList<String> list = new ArrayList<>();
//read first line
String line = br.readLine();
String array[];
long mapKey = 0;
while (line != null) {
array = line.split(",");
list.clear();
for (String cell : array) {
list.add(cell);
}
line = br.readLine();
linesEntity.setSingleLine(list);
dataService.saveOne(linesEntity);
xlsMapped.put(mapKey, linesEntity);
mapKey++;
}
// mapEntity.setMapa(xlsMapped);
// dataService.save(mapEntity);
}
I think you need to create new linesEntity and list object instances for each loop:
while (line != null) {
linesEntity = new LinesEntity(); // create a new LinesEntity for this loop execution
list = new ArrayList()
array = line.split(",");
Which means that technically you don't need to create them at the top, just declare them:
LinesEntity linesEntity;
ArrayList<String> list;

Reading a text file into multiple arrays in Java

I'm currently working on a program that reads in a preset text file and then manipulates the data in various ways. I've got the data manipulation to work with some dummy data but I still need to get the text file read in correctly.
The test file looks like this for 120 lines:
Aberdeen,Scotland,57,9,N,2,9,W,5:00,p.m. Adelaide,Australia,34,55,S,138,36,E,2:30,a.m. Algiers,Algeria,36,50,N,3,0,E,6:00,p.m.(etc etc)
So each of these needs to be read into its own array, in order String[] CityName,String[] Country,int[] LatDeg,int[] LatMin,String[] NorthSouth,int[] LongDeg,int LongMin,String[] EastWest,int[] Time.String[] AMPM
So the problem is that while I'm reasonably comfortable with buffered readers, designing this particular function has proven difficult. In fact, I've been drawing a blank for the past few hours. It seems like it would need multiple loops and counters but I can't figure out the precisely how.
I am assuming that you have one city per line type of file structure. If it is not, it will require a bit of tweaking in the following solution:
I will do the following way if I am more comfortable with BufferReader as you say:
List<List<String>> addresses = new ArrayList<List<String>>();
try(BufferedReader br = new BufferedReader(new FileReader(file))) {
for(String line; (line = br.readLine()) != null; ) {
addresses.add(line.split(","));
}
}
Later, let's say you want to retrieve the country information of say 'Adelaid', you can try the following:
for (List<String> cityInfo : addresses) {
if("Adelaid".equals(cityInfo.get(0)) {
country = cityInfo.get(1);
}
}
Instead of creating different arrays (like String[] CityName,String[] Country, etc.,), try using a Domain Object.
Here, you can have a Domain object or Custom class Location with attributes
public class Location
{
private String cityName;
private String country;
private String latDeg;
etc
getters();
setters();
}`
Then you can write a file reader, each line item in the file will be a Location. So result will have
Location[] locations;
or
List locations;`
To carry out this task I should think the first thing you want to do is establish how many lines of data actually exist within the data file. You say it is 120 lines but what if it happens that it will be more or less? We would want to know exactly what it is so as to properly initialize all our different Arrays. We can use a simple method to accomplish this, let's call it the getFileLinesCount() method which will ulitmately return a Integer value that would be the number of text lines the data file holds:
private int getFileLinesCount(final String filePath) {
int lines = 0;
try{
File file =new File(filePath);
if(file.exists()){
FileReader fr = new FileReader(file);
try (LineNumberReader lnr = new LineNumberReader(fr)) {
while (lnr.readLine() != null){ lines++; }
}
}
else {
throw new IllegalArgumentException("GetFileLinesCount() Method Error!\n"
+ "The supplied file path does not exist!\n(" + filePath + ")");
}
}
catch(IOException e){ e.printStackTrace(); }
return lines;
}
Place this method somewhere within your main class. Now you need to Declare and initialize all your Arrays:
String filePath = "C:\\My Files\\MyDataFile.txt";
int lines = getFileLinesCount(filePath);
String[] CityName = new String[lines];
String[] Country = new String[lines];
int[] LatDeg = new int[lines];
int[] LatMin = new int[lines];
String[] NorthSouth = new String[lines];
int[] LongDeg = new int[lines];
int[] LongMin = new int[lines];
String[] EastWest = new String[lines];
int[] Time = new int[lines];
String[] AMPM = new String[lines];
Now to fill up all those Arrays:
public static void main(String args[]) {
loadUpArrays();
// Do whatever you want to do
// with all those Arrays.....
}
private void loadUpArrays() {
// Read in the data file.
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String sCurrentLine;
int x = 0;
// Read in one line at a time and Fill the Arrays...
while ((sCurrentLine = br.readLine()) != null) {
// Split each line read into an array upon itself.
String[] fileLine = sCurrentLine.split(",");
// Fill our required Arrays...
CityName[x] = fileLine[0];
Country[x] = fileLine[1];
LatDeg[x] = Integer.parseInt(fileLine[2]);
LatMin[x] = Integer.parseInt(fileLine[3]);
NorthSouth[x] = fileLine[4];
LongDeg[x] = Integer.parseInt(fileLine[5]);
LongMin[x] = Integer.parseInt(fileLine[6]);
EastWest[x] = fileLine[7];
Time[x] = Integer.parseInt(fileLine[8]);
AMPM[x] = fileLine[9];
x++;
}
br.close();
}
catch (IOException ex) { ex.printStackTrace(); }
}
Now, I haven't tested this, I just quickly punched it out but I think you can get the jest of it.
EDIT:
As #Mad Physicist has so graciously pointed out within his comment below, a List can be used to eliminate the need to count file lines therefore eliminating the need to read the data file twice. All the file lines can be placed into the List and the number of valid file lines can be determined by the size of the List. Filling of your desired arrays can now also be achieved by iterating through the List elements and processing the data accordingly. Everything can be achieved with a single method we'll call fillArrays(). Your Arrays declaration will be a little different however:
String[] CityName;
String[] Country;
int[] LatDeg;
int[] LatMin;
String[] NorthSouth;
int[] LongDeg;
int[] LongMin;
String[] EastWest;
String[] Time;
String[] AMPM;
public static void main(String args[]) {
fillArrays("C:\\My Files\\MyDataFile.txt");
// Whatever you want to do with all
// those Arrays...
}
private void fillArrays(final String filePath) {
List<String> fileLinesList = new ArrayList<>();
try{
File file = new File(filePath);
if(file.exists()){
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String strg;
while((strg = br.readLine()) != null){
// Make sure there is no blank line. If not
// then add line to List.
if (!strg.equals("")) { fileLinesList.add(strg); }
}
br.close();
}
}
else {
throw new IllegalArgumentException("GetFileLinesCount() Method Error!\n"
+ "The supplied file path does not exist!\n(" + filePath + ")");
}
// Initialize all the Arrays...
int lines = fileLinesList.size();
CityName = new String[lines];
Country = new String[lines];
LatDeg = new int[lines];
LatMin = new int[lines];
NorthSouth = new String[lines];
LongDeg = new int[lines];
LongMin = new int[lines];
EastWest = new String[lines];
Time = new String[lines];
AMPM = new String[lines];
// Fill all the Arrays...
for (int i = 0; i < fileLinesList.size(); i++) {
String[] lineArray = fileLinesList.get(i).split(",");
CityName[i] = lineArray[0];
Country[i] = lineArray[1];
LatDeg[i] = Integer.parseInt(lineArray[2]);
LatMin[i] = Integer.parseInt(lineArray[3]);
NorthSouth[i] = lineArray[4];
LongDeg[i] = Integer.parseInt(lineArray[5]);
LongMin[i] = Integer.parseInt(lineArray[6]);
EastWest[i] = lineArray[7];
Time[i] = lineArray[8];
AMPM[i] = lineArray[9];
}
}
catch(IOException e){ e.printStackTrace(); }
}
On another note...your Time Array can not be Integer since in data, what is considered the time contains a colon (:) which is a alpha character therefore (in case you haven't noticed) I have changed its declaration to String[]

JAVA - How to create an array of objects?

I need to read a CSV file into an array of Objects.
I didn't realise that it had to go into one, and just made an ArrayList instead. I now need to fix that, and have no idea what I'm doing.
This is my code to read the CSV file into a multidimensional array.
public static void readClub() throws IOException {
BufferedReader clubBR = new BufferedReader(new FileReader(new File("nrlclubs.txt")));
String line = "";
ArrayList<String[]> clubsArr = new ArrayList<String[]>();
while ((line = clubBR.readLine()) != null) {
String[] club = new String[3];
for (int i = 0; i < 3; i++) {
String[] value = line.split(",", 3);
club[i] = value[i];
}
clubsArr.add(club);
}
A snippet of my CSV file is this:
Glebe,G Shield,Glebe District
Cumberland,C Shield,Central Cumberland
Annandale,A Shield,Annandale District
University,Lion,Sydney Uni Rugby League Club
Souths,Rabbit,South Sydney,Rabbitohs
Easts,Rooster,Eastern Suburbs,Roosters,Sydney Roosters
Balmain,Tiger,Tigers,Balmain Tigers
Newtown,Jets,Jets,Newtown Jets,Bluebags
The first word is the Team name, the second word is the Team mascot, and the rest are the alias's.
Now the question is, how do i do the same thing, but with an Array of Objects (in a class called Clubs)?
I just spent a few hours trying to get this working, only to be told its wrong, and the Array of Objects is doing my head in :'(
Thanks heaps!
edit:
ok, the actual question is this:
the program should read the content of the data file (NRLclubs.txt) into memory into an appropriate array of objects (see previous page for descriptions of the class). Do not assume that the file exists.
The description of the class is this:
Club class: the Club class represents an individual NRL club within the competition. The Club class needs to store data for the current club name, current club mascot, any aliases by which the club is or has been known. As well as the normal methods that should be created for a class (eg, constructors, ‘setters’, and ‘getters’) you will need to decide upon appropriate methods for this class based upon the general requirements of the assignment specification.
Create a new Class that will hold the data of a row.
In the easiest case you could create a class like this:
class MyClass {
public String column1;
public String column2;
public ArrayList<String> aliases = new ArrayList<String>();
public void addAliases(String[] a){
for(int i=2;i<a.length;i++){
aliases.add(a[i]);
}
}
}
Then change your ArrayList like so: ArrayList<MyClass> clubsArr = new ArrayList<MyClass>();
and your reading part like so:
while ((line = clubBR.readLine()) != null) {
MyClass club = new MyClass;
String[] value = line.split(",", 3);
club.column1 = value[0];
club.column2 = value[1];
// etc...
clubsArr.add(club);
}
MyClass[] clubs = clubsArr.toArray();
That way you will later be able to get a value from one of the objects by using its attributename (in this case for example .column2) instead of some index you would have to keep in mind.
Note that you can call the attributes in the class to your liking (e.g. clubname instead of column1)
EDIT (to help with OPs edit)
To check, if the file exists, replace the line
BufferedReader clubBR = new BufferedReader(new FileReader(new File("nrlclubs.txt")));
with
File file = new File("nrlclubs.txt");
if(!file.exists()){
System.exit(1); // no use to go any further if we have no input
}
BufferedReader clubBR = new BufferedReader(new FileReader(file));
I don't understand your question well but maybe you are looking for this:
public static void readClub() throws IOException {
BufferedReader clubBR = new BufferedReader(new FileReader(new File("nrlclubs.txt")));
String line = "";
ArrayList<Clubs> clubs = new ArrayList<Clubs>();
while ((line = clubBR.readLine()) != null) {
Clubs club = new Clubs();
String[] value = line.split(",", 3);
club.name = value[0];
club.mascot = value[1];
club.alias = value[2];
clubs.add(club);
}
}

Code is only saving one line of a text file to the array

The code I have produced is meant to provide functionality of reading a text file line by line, saving each line into an array. It seems to read in each line correctly but when I use the printProps() method it only displays one...
Code is only saving one line of a text file to the array, what's wrong with my code?
/*reading in each line of text from text file and passing it to the processProperty() method.*/
Public void readProperties(String filename) {
try {
BufferedReader reader = new BufferedReader(new FileReader(filename));
int i = 0;
String line;
line = reader.readLine();
while (line != null && !line.equals("")) {
i++;
processProperty(line);
line = reader.readLine();
}
System.out.println("" + i + " properties read");
} catch (Exception e) {
System.err.println(e.getMessage());
e.printStackTrace();
}
}
/*Breaks up the line of text in order to save the value to an array (at this point it only saves one line to the array). org.newProp(newProp) passes the new property to the Organize class where it saves it to an array.
public void processProperty(String line) {
org = new Organize();
int id = nextPropertyID;
nextPropertyID++;
String[] parts = line.split(":");
int propNo = Integer.parseInt(parts[0]);
String postcode = parts[1];
String type = parts[2];
int bedrooms = Integer.parseInt(parts[3]);
int year = Integer.parseInt(parts[4]);
int rental = Integer.parseInt(parts[5]);
Landlord landlord = theLandlord;
Tenant tenant = null;
org.propUniqueCheck(id);
propNoCheck(propNo, postcode);
postcodeCheck(postcode,propNo);
typeCheck(postcode, propNo, type);
bedroomsCheck(bedrooms, postcode, propNo);
yearCheck(propNo, postcode, year);
System.out.println("Creating property " + id);
Property newProp = new Property(id, propNo, postcode, type, bedrooms, year,
rental, landlord, tenant);
org.newProp(newProp);
org.printProps();
}
/*From here down it is the code to save the value to the array*/
public Organize() {
props = new ArrayList<Property>();
PTs = new ArrayList<PotentialTenant>();
waitingList = new LinkedList<String>();
//myList.add(new prop(Property.toString()));
}
public void newProp(Property p)
{
props.add(p);
}
I have actively been seeking help in my seminar with this problem and I can't seem to find a solution, any advice would be very much appreciated!
In processProperty you are instantiating a new Organize object. Therefore, each Property (which you create for each row) is ending up in a different ArrayList (as the first element).
One solution would be to instantiate one Organize object before you start your loop and then pass this into your processProperty method as a parameter.
When one line in your text file is an empty String, your while-loop will break.
This is the right way to implement the loop:
String line = "";
while ((line = reader.readLine()) != null) {
// your code here
}
In processProperty you are instantiating a new Organize object. Therefore, each Property (which you create for each row) is ending up in a different ArrayList (as the first element).
One solution would be to instantiate one Organize object before you start your loop and then pass this into your processProperty method as a parameter.
String line = "";
while ((line = reader.readLine()) != null) {
// your code here
}

Text file parsing using java, suggestions needed on which one to use

I can successfully read text file using InputFileStream and Scanner classes. It's very easy but I need to do something more complex than that. A little background about my project first.. I have a device with sensors, and I'm using logger that will log every 10sec data from sensors to a text file. Every 10 sec its a new line of data. So what I want is when I read a file is to grab each separate sensor data into an array. For example:
velocity altitude latitude longitude
22 250 46.123245 122.539283
25 252 46.123422 122.534223
So I need to grab altitude data (250, 252) into an array alt[]; and so forth vel[], lat[], long[]...
Then the last line of the text file will different info, just a single line. It will have the date, distance travelled, timeElapsed..
So after doing a little research I came across InputStream, Reader, StreamTokenizer and Scanner class. My question is which one would you recommend for my case? Is it possible to do what I need to do in my case? and will it be able to check what the last line of the file is so it can grab the date, distance and etc.. Thank you!
Reader + String.split()
String line;
String[] values;
BufferedReader reader = new BufferedReader(new FileReader(args[0]));
List<Integer> velocity = new ArrayList<Integer>();
List<Integer> altitude = new ArrayList<Integer>();
List<Float> latitude = new ArrayList<Float>();
List<Float> longitude = new ArrayList<Float>();
while (null != (line = reader.readLine())) {
values = line.split(" ");
if (4 == values.length) {
velocity.add(Integer.parseInt(values[0]));
altitude.add(Integer.parseInt(values[1]));
latitude.add(Float.parseFloat(values[2]));
longitude.add(Float.parseFloat(values[3]));
} else {
break;
}
}
If you need arrays not list:
velocity.toArray();
As far I undestand data lines has 4 items and last line has 3 items (date, distance, elapsed time)
I would use Scanner. Take a look at the examples here. Another option for you to use BufferedReader to read a line and then have parse method to parse that line into the tokens you want.
Also you might find this thread to be useful.
Very quick code base on the link above. The inputs array has your file data tokens.
public static void main(String[] args) {
BufferedReader in=null;
List<Integer> velocityList = new ArrayList<Integer>();
List<Integer> altitudeList = new ArrayList<Integer>();
List<Double> latitudeList = new ArrayList<Double>();
List<Double> longitudeList = new ArrayList<Double>();
try {
File file = new File("D:\\test.txt");
FileReader reader = new FileReader(file);
in = new BufferedReader(reader);
String string;
String [] inputs;
while ((string = in.readLine()) != null) {
inputs = string.split("\\s");
//here is where we copy the data from the file to the data stucture
if(inputs!=null && inputs.length==4){
velocityList.add(Integer.parseInt(inputs[0]));
altitudeList.add(Integer.parseInt(inputs[1]));
latitudeList.add(Double.parseDouble(inputs[2]));
longitudeList.add(Double.parseDouble(inputs[3]));
}
}
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
if(in!=null){
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
//here are the arrays you want!!!
Integer [] velocities = (Integer[]) velocityList.toArray();
Integer [] altitiudes = (Integer[]) altitudeList.toArray();
Double [] longitudes = (Double[]) longitudeList.toArray();
Double [] latitudes = (Double[]) latitudeList.toArray();
}
As your data is relatively simple, BufferedReader and StringTokenizer should do the trick. You'll have to read ahead by one line to detect when there are no more lines left.
Your code could be something like this
BufferedReader reader = new BufferedReader( new FileReader( "your text file" ) );
String line = null;
String previousLine = null;
while ( ( line = reader.readLine() ) != null ) {
if ( previousLine != null ) {
//tokenize and store elements of previousLine
}
previousLine = line;
}
// last line read will be in previousLine at this point so you can process it separately
But how you process the line itself is really up to you, you can use Scanner if you're feeling more comfortable with it.

Categories

Resources