I am having troubles with parsing string into double. I am trying to get the price of an item but the string returns in a value like: $24.54. So the problem (I'm assumming) is that it is conflicting with the $. Is there a way to eleminate the $ and turn the 24.54 into a double and store in a variable. Here is the code: (PS I am a C++ programmer haven't programmed in Java for a while so feel free to give me tips):
Elements tdsInSecondRow = doc.select("table tr:eq(1) > td:eq(0)"); //Test the changing of these numbers
Elements prices = doc.select("table tr:eq(1) > td:eq(2)");
for (Element td : tdsInSecondRow)
{
String word = td.text(); //Saved the text into symbol
double price = Double.parseDouble(prices.text());
System.out.println(symbol);
System.out.println(price);
}
You could check if your text starts with "$".
if(word.startsWith("$")){
word = word.substring(1, word.length());
}
double price = Double.parseDouble(word.text());
Hope it helps,
Related
I am currently seeking for a bit of help with the use of arrays. Quite a newbie on the Java language, so excuse the poor etiquette towards the programming format and I forwardly thank for any answers provided.
My current quarrel with the Array is how to fetch data from any array element. Currently I use the method System.out.println(Arrays.toString(listarray)) but the problem with this method is that it's not necessarily User friendly and it can't be formatted (to my little knowledge). So I'd like to ask help on how to fetch data from an element of an array and put it in a way so its readable by any given user.
Here is the code I'm utilizing:
import java.util.Arrays;
import java.util.Scanner;
public class principal {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Array Example");
String[] listarray = new String[10];
int i = 0;
byte op;
do {
System.out.println("Select your option:");
System.out.println("1-Add");
System.out.println("2-Check");
System.out.println("3-Change");
op = input.nextByte();
switch (op) {
case 1:
input.nextLine();
System.out.println("First String:");
String a1 = input.nextLine();
System.out.println("Second String:");
String a2 = input.nextLine();
System.out.println("Third String:");
String a3 = input.nextLine();
System.out.println("(" + (i + 1) + "/10)");
listarray[i] = a1 + a2 + a3;
i++;
break;
case 2:
System.out.println(Arrays.toString(listarray));
break;
}
}while(op != 9);
}
}
While the code does work, I'd like to know how to format the data, and from a single element, not every element. Or even if I can. Thanks and I appreciate the time spent reading this question.
You have two questions:
How do you reference an array element?
How do you format output?
When you declare an array like
String[10] names;
You have an array that can hold 10 strings, numbered 0 to 9. To reference the fifth element (remembering that array indices start at 0), you would use
names[4]
You can do various things with a reference. If you put it on the right side of an equals sign, then you are assigning the value at that element to something else.
currentName = names[4];
If you put it on the left side, you are assigning something to that element.
names[4] = "Michael";
And if you put it in a println statement, it will output the value to wherever the println statement is putting things at that time, usually the console:
System.out.println(names[4]);
So much for references. And, incidentally, that's what it is called -- you are referencing the 5th element of the array, or you are referencing the indicated element of the array. You can also put the number in a variable:
var i = 4;
System.out.println[i];
Note that most of these uses of the reference assume there is something IN that element of the array. Until something is assigned there, the element is a null.
To format, I recommend looking (carefully) into the Format / Formatter classes and choosing some simple things to do what you want. As an example, you could have:
String formatString = "The name is currently %s.";
String outputString = String.format(formatString, names[i]);
and String's format method will substitute whatever is in names[i] for the %s in the format. There are also formats for ints, doubles, and dates.
For more info, see the Oracle Tutorial on arrays and on manipulating Strings.
Hope that helps
If you want to traverse the Array that is how you can do it:-
for(int i = 0; i < listArray.length; i++) {
System.out.println(listArray[i]);
}
or
for (String s : listArray) {
System.out.println(s);
}
I am writing a program and I need to input a value for index, but the index should be composite, e.g 44GH.
My question is, how to make the program to do not crash when I ask the user to input it and then I want to display it?
I have been looking for answer in the site, but they are only for integer or string type.
If anyone can help, would be really appreciated.
Scanner s input = new Scanner(System.in);
private ArrayList<Product> productList;
System.out.println("Enter the product");
String product = s.nextLine();
System.out.println("Input code for your product e.g F7PP");
String code = s.nextLine();
}
public void deleteProduct(){
System.out.println("Enter the code of your product that you want to delete ");
String removed = input.nextLine();
if (productList.isEmpty()) {
System.out.println("There are no products for removing");
} else {
String aString = input.next();
productList.remove(aString);
}
}
Remove all non digits char before casting to integer:
String numbersOnly= aString.replaceAll("[^0-9]", "");
Integer result = Integer.parseInt(numbersOnly);
The best way to do it is to create some RegEx that could solve this problem, and you test if your input matches your RegExp. Here's a good website to test RegExp : Debuggex
Then, when you know how to extract the Integer part, you parse it.
I think the OP wants to print out a string just but correct me if I am wrong. So,
Scanner input = new Scanner(System.in);
String aString = input.nextLine(); // FFR55 or something is expected
System.out.println(aString);
Then obviously you can use:
aString.replaceAll();
Integer.parseInt();
To modify the output but from what I gather, the output is expected to be something like FFR55.
Try making the code split the two parts:
int numbers = Integer.parseInt(string.replaceAll("[^0-9]", ""));
String chars = string.replaceAll("[0-9]", "").toUpperCase();
int char0Index = ((int) chars.charAt(0)) - 65;
int char1Index = ((int) chars.charAt(1)) - 65;
This code makes a variable numbers, holding the index of the number part of the input string, as well as char0Index and char1Index, holding the value of the two characters from 0-25.
You can add the two characters, or use the characters for rows and numbers for columns, or whatever you need.
I am stuck with a problem of splitting just the numbers from a given input string
take an example of a total bill of
TOTAL = $19,67,456.45
Now, for the arithmetic calculations we need just the numbers removing the
$ , .
and so every string which tries to come in the entire string of
TOTAL=$##,##,##,###
Finally we should have just the numbers for performing arithmetic calculations on bill.
I tried to solve this as follows
String price = "$12,23,44,555"
String ArrArgs[] = price.split("");
for (int i=2;i<ArrArgs.length;i++){
if (ArrArgs.equals(".")){
break;
}
if ((ArrArgs[i]).equals(",")){
}else {
strPrice = ""+strPrice+ArrArgs[i];
System.out.println("Adding "+ArrArgs[i]);
}
}
BTW All I am doing is to automate a testcase in Selenium WebDriver for bills greater than $99,99,99,999.
Thank you in advance :)
do like this
NumberFormat format = NumberFormat.getCurrencyInstance();
Number number = format.parse("$19,67,456.45");
System.out.println(number.toString());
Output
1967456.45
Try it with the String.replaceAll function:
String TOTAL = "$19,67,456.45";
System.out.println(TOTAL.replaceAll("[\\$,.]", ""));
The function takes a regular expression.
I'm writing a program to open up links based on a command entered into a console. The command is "/wiki >term array<", and it will open up a web browser with the wiki open and the term array sent through the search function of said wiki.
Here is my current code for building the term array to send to the search field:
SearchTerm = Arrays.toString(StringTerm).replace("[", "").replace("]", "").replace(",", "");
Now, all that does is get all terms passed the word "/wiki" in my slash command and prints them into a list. It also removes commas and square brackets to make what it prints cleaner.
-- I want to add a specific parameter for the first term in the array, so if it is a specific code such as "/wiki wikipedia chickens" is entered, it will send the user to wikipedia with the term "chickens" searched instead of the default wiki with the terms "wikipedia chickens" searched.
Using the current code that I have to build the term array I need to use Arrays.toString in order to print the whole array in a readable fashion, but I don't want it to print the first term in the array after it passes through my keyword filter?
When I use this code:
WIKI_HYPERLINK = WIKI_WIKIPEDIA + StringTerm[1] + StringTerm[2] + StringTerm[3] + StringTerm[4] + StringTerm[5];
It uses array terms 1 - 5, but if there are only 3 entered terms it will throw an error, and if there are more than 5 it will throw an error.
So my question is: How do I get a whole array excluding the first term?
You could use StringBuilder in a loop
// StringBuilder with initial String
StringBuilder builder = new StringBuilder(WIKI_WIKIPEDIA);
for (int i=1; i < stringTerm.length; i++) {
builder.append(stringTerm[i]);
}
String searchTerm = builder.toString();
You could try something like this:
String outputString = "";
for (int i = 1; i < StringTerm.Length; i++)
{
outputString += StringTerm[i];
}
You may also be able to use a for each loop if there is something like if (Array.Element != 0) in Java, but I don't know of one. Just edit the code above to get it in the format you need.
I really tried a lot and also searched a lot of websites...
I tried to parse a price from a website with jsoup, but it didn't work.
What I tried out is this:
try {
String str1 = "https://www.google.de/shopping/product/3996339592576509511?hl=de&q=4250155834791&oq=4250155834791&gs_l=products-cc.3...4306.7625.0.8037.13.6.0.7.0.0.60.314.6.6.0...0.0...1ac.1.LgJKDfZQvls&sa=X&ei=eeqlUY2zFNT54QSyloCoDw&ved=0CFIQgggwAA&prds=scoring:p";
doc = Jsoup.connect(str3).get();
final Elements elements = doc.select("td:lt(1)");
String price = doc.select("span").first().text();
System.out.println(price);
System.out.println("Ende");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The goal should be to extract the lowest price of the product.
example-page:
https://www.google.de/shopping/product/3996339592576509511?hl=de&q=4250155834791&oq=4250155834791&gs_l=products-cc.3...4306.7625.0.8037.13.6.0.7.0.0.60.314.6.6.0...0.0...1ac.1.LgJKDfZQvls&sa=X&ei=eeqlUY2zFNT54QSyloCoDw&ved=0CFIQgggwAA&prds=scoring:p
I would like to parse the first row that shows me the results.
in this case: ebay 24-trade365.
I need the article's price and the link to the vendor.
Can anyone help, please?
You'd do better extracting by class, also when you select for "span" you are selecting in the original doc, not the elements you have extracted. Try something like:
// get all column entries for price
final Elements elements = doc.getElementsByClass("os-price-col");
int lowest_price = Integer.MAX_VALUE;
// foreach entry
for(Element element : elements){
// get the price in text form
String text_price = element.text();
// convert to an integer
text_price = text_price.replaceAll("[^0-9.]", "");
int price = Integer.parseInt(text_price);
// check if it's the lowest
if(price < lowest_price) lowest_price = price;
}
System.out.println(lowest_price);
Obviously updating slightly to get the output in a format you want.
EDIT: Just saw that you wanted the vendor link as well. In this case I would extract a row at a time i.e.
Elements rows = doc.getElementsByClass("os-row");
Then iterate through each row and pick out the price as before, but this time do
row.getElementsByClass("os-price-col").first();
And if it's the lowest you can pick out the vendor url with something like
row.getElementsByClass("os-seller-name").first().select("a").attr("href");
If your table is already sorted and all you want is the first row:
Element table=doc.getElementsByClass("os-main-table").first();
Element firstRow=table.select("tr[class=os-row").first();
Element seller=firstRow.select("td[class=os-seller-name]").first();
String sellerName=seller.text().trim();
String sellerLink=seller.getElementsByTag("a").first().attr("href");
String price=firstRow.select("td[class=os-price-col").first().getElementsByClass("os-base_price").text();
You can find a tutorial on Jsoup navigation at http://jsoup.org/cookbook/extracting-data/dom-navigation