How to get values from string in java? - java

My string: result = order=7781&state=1&value=&add=114GH;
I want to get values:
String order = "7781";
String state = "1";
String value = "";
String add = "114GH";
Please help me to solve this problem! Thanks!
I have done till here, but its not working.
String[] resDetails = result.split("&");
for(String pair : resDetails)
{
String[] entry = pair.split("=");
map.put(entry[0].trim(), entry[1].trim());
}
Its giving error because value is empty

Change split("=") to split("=", -1), so trailing empty strings will not be discarded.

Related

How to deal with NumberFormatException when reading from a csv file [duplicate]

This question already has answers here:
How can I prevent java.lang.NumberFormatException: For input string: "N/A"?
(6 answers)
Closed 9 months ago.
My task is to read values from a csv file, and import each line of information from this file into an object array. I think my issue is the blank data elements in my csv file which doesn't work for my parsing from string to int, but I have found no way to deal with this. Here is my code:
`fileStream = new FileInputStream(pFileName);
rdr = new InputStreamReader(fileStream);
bufRdr = new BufferedReader(rdr);
lineNum = 0;`
while (line != null) {
lineNum++;
String[] Values = new String[13];
Values = line.split(",");
int cumulPos = Integer.parseInt(Values[6]);
int cumulDec = Integer.parseInt(Values[7]);
int cumuRec = Integer.parseInt(Values[8]);
int curPos = Integer.parseInt(Values[9]);
int hosp = Integer.parseInt(Values[10]);
int intenCar = Integer.parseInt(Values[11]);
double latitude = Double.parseDouble(Values[4]);
double longitude = Double.parseDouble(Values[5]);
covidrecordArray[lineNum] = new CovidRecord(Values[0], cumulPos, cumulDec, cumuRec, curPos, hosp,
intenCar, new Country(Values[1], Values[2], Values[3], Values[13], latitude, longitude));
If anyone could help it would be greatly appreciated.
As already suggested, use a proper CSV Parser if you can but if for some unknown reason you can't, this could be one way you can do it. Be sure to read the comments in code:
fileStream = new FileInputStream(pFileName);
rdr = new InputStreamReader(fileStream);
bufRdr = new BufferedReader(rdr);
// Remove the following line if there is no Header line in the CSV file.
String line = bufRdr.readLine();
String csvFileDataDelimiter = ",";
List<CovidRecord> recordsList = new ArrayList<>();
// True value calculated later in code (read comments).
int expectedNumberOfElements = 0; // 0 is default
while ((line = bufRdr.readLine()) != null) {
line = line.trim();
// If for some crazy reason a blank line is encountered...skip it.
if (line.isEmpty()) {
continue;
}
/* Get the expected number of elements within each CSV File Data Line.
This is based off of the number of actual delimiters within a file
data line plus 1. This is only calculated from the very first data
line. */
if (expectedNumberOfElements == 0) {
expectedNumberOfElements = line.replaceAll("[^\\" + csvFileDataDelimiter + "]", "").length() + 1;
}
/* Create and fill (with Null String) an array to be the expected
size of a CSV data line. This is done because if a data line
contains nothing for the last data element on that line then
when the line is split, the srray that is created will be short
by one element. This will ensure that there will alsways be a
Null String ("") present within the array when there is nothing
in the CSV data line. This null string is used in data validations
so as to provide a default value (like 0) if an Array Element
contains an actual Null String (""). */
String[] csvLineElements = new String[expectedNumberOfElements];
Arrays.fill(csvLineElements, "");
/* Take the array from the split (values) and place the data into
the csvLineElements[] array. */
String[] values = line.split("\\s*,\\s*"); // Takes care of any comma/whitespace combinations (if any).
for (int i = 0; i < values.length; i++) {
csvLineElements[i] = values[i];
}
/* Is the csvLineElements[] element a String representation of a signed
or unsigned integer data type value ("-?\\d+"). If so, convert the
String array element into an Integer value. If not, provide a default
value of 0. */
int cumulPos = Integer.parseInt(csvLineElements[6].matches("-?\\d+") ? csvLineElements[6] : "0");
int cumulDec = Integer.parseInt(csvLineElements[7].matches("-?\\d+") ? csvLineElements[7] : "0");
int cumuRec = Integer.parseInt(csvLineElements[8].matches("-?\\d+") ? csvLineElements[8] : "0");
int curPos = Integer.parseInt(csvLineElements[9].matches("-?\\d+") ? csvLineElements[9] : "0");
int hosp = Integer.parseInt(csvLineElements[10].matches("-?\\d+") ? csvLineElements[10] : "0");
int intenCar = Integer.parseInt(csvLineElements[11].matches("-?\\d+") ? csvLineElements[11] : "0");
/* Is the csvLineElements[] element a String representation of a signed
or unsigned integer or floating point value ("-?\\d+(\\.\\d+)?").
If so, convert the String array element into an Double data type value.
If not, provide a default value of 0.0 */
double latitude = Double.parseDouble(csvLineElements[4]
.matches("-?\\d+(\\.\\d+)?") ? csvLineElements[4] : "0.0d");
double longitude = Double.parseDouble(csvLineElements[5]
.matches("-?\\d+(\\.\\d+)?") ? csvLineElements[5] : "0.0d");
/* Create an instance of Country to pass into the constructor of
CovidRecord below. */
Country country = new Country(csvLineElements[1], csvLineElements[2],
csvLineElements[3], csvLineElements[13],
latitude, longitude);
// Create an add an instance of CovidRecord to the recordsList List.
recordsList.add(new CovidRecord(csvLineElements[0], cumulPos, cumulDec,
cumuRec, curPos, hosp, intenCar, country));
// Do what you want with the recordList List....
}
For obvious reasons, the code above was not tested. If you have any problems with it then let me know.
You will also notice the instead of the covidrecordArray[] CovidRecord Array I opted to use a List Interface named recordsList. This List can grow dynamically whereas the array is fixed meaning you need to determine the number of data lines within the file when initializing the array. This is not required with the List.
you can create one generic method for null check and check if it's null then return empty string or any thing else based on your needs
int hosp = Integer.parseInt(checkForNull(Values[10]));
public static String checkForNull(String val) {
return (val == null ? " " : val);
}

Trying to get the Text inside a <ul> tag but its only returning the First item Selenium

this is the structure of the unodered list
structure of the unodered list
i want to get the value of "var" and "time" to two strings and save them in a ArrayList
List<String[]> finalResult = new ArrayList<>();
This is what i tried
List<WebElement> typeElements =driver.findElements(By.xpath("//*[#id=\"container\"]/section[2]/div/div[2]/div[2]/ul/li"));
for(int i=0;i<typeElements.size();i++){
WebElement typeSingle = typeElements.get(i);
String stName = typeSingle.findElement(By.xpath("//div/a/var")).getText();
String stTime = typeSingle.findElement(By.xpath("//div/a/time")).getText();
String singleType[] =stName,stTime};
finalResult.add(singleType);
}
im getting total of 13 items in the
finalResult
variable. but all the items are same
{"title1","00:23"}
{"title1","00:23"}
{"title1","00:23"}....
i want them to be like this
{"title1","00:23"}
{"title2","00:31"}.....
what am i doing wrong?
***Edit*
On each itterations inside the for loop typeSingle
is refering to different id's,
but stName , stTime variables are same
To get child element with xpath you need to use ./:
String stName = typeSingle.findElement(By.xpath("./div/a/var")).getText();
String stTime = typeSingle.findElement(By.xpath("./div/a/time")).getText();
Or use css selector:
String stName = typeSingle.findElement(By.cssSelector("var")).getText();
String stTime = typeSingle.findElement(By.cssSelector("time")).getText();
Changing this
String stName = typeSingle.findElement(By.xpath("//div/a/var")).getText();
String stTime = typeSingle.findElement(By.xpath("//div/a/time")).getText();
to this solved the issue
String stName = typeSingle.findElement(By.xpath("div/a/var")).getText();
String stTime = typeSingle.findElement(By.xpath("div/a/time")).getText();

Remove words in a string array until it becomes empty

I have "help","me","please" in a String array and I want to remove "help" from the array, i.e. after returning it as a string, remove "me" after returning it as a string, then remove the last one too, thereby making the string array empty.
I used this
public String showCurrentString(){
EditText ed = (EditText)findViewById(R.id.ed);
String edText = ed.getText().toString();
String nn =edText;
String[] blure = nn.split(" ");
int Index = 1;
for(String check : blure){
if(Arrays.asList(blure).contains(edText)){
PlaySound(StringName() + ".mp3");
Toast.makeText(getApplicationContext(),check,Toast.LENGTH_LONG).show();
But I don't know how to delete each word after toasting it.
So my main question is on how to delete a words that have been parsed or (that I have already used) from a string array.
I think you could delete the first word by doing :
nn = nn.substring(nn.indexOf(' '), nn.length);
(You can do it multiple time, just check that nn.trim().length != 0)
Suppose you have following values:
edText = "Help Me Please"
blure[0] = "Help"
blure[1] = "Me"
blure[2] = "Please"
Then this code should work fine for you:
public String showCurrentString(){
EditText ed = (EditText)findViewById(R.id.ed);
String edText = ed.getText().toString();
String nn =edText;
List<String> blure = new LinkedList<String>(Arrays.asList(nn.split("
")));
ListIterator<String> iter = blure.listIterator();
while(iter.hasNext())
{
String itemToBeRemoved = iter.next();
iter.remove();
System.out.println("Removed "+itemToBeRemoved+"!");
}
}

How to get original codes from generated pattern in java?

Suppose I have java.util.Set<String> of "200Y2Z", "20012Y", "200829", "200T2K" which follows the same pattern "200$2$", where "$" is the placeholder. Now which is the most efficient way to get Set of just unique codes from such strings in Java?
Input: java.util.Set<String> of "200Y2Z", "20012Y", "200829", "200T2K"
Expected output: java.util.Set<String> of "YZ", "1Y", "89", "TK"
My Try ::
public static void getOutPut()
{
Set<String> input = new HashSet<String>();
Set<String> output = new HashSet<String>();
StringBuffer out = null;
for(String in : input)
{
out = new StringBuffer();
StringCharacterIterator sci = new StringCharacterIterator(in);
while (sci.current( ) != StringCharacterIterator.DONE){
if (sci.current( ) == '$')
{
out.append(in.charAt(sci.getIndex()));
}
sci.next( );
}
output.add(out.toString());
}
System.out.println(output);
}
It is working fine, but is there any efficient way than this to achieve it? I need to do it for more than 1000K codes.
Get the indexes of the placeholder in the pattern:
int i = pattern.getIndexOf('$');
You'll must to iterate to obtain all the indexes:
pattern.getIndexOf('$', lastIndex+1);
The loop and the checks are up to you.
Then use charAt with the indexes over each element of the set.

Get parameter after "#" from url java

I have a redirect uri of the form https://stackexchange.com/oauth/login_success#access_token=token&expires=5678. I am trying to get the acces token from this url. tried following methods
uri.getQueryParameter("access_token"); //will return null since it is not a query param
uri.getFragment(); //will return "access_token=token&expires=5678" so i need to seperate it again.
Any direct methods? Pls help
Some one might find this helpful
String queryAfterFragment = uri.getFragment();
String dummy_url = "http://localhost?" + queryAfterFragment;
Uri dummy_uri = Uri.parse(dummy_url);
String access_token = dummy_uri.getQueryParameter("access_token");
Works like a charm and easy to use, thank me later :-)
Simple and elegant solution which can get the values which you want:
public static Map<String, String> parseUrlFragment (String url) {
Map<String, String> output = new LinkedHashMap<> ();
String[] keys = url.split ("&");
for (String key : keys) {
String[] values = key.split ("=");
output.put (values[0], (values.length > 1 ? values[1] : ""));
}
return output;
}
It's using LinkedHashMap to represent values, so it's output:
Map<String, String> data = parseUrlFragment (uri.getFragment ());
data.get ("access_token") // token
data.get ("expires") // 5678
You can try in this way
String str = "https://stackexchange.com/oauth/
login_success#access_token=token&expires=5678";
int indexOfHash = str.indexOf("#");
// now you can substring from this
String subStr = str.substring(indexOfHash+1, str.length());
System.out.println(subStr);
// now you can substring from &
String sStr=subStr.substring(0,subStr.indexOf("&"));
System.out.println(sStr);
// now you can get token
String[] arr=sStr.split("=");
System.out.println(arr[0]);
System.out.println(arr[1]);
Out put
access_token=token&expires=5678
access_token=token
access_token
token
You could use the String method split(String) with Regex
str.split("#|&|=")
this splits the string by the passed 3 chars and you get an array with all the splitted parts.
String s =
"https://stackexchange.com/oauth/login_success#access_token=token&expires=5678";
final String[] split = s.split("#|&|=");
for (String s1 : split) {
System.out.println(s1);
}
Output:
https://stackexchange.com/oauth/login_success
access_token
token
expires
5678

Categories