Parsing data from txt file in J2ME - arrays

Basically I'm creating an indoor navigation system in J2ME. I've put the location details in a .txt file i.e.
Locations names and their coordinates.
Edges with respective start node and end node as well as the weight (length of the node).
I put both details in the same file so users dont have to download multiple files to get their map working (it could become time consuming and seem complex).
So what i did is to seperate the deferent details by typing out location Names and coordinates first, After that I seperated that section from the next section which is the edges by drawing a line with multiple underscores.
Now the problem I'm having is parsing the different details into seperate arrays by setting up a command (while manually tokenizing the input stream) to check wether the the next token is an underscore.
If it is, (in pseudocode terms), move to the next line in the stream, create a new array and fill it up with the next set of details.
I found a some explanation/code HERE that does something similar but still parses into one array, although it manually tokenizes the input. Any ideas on what to do? Thanks
Text File Explanation
The text has the following format...
<--1stSection-->
/**
* Section one has the following format
* xCoordinate;yCoordinate;LocationName
*/
12;13;New York City
40;12;Washington D.C.
...e.t.c
_________________________ <--(underscore divider)
<--2ndSection-->
/**
* Its actually an adjacency list but indirectly provides "edge" details.
* Its in this form
* StartNode/MainReferencePoint;Endnode1;distance2endNode1;Endnode2;distance2endNode2;...e.t.c
*/
philadelphia;Washington D.C.;7;New York City;2
New York City;Florida;24;Illinois;71
...e.t.c

package filereader;
import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;
import java.util.Vector;
public class FileReader {
String locationSection;
String edgeSection;
Vector locations;
Vector edges;
public FileReader(String fileName) {
// read the contents into the string
InputStream is = getClass().getResourceAsStream(fileName);
StringBuffer sb = new StringBuffer();
int ch;
try {
while ((ch = is.read()) != -1) {
sb.append((char) ch);
}
} catch (IOException e2) {
e2.printStackTrace();
}
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
String text = sb.toString();
// separate locations and edges
String separator = "_________________________";
// read location section, without last end-of-line char
int endLocationSection = text.indexOf(separator) - 1;
locationSection = text.substring(0, endLocationSection);
// read edges section, without end-of-line char after separator
int startEdgeSection = endLocationSection + separator.length() + 3;
edgeSection = text.substring(startEdgeSection, text.length());
// parse locations and edges
locations = getLocationsVector(locationSection);
edges = getEdgesVector(edgeSection);
}
// parse locations section
public Vector getLocationsVector(String section) {
Vector result = new Vector();
int startLine = 0;
int endLine = section.indexOf('\n');
while (endLine != -1) {
String line = section.substring(startLine, endLine);
result.addElement(parseLocationsLine(line, ';'));
startLine = endLine + 1;
if (endLine == section.length() - 1)
break;
endLine = section.indexOf('\n', startLine);
// if no new line found, read to the end of string
endLine = (-1 == endLine) ? section.length() - 1 : endLine;
}
return result;
}
// parse edges section
public Vector getEdgesVector(String section) {
Vector result = new Vector();
int startLine = 0;
int endLine = section.indexOf('\n');
while (endLine != -1) {
String line = section.substring(startLine, endLine - 1);
result.addElement(parseEdgesLine(line, ';'));
startLine = endLine + 1;
if (endLine == section.length() + 1)
break;
endLine = section.indexOf('\n', startLine);
// if no new line found, read to the end of string
endLine = (-1 == endLine) ? section.length() + 1 : endLine;
}
return result;
}
// parse locations line
public Hashtable parseLocationsLine(String value, char splitBy) {
Hashtable result = new Hashtable();
int xCEnd = value.indexOf(splitBy);
int yCEnd = value.indexOf(splitBy, xCEnd + 1);
result.put("x", value.substring(0, xCEnd));
result.put("y", value.substring(xCEnd + 1, yCEnd));
result.put("location", value.substring(yCEnd + 1,
value.length() - 1));
return result;
}
// parse edges line
public Hashtable parseEdgesLine(String value, char splitBy) {
Hashtable result = new Hashtable();
int snEnd = value.indexOf(splitBy);
result.put("startnode", value.substring(0, snEnd));
int n = 1;
int start = snEnd + 1;
int enEnd = value.indexOf(splitBy, snEnd + 1);
int dstEnd = value.indexOf(splitBy, enEnd + 1);
while (enEnd != -1 && dstEnd != -1) {
result.put("endnode" + String.valueOf(n),
value.substring(start, enEnd));
result.put("distance" + String.valueOf(n), value.substring(
enEnd + 1, dstEnd));
start = dstEnd + 1;
enEnd = value.indexOf(splitBy, start);
if (dstEnd == value.length())
break;
dstEnd = value.indexOf(splitBy, enEnd + 1);
// if last endnode-distance pair, read to the end of line
dstEnd = (-1 == dstEnd) ? value.length() : dstEnd;
n++;
}
return result;
}
// getters for locations and edges
public Vector getLocations() {
return locations;
}
public Vector getEdges() {
return edges;
}
}
and somewhere in application screen:
fr = new FileReader("/map.txt");
Vector vct1 = fr.getLocations();
for (int i = 0; i < vct1.size(); i++) {
Hashtable location = (Hashtable) vct1.elementAt(i);
Enumeration en = location.keys();
String fv = "";
while (en.hasMoreElements()) {
String key = (String) en.nextElement();
String value = (String)location.get(key);
fv = fv + value + "-";
}
this.add(new LabelField(fv));
}
Vector vct2 = fr.getEdges();
for (int i = 0; i < vct2.size(); i++) {
Hashtable location = (Hashtable) vct2.elementAt(i);
Enumeration en = location.keys();
String fv = "";
while (en.hasMoreElements()) {
String key = (String) en.nextElement();
String value = (String)location.get(key);
fv = fv + value + "-";
}
this.add(new LabelField(fv));
}
it will be easy to get values from hashtable by keys:
(String)location.get("x")
(String)location.get("y")
(String)location.get("location")
(String)edge.get("startnode")
(String)edge.get("endnode1")
(String)edge.get("distance1")
(String)edge.get("endnode2")
(String)edge.get("distance2")
...

Related

How to add multiple chars between string?

I want to add char in my string like '.', '"', '°'... to make it valid for google map location
The code is:
void loop() {
// print the string when a newline arrives:
if (stringComplete) {
String BB = inputString.substring(0, 6);
//String degree = "°";
//String comma = ;
//String dot = ".";
if (BB == signal) {
String LAT = inputString.substring(7, 17);
int LATperiod = LAT.indexOf('.');
int LATzero = LAT.indexOf('0');
if (LATzero == 0) {
LAT = LAT.substring(1);
}
LAT.setCharAt(2, '°');
LAT.setCharAt(5, '\'');
LAT.remove(5,1);
LAT.setCharAt(8, '.');
LAT.setCharAt(12, 'N');
String LON = inputString.substring(20, 31);
int LONperiod = LON.indexOf('.');
int LONTzero = LON.indexOf('0');
if (LONTzero == 0) {
LON = LON.substring(1);
}
LON.setCharAt(2, '°');
LON.setCharAt(5, '\'');
LON.remove(5,1);
LON.setCharAt(8, '.');
LON.setCharAt(12, 'E');
Serial.println("==LATITUDE==");
Serial.println(LAT);
Serial.println("==LONGITUDE==");
Serial.println(LON);
Serial.println("=========================");
}
Output:
==LATITUDE==
2432.06746
==LONGITUDE==
6713.13658
And I want to add chars in this string like it like:
24°32'06.746N 67°13'13.658E
sscanf + sprintf is your solution here.
First let's get needed parts of inputString:
String LAT = inputString.substring(7, 17);
char deg[3], min[3], sec_main[3], sec_frac[4];
sscanf(LAT.c_str(), "%2s%2s.%2s%s", deg, min, sec_main, sec_frac);
Then, collect all these parsed parts into one string:
char latitude[15];
sprintf(latitude, "%s°%s'%s.%s", deg, min, sec_main, sec_frac);

won't read the first line C#

I have a problem with C# read(){} function. When I open and read my document it does not read the first line:
private static void read(string file, Konteineris butas)
{
using (StreamReader reader = new StreamReader(#file))
{
string line;
line = reader.ReadLine();
while (null != (line = reader.ReadLine()))
{
string[] values = line.Split(';');
int nr = Convert.ToInt16(values[0]);
double plotas = Convert.ToDouble(values[1]);
int kambariusk = Convert.ToInt16(values[2]);
int kaina = Convert.ToInt32(values[3]);
string tnr = values[4];
Apartaments apart = new Butas(nr,plotas,kambariusk,kaina,tnr); // array of apartaments
apartaments.addapartament(apart);
}
}
}
the text file:
1;25,4;1;25000;867467212 // skips this line...
2;26,4;2;100000;867467212
3;75,4;3;2100;867467212
4;65,4;4;15000;867467212
Remove the first call to line = reader.ReadLine(); You are calling ReadLine() your loop, so you don't need it there.
Because you do a line = reader.ReadLine(); then follow it up with the same code in the while loop, by the time it hits it's first iteration of the loop, it's already done a .ReadLine() twice, thus is on the second line of the file.
Remove the line = reader.ReadLine(); from the code and retry.
private static void read(string file, Konteineris butas)
{
using (StreamReader reader = new StreamReader(#file))
{
string line;
line = reader.ReadLine();
while (null != (line = reader.ReadLine()))
{
string[] values = line.Split(';');
int nr = Convert.ToInt16(values[0]);
double plotas = Convert.ToDouble(values[1]);
int kambariusk = Convert.ToInt16(values[2]);
int kaina = Convert.ToInt32(values[3]);
string tnr = values[4];
Apartaments apart = new Apartaments(nr,plotas,kambariusk,kaina,tnr); // array of apartaments
apartaments.addapartament(apart);
}
}
}
remove this. since your while condition does this already and you will jump over the first line based on this call.
line = reader.ReadLine(); gives you a new line every time you call it.
So in your while condition you get your second line without using your first.
way1:
private static void read(string file, Konteineris butas)
{
using (StreamReader reader = new StreamReader(#file))
{
string line;
while (null != (line = reader.ReadLine()))
{
string[] values = line.Split(';');
int nr = Convert.ToInt16(values[0]);
double plotas = Convert.ToDouble(values[1]);
int kambariusk = Convert.ToInt16(values[2]);
int kaina = Convert.ToInt32(values[3]);
string tnr = values[4];
Apartaments apart = new Apartaments(nr,plotas,kambariusk,kaina,tnr); // array of apartaments
apartaments.addapartament(apart);
}
}
}
way2:
private static void read(string file, Konteineris butas)
{
using (StreamReader reader = new StreamReader(#file))
{
string line;
while (line!=null)
{
line = reader.ReadLine();
string[] values = line.Split(';');
int nr = Convert.ToInt16(values[0]);
double plotas = Convert.ToDouble(values[1]);
int kambariusk = Convert.ToInt16(values[2]);
int kaina = Convert.ToInt32(values[3]);
string tnr = values[4];
Apartaments apart = new Apartaments(nr,plotas,kambariusk,kaina,tnr); // array of apartaments
apartaments.addapartament(apart);
}
}
}

Get element if from excel Sheet [duplicate]

This question already has answers here:
how to read all cell value using Apache POI?
(2 answers)
Closed 7 years ago.
I had created my script to validate my actual result and expected result , .
As there is too many link to validated script will get too much of coding m so i need to convert this into Data Driven Case ,.
Where Webdriver will get URL , xpath ,expected value from excel .
But dont know how to proceed , .
A demo code is much appreciated
Here is my current script :
public void test() throws Exception
{
String home_logo_url="158321";
String enough_talk_promo="1057406";
System.out.println("Check for home_logo_url");
driver.get(baseUrl);
String SiteWindow = driver.getWindowHandle(); // get the current window handle
driver.findElement(By.xpath("//*[#id='logo']/a")).click();
for (String PromoWindow : driver.getWindowHandles())
{
driver.switchTo().window(PromoWindow); // switch focus of WebDriver to the next found window handle (that's your newly opened window)
}
String script = "return rlSerial;";
String value = (String) ((JavascriptExecutor)driver).executeScript(script);
Assert.assertEquals(value,home_logo_url);
driver.close();
driver.switchTo().window(SiteWindow);
System.out.println("Pass");
System.out.println("Check for enough_talk_promo");
driver.get(baseUrl + "/category/tournaments/");
driver.findElement(By.xpath("//*[#id='content']/div/div[4]/aside/div/div/p[1]/a")).click();
for (String PromoWindow : driver.getWindowHandles())
{
driver.switchTo().window(PromoWindow); // switch focus of WebDriver to the next found window handle (that's your newly opened window)
}
String sr_enough_talk_promo = (String) ((JavascriptExecutor)driver).executeScript(script);
Assert.assertEquals(sr_enough_talk_promo,enough_talk_promo);
driver.close();
driver.switchTo().window(SiteWindow);
System.out.println("Pass");
}
How to iterated to each rows and get my test case run !!!
It is much helpful , if some one can convert my existing code to work on excel sheet .
Thanks
i was working on a project in Spring that read from an excel (.xls) and this was my code if can help
private List<String> extraire (String fileName) throws IOException {
List<String> liste = new ArrayList();
FileInputStream fis = new FileInputStream(new File(fileName));
HSSFWorkbook workbook = new HSSFWorkbook(fis);
HSSFSheet spreadsheet = workbook.getSheetAt(0);
Iterator < Row > rowIterator = null;
rowIterator = spreadsheet.iterator();
while (rowIterator.hasNext()) {
int i = 0;
row = (HSSFRow) rowIterator.next();
Iterator < Cell > cellIterator = row.cellIterator();
while ( cellIterator.hasNext()) {
Cell cell = cellIterator.next();
i++;
/**
* For verifying if a line is empty
*/
if (i % 29 == 0 || i == 1) {
while ( cellIterator.hasNext() && cell.getCellType() == Cell.CELL_TYPE_BLANK) {
cell = cellIterator.next();
}
}
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
String cellule = String.valueOf(cell.getNumericCellValue());
liste.add(cellule);
break;
case Cell.CELL_TYPE_STRING:
liste.add(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BLANK:
cellule = " ";
liste.add(cellule);
break;
}
}
}
fis.close();
return liste;
}
in my controller :
List<String> liste = new ArrayList();
liste = extraire(modelnom);
for (int m=0, i=29;i<liste.size();i=i+29) {
if(i % 29 == 0) {
// i=i+29 : begin from the second line first coll
// m is line
m++;
}
String matricule = (String)liste.get(29*m).toString().trim();
float mat = Float.parseFloat(matricul); // From String to float
employe.setMatricule((int)mat); //reading mat as an int
// ... your Code
}

Could not find a part of the path using File.Copy(source,destination,true) in C# console app

I continue to get the (Could not find a part of the path 'C:\Users(user profile)\VirtualStore\Program Files (x86)\E!PC\Macros) exception. The directory is there on the drive but im not sure why i continue to get this exception.
Extra6DestPath = "C:\Users\(user profile)\VirtualStore\Program Files (x86)\E!PC\Macros\"
static void copyMacrosAndBitmaps(string ExtraSourcePath, string Extra6xDestPath )
{
//counter for total Macro count on network
int Count = 0;
//counter for total bitmap count on network
int iCount = 0;
//Get File information to use for copy
FileInfo[] macrosArray;
FileInfo[] iconArray;
//Get Directory information to use for copy
DirectoryInfo di = new DirectoryInfo(ExtraSourcePath);
DirectoryInfo diIcon = new DirectoryInfo(ExtraIconPath);
//set all macro paths as a string from directory into an array
macrosArray = di.GetFiles("*.ebm");
Count = macrosArray.Length;
//set all bitmaps from directory into an array
iconArray = diIcon.GetFiles("*.bmp");
iCount = iconArray.Length;
//copy macros into destination folder
if (Count == 0)
{
throw new FileNotFoundException("No Macros found to copy");
}
else
{
for (int i = 0; i < Count; i++)
{
File.Copy(Extra6xSourcePathW7 + macrosArray[i].ToString(), Extra6xDestPath + iconArray[i].Name, true);
}
//Copy the bitmaps into destination folder
if (iCount == 0)
{
throw new FileNotFoundException("No bitmaps found to copy");
}
else
{
for (int i = 0; i < Count; i++)
{
File.Copy(ExtraIconPath + iconArray[i].ToString(), Extra6xDestPath + iconArray[i].Name, true);
}
}
}
}
I would first try declaring the path with # symbol, to handle characters that need to be escaped:
Extra6DestPath = #"C:\Users\(user profile)\VirtualStore\Program Files (x86)\E!PC\Macros\"

LZW Decompression in C

I have an LZW compressor/decompressor written in C.
The initial table consists of ASCII characters and then each now string to be saved into the table consists of a prefix and a character both saved in a list as int.
My compression works but my decompression leaves some characters out.
The input:
<title>Agile</title><body><h1>Agile</h1></body></html>
The output I get (notice the missing 'e' and '<'):
<title>Agile</title><body><h1>Agil</h1></body>/html>
This is the code I use (the relevant part):
void expand(int * input, int inputSize) {
// int prevcode, currcode
int previousCode; int currentCode;
int nextCode = 256; // start with the same dictionary of 255 characters
dictionaryInit();
// prevcode = read in a code
previousCode = input[0];
int pointer = 1;
// while (there is still data to read)
while (pointer < inputSize) {
// currcode = read in a code
currentCode = input[pointer++];
if (currentCode >= nextCode) printf("!"); // XXX not yet implemented!
currentCode = decode(currentCode);
// add a new code to the string table
dictionaryAdd(previousCode, currentCode, nextCode++);
// prevcode = currcode
previousCode = currentCode;
}
}
int decode(int code) {
int character; int temp;
if (code > 255) { // decode
character = dictionaryCharacter(code);
temp = decode(dictionaryPrefix(code)); // recursion
} else {
character = code; // ASCII
temp = code;
}
appendCharacter(character); // save to output
return temp;
}
Can you spot it? I'd be grateful.
Your decode function returns the first character in the string. You need this character in order to add it to the dictionary, but you should not set previousCode to it. So your code should look like:
...
firstChar = decode(currentCode);
dictionaryAdd(previousCode, firstChar, nextCode++);
previousCode = currentCode;
...

Resources