Related
I made a project in Java, if I run the project from my machine everything works fine, but if I share the jar file and execute from another machine it does not work. I get this error:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "10,00"
at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2054)
at java.base/jdk.internal.math.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.base/java.lang.Double.parseDouble(Double.java:651)
at model.components.Transaction.<init>(Transaction.java:33)
at model.events.components.AddTransactionListener.actionPerformed(AddTransactionListener.java:87)
at java.desktop/javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1972)
at java.desktop/javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2313)
at java.desktop/javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:405)
at java.desktop/javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:262)
at java.desktop/javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:279)
at java.desktop/java.awt.Component.processMouseEvent(Component.java:6626)
at java.desktop/javax.swing.JComponent.processMouseEvent(JComponent.java:3389)
at java.desktop/java.awt.Component.processEvent(Component.java:6391)
at java.desktop/java.awt.Container.processEvent(Container.java:2266)
at java.desktop/java.awt.Component.dispatchEventImpl(Component.java:5001)
at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2324)
at java.desktop/java.awt.Component.dispatchEvent(Component.java:4833)
at java.desktop/java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4948)
at java.desktop/java.awt.LightweightDispatcher.processMouseEvent(Container.java:4575)
at java.desktop/java.awt.LightweightDispatcher.dispatchEvent(Container.java:4516)
at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2310)
at java.desktop/java.awt.Window.dispatchEventImpl(Window.java:2780)
at java.desktop/java.awt.Component.dispatchEvent(Component.java:4833)
at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:773)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:722)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:716)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:97)
at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:746)
at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:744)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:743)
at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
I suspect this is the code that is producing the error:
double transactionAmount = 0;
try {
if (addTransactionPanel.getAmountField().getText().equals("") || Double.parseDouble(addTransactionPanel.getAmountField().getText()) < 0.0)
throw new MyException("Enter a valid amount!");
transactionAmount = Double.parseDouble(addTransactionPanel.getAmountField().getText());
} catch(Exception e) {
errorMessage += e.getMessage() + "\n";
errorCount++;
}
addTransactionPanel.getAmountField().getText returns the text of a JTextField.
As I said before if I run the project on my machine I don't get the error (Im on Pop-os).
I made a virtual machine with Windows 10 and it works fine. I tried the code on Ubuntu which is on another disk partition and it also works.
Anyone can help me?
Without more context, I'm guessing that this is a localisation issue.
You could start by adding System.out.println(Locale.getDefault()); to your code to see what locale each platform is using.
Generally, you should be making use of JFormattedTextField or JSpinner to deal with the input format and then use their getValue method, which will actually perform the parsing, for example...
// By default, my locale is en_AU, so this is just for demonstration
// purposes, don't do this to your users
NumberFormat format = NumberFormat.getNumberInstance(Locale.GERMANY);
format.setMinimumFractionDigits(2);
format.setMaximumFractionDigits(2);
format.setRoundingMode(RoundingMode.HALF_UP);
JFormattedTextField textField = new JFormattedTextField(format);
textField.setColumns(10);
add(textField);
textField.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Will need to cast the result, as it
// returns Object by default
System.out.println(textField.getValue());
}
});
If I enter 10.10 into the field, it will output 1010, if I input 10,10 it will output 10.10
If I use Locale.getDefault() instead (ie en_AU in my case), if I enter 10.10, it will output 10.10, if I input 10,10, it will output 1010
I'm using a java wrapper to upload products from a csv to woocommerce rest api v2 using java. I keep getting this error when inserting an image:
Here is my offending input:
{regular_price=9.99, short_description=This is a short description, manage_stock=true, virtual=true, downloadable=true, images={id=0, url=https://redacted.com/assets/postcardicon.png}, stock_status=in_stock, name=Premium Quality, description=Pellentesque habitant morbi tristique senectus et netus, type=simple, sku=1234, stock_quantity=1}
Here is the offending output:
{code=rest_invalid_param, message=Invalid parameter(s): stock_status, images, data={status=400, params={stock_status=stock_status is not one of instock, outofstock, and onbackorder., images=images is not of type array.}, details={stock_status={code=rest_not_in_enum, message=stock_status is not one of instock, outofstock, and onbackorder., data=null}, images={code=rest_invalid_type, message=images is not of type array., data={param=images}}}}}
Here is valid input when omitting images:
{regular_price=9.99, short_description=This is a short description, manage_stock=true, virtual=true, downloadable=true, stock_status=instock, name=Premium Quality, description=Pellentesque habitant morbi tristique senectus et netus, type=simple, sku=1234, stock_quantity=1}
Here is valid output when omitting images:
{id=40625, name=Premium Quality, slug=premium-quality, permalink=https://redacted.com/product/premium-quality/, date_created=2022-08-13T16:22:43, date_created_gmt=2022-08-13T16:22:43, date_modified=2022-08-13T16:22:43, date_modified_gmt=2022-08-13T16:22:43, type=simple, status=publish, featured=false, catalog_visibility=visible, description=Pellentesque habitant morbi tristique senectus et netus, short_description=This is a short description, sku=1234, price=9.99, regular_price=9.99, sale_price=, date_on_sale_from=null, date_on_sale_from_gmt=null, date_on_sale_to=null, date_on_sale_to_gmt=null, on_sale=false, purchasable=true, total_sales=0, virtual=true, downloadable=true, downloads=[], download_limit=-1, download_expiry=-1, external_url=, button_text=, tax_status=taxable, tax_class=, manage_stock=true, stock_quantity=1, in_stock=true, backorders=no, backorders_allowed=false, backordered=false, sold_individually=false, weight=, dimensions={length=, width=, height=}, shipping_required=false, shipping_taxable=false, shipping_class=, shipping_class_id=0, reviews_allowed=true, average_rating=0, rating_count=0, upsell_ids=[], cross_sell_ids=[], parent_id=0, purchase_note=, categories=[], tags=[], images=[{id=0, date_created=2022-08-13T16:22:44, date_created_gmt=2022-08-13T16:22:44, date_modified=2022-08-13T16:22:44, date_modified_gmt=2022-08-13T16:22:44, src=http://redacted.com/wp-content/plugins/woocommerce/assets/images/placeholder.png, name=Placeholder, alt=Placeholder, position=0}], attributes=[], default_attributes=[], variations=[], grouped_products=[], menu_order=0, price_html=<span class="woocommerce-Price-amount amount"><bdi><span class="woocommerce-Price-currencySymbol">$</span>9.99</bdi></span>, related_ids=[], meta_data=[], _links={self=[{href=https://leads.lionpridefinancial.com/wp-json/wc/v2/products/40625}], collection=[{href=https://redacted.com/wp-json/wc/v2/products}]}}
Offending code:
Map<String, Object> productInfo = new HashMap<>();
productInfo.put("name", "Premium Quality");
productInfo.put("type", "simple");
productInfo.put("description", "Pellentesque habitant morbi tristique senectus et netus");
productInfo.put("sku", "1234");
productInfo.put("short_description", "This is a short description");
productInfo.put("virtual", true);
productInfo.put("downloadable", true);
productInfo.put("regular_price", "9.99");
productInfo.put("stock_status", "in_stock");
productInfo.put("stock_quantity", "1");
productInfo.put("manage_stock", true);
productInfo.put("images", new HashMap <String, Object>() {{
put("id",0);
put("url","https://redacted.com/assets/postcardicon.png");
}});
Map<String, Object> product = wooCommerce.create(EndpointBaseType.PRODUCTS.getValue(), productInfo);
System.out.println(productInfo.toString());
System.out.println(product.toString());
Java WooCommerce API Wrapper:
https://github.com/calatonsystems/wc-api-java
Thank you for your help! :)
shoutout to #icorederman
It requires multi dimensional array
ArrayList<Map> imagesArray = new ArrayList<Map>();
Map imagesMap = new HashMap<String, Object>() {
{
put("id", "0");
put("url",
"https://redacted.com/assets/postcardicon.png");
}
};
imagesArray.add(imagesMap);
productInfo.put("images", imagesArray);
My code :
String content = '<?xml version="1.0" encoding="UTF-8"?>
<svg width="16px" height="16px" viewBox="0 0 16 16" version="1.1"
xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<!-- Generator: Sketch 64 (93537) - https://sketch.com -->
<title>Group 36 Copy 4</title>
<desc>Created with Sketch.</desc>
<g id="Portal" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g id="Group-36-Copy-4" fill="#FFFFFF">
<path d="M0,7.162 L6,8.877 L6.00036056,9 C6.00036056,10.0543618 6.81623835,10.9181651 7.85109822,10.9945143 L8.00036056,11 C9.10493006,11 10.0003606,10.1045695 10.0003606,9 L10.0003606,9 L10.0003606,8.98076197 L16,7.266 L16.0003606,14 C16.0003606,15.1045695 15.1049301,16 14.0003606,16 L2.00036056,16 C0.895791064,16 0.000360563943,15.1045695 0.000360563943,14 L0,7.162 Z M14.0003606,4 C15.1049301,4 16.0003606,4.8954305 16.0003606,6 L16,6.226 L9.99950581,7.94095939 C9.96827529,6.8636983 9.0851817,6 8.00036056,6 C6.94978154,6 6.08839609,6.81003398 6.00669844,7.83960773 L0,6.122 L0.000360563943,6 C0.000360563943,4.8954305 0.895791064,4 2.00036056,4 L14.0003606,4 Z" id="Combined-Shape"></path>
<rect id="Rectangle" x="7.00036056" y="7" width="2" height="3" rx="1"></rect>
<path d="M10.0003606,0 C11.0547224,0 11.9185257,0.815877791 11.9948748,1.85073766 L12.0003606,2 L12.0003606,4 L10.0003606,4 L10.0003606,2 L6.00036056,2 L6.00036056,4 L4.00036056,4 L4.00036056,2 C4.00036056,0.945638205 4.81623835,0.0818348781 5.85109822,0.00548573643 L6.00036056,0 L10.0003606,0 Z" id="Path-21" fill-rule="nonzero"></path>
</g>
</g>
</svg>'
I have a string named "content" in java which holds any svg file's content that the user uploads. Now my task is to replace the value that is inside this attribute fill="#FFFFFF" with the input that my user has given.
Example : user input : ff0000
so now content string must replace this line <g id="Group-36-Copy-4" fill="#FFFFFF"> as <g id="Group-36-Copy-4" fill="#ff0000">
I am stucked. Please help.
if the fill you mention in the content never change, you can use the replace function.
content = content.replace("#FFFFFF",input)
Reference : https://www.javatpoint.com/java-string-replace
First, your code is not compilable, because you are using single quote which is for character type, you need to use double quotes for your String and escape all internal double quotes:
String content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><svg width=\"16px\" height=\"16px\" viewBox=\"0 0 16 16\" version=\"1.1\"xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\"><!-- Generator: Sketch 64 (93537) - https://sketch.com --><title>Group 36 Copy 4</title><desc>Created with Sketch.</desc><g id=\"Portal\" stroke=\"none\" stroke-width=\"1\" fill=\"none\" fill-rule=\"evenodd\"><g id=\"Group-36-Copy-4\" fill=\"#FFFFFF\"><path d=\"M0,7.162 L6,8.877 L6.00036056,9 C6.00036056,10.0543618 6.81623835,10.9181651 7.85109822,10.9945143 L8.00036056,11 C9.10493006,11 10.0003606,10.1045695 10.0003606,9 L10.0003606,9 L10.0003606,8.98076197 L16,7.266 L16.0003606,14 C16.0003606,15.1045695 15.1049301,16 14.0003606,16 L2.00036056,16 C0.895791064,16 0.000360563943,15.1045695 0.000360563943,14 L0,7.162 Z M14.0003606,4 C15.1049301,4 16.0003606,4.8954305 16.0003606,6 L16,6.226 L9.99950581,7.94095939 C9.96827529,6.8636983 9.0851817,6 8.00036056,6 C6.94978154,6 6.08839609,6.81003398 6.00669844,7.83960773 L0,6.122 L0.000360563943,6 C0.000360563943,4.8954305 0.895791064,4 2.00036056,4 L14.0003606,4 Z\" id=\"Combined-Shape\"></path><rect id=\"Rectangle\" x=\"7.00036056\" y=\"7\" width=\"2\" height=\"3\" rx=\"1\"></rect><path d=\"M10.0003606,0 C11.0547224,0 11.9185257,0.815877791 11.9948748,1.85073766 L12.0003606,2 L12.0003606,4 L10.0003606,4 L10.0003606,2 L6.00036056,2 L6.00036056,4 L4.00036056,4 L4.00036056,2 C4.00036056,0.945638205 4.81623835,0.0818348781 5.85109822,0.00548573643 L6.00036056,0 L10.0003606,0 Z\" id=\"Path-21\" fill-rule=\"nonzero\"></path></g></g></svg>";
then you can use String's replace:
content = content.replace("fill=\"#FFFFFF\"", String.format("fill=\"%s\"", replacement));
this, in case you want to replace in the same variable, use a different one otherwise.
UPDATE -
chardetect
considers the srt file to be encoded as UTF-8 with a confidence score of 1.0. I have been reading in the file with:
Files.readAllLines
set to interpret it as utf-8. With the help of others here, I determined the single digit string in fact has a length of 2... the trick now is to figure out where that extra character is coming from. The following is a en excerpt of the hex dump:
00000000: efbb bf31 0d0a 3030 3a30 303a 3034 2c35 ...1..00:00:04,5
00000010: 3031 202d 2d3e 2030 303a 3030 3a30 362c 01 --> 00:00:06,
00000020: 3439 300d 0ae3 8199 e381 9fe3 8198 e381 490.............
00000030: 8ae3 8198 e381 b6e3 828a e381 95e3 818f ................
00000040: e381 b2e3 8293 0d0a 2d20 4c75 7069 6e20 ........- Lupin
00000050: 3230 3033 2070 7265 7365 6e74 7320 2d0d 2003 presents -.
00000060: 0a0d 0a32 0d0a 3030 3a30 303a 3036 2c35 ...2..00:00:06,5
00000070: 3030 202d 2d3e 2030 303a 3030 3a30 382c 00 --> 00:00:08,
00000080: 3032 340d 0a41 2053 7475 6469 6f20 4768 024..A Studio Gh
00000090: 6962 6c69 2046 696c 6d0d 0a0d 0a33 0d0a ibli Film....3..
000000a0: 3030 3a30 303a 3133 2c30 3437 202d 2d3e 00:00:13,047 -->
000000b0: 2030 303a 3030 3a31 352c 3132 360d 0a3c 00:00:15,126..<
000000c0: 666f 6e74 2063 6f6c 6f72 3d22 2338 3838 font color="#888
000000d0: 3838 3822 3ee3 81a1 e381 b2e3 828d e380 888">...........
000000e0: 80e3 8192 e382 93e3 818d e381 a7e3 81ad ................
000000f0: e380 82e3 8080 e381 bee3 819f e380 80e3 ................
00000100: 8182 e381 8ae3 8186 e381 ade3 8080 e382 ................
Original question:
I'm reading in a .srt file using java.nio.file.Files.readAllLines().
In .srt files, every subtitle has a number line - an integer that indexes the subtitle.
As captured, this line is a string.
When I use Integer.parsint( numberLineString ), I get
java.lang.NumberFormatException
I've troubleshot this as best I can, by:
homing in on a very specific subtitle so I know this isn't being caused by some errant subtitle that might have an erroneous index with non digit characters in it.
removing any potential \n or \r away from the index number
printing the variable passed to Integer.parsint() to verify it is definitely the index string, representing an integer.
As you can see, the exception thrown is even confessing it threw the exception for the input string "1"
Exception in thread "main" java.lang.NumberFormatException: For input string: "1"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:658)
at java.base/java.lang.Integer.parseInt(Integer.java:776)
at japanese.engine.kana.JPSubsParser.parseTitles(JPSubsParser.java:218)
at japanese.engine.kana.srtManager.main(srtManager.java:25)
I'm at a loss - any help would be appreciated.
Here is an extract from the file being read:
1
00:00:04,501 --> 00:00:06,490
すたじおじぶりさくひん
- Lupin 2003 presents -
2
00:00:06,500 --> 00:00:08,024
A Studio Ghibli Film
3
00:00:13,047 --> 00:00:15,126
<font color="#888888">ちひろ げんきでね。 また あおうね りさ</font>
<font color="#8888FF">Good Luck, Chihiro. We'll meet again</font>
Here is the relevant Java code:
public int parseTitles( Map<String, ArrayList<String>> subsMap ) {
/* Setup, get iterator for the Map
* Instantiate a charMatch object for checking for the various characters */
Iterator<String> keyIter = subsMap.keySet().iterator();
JPcharMatch charMatch = new JPcharMatch();
// Loop through the map
int tempCounter = 0;
while (keyIter.hasNext() && tempCounter == 0) {
//get the current title
ArrayList<String> titleLines = subsMap.get(keyIter.next());
String trimmedLine0 = titleLines.get(0).replace("\n", "").replace("\r", "").replace("\"", "");
int indexLineInt = Integer.parseInt( trimmedLine0 );
public class srtManager {
public static void main( String[] args ) {
Path subsFilePath = Paths.get("/Volumes/Multimedia/Coding/experimenting_srts/Sen to Chihiro Kanji+Hir+Eng.srt");
SubsFileDAO subsFileDAO = new SubsFileDAO(subsFilePath);
List<String> fileLines = subsFileDAO.getLinesList();
JPSubsParser parser = new JPSubsParser( fileLines );
Map<String, ArrayList<String>> subsMap = parser.getSubsMap();
// TODO analyze to detect kanji lines and store.
parser.parseTitles(subsMap);
}
}
You are trying to interpret BOM at beginning of file as a number.
You can remove it by hand before parsing:
String BOM = new String(new byte[] { (byte) 0xef, (byte) 0xbb, (byte) 0xbf});
int indexLineInt = Integer.parseInt( trimmedLine0.replaceAll(BOM, ""));
Alternatively, there are solutions like BOMInputStream that will remove BOM transparently from provided InputStream
I have to take this text file:
Ulric Schwartz ullamcorper#Quisque.ca Fringilla Donec PC urna convallis erat
Jesse Conrad Nunc#eunulla.edu Magna Praesent Interdum Incorporated et netus
et
Ethan Eaton cursus#Nullam.co.uk Sed Consequat Auctor Institute posuere
vulputate lacus
Griffin Stephenson habitant#mattis.com Purus Sapien Institute auctor non
feugiat
Alan Howell lorem#penatibusetmagnis.com Mi Limited non sollicitudin a
Sawyer Stokes ornare#utmiDuis.com Ut Institute nibh Phasellus nulla
Nigel Sanford adipiscing#euerat.org Lacus Varius Corp Integer vitae nibh
and scan it for the email addresses, meaning an # followed by atleast three characters, a period, and atleast two more characters. I understand how to scan the file:
while(fscan.hasNext())
{
//scan for emails goes in here
}
but I'm not sure how to scan for the email.
This is what I have:
import java.io.*;
import java.util.Scanner;
public class lab11_emena {
public static void main(String[] args)
{
Scanner cscan = new Scanner(System.in);
System.out.println("Please enter the file name.");
String filename = " ";
filename= cscan.nextLine();
File inFile = new File(filename);
if(!inFile.exists())
{
System.out.println("File " + filename + " does not exist.");
System.exit(0);
}
Scanner fscan = new Scanner(inFile);//I am getting an error
here? Saying inFile was thrown
System.out.println("Opened file " + filename);
}
}
You must use a scanner to read the characters. Then check for the different requirements for each thing like the # character. So if char=="#" then it will continue looking for the other requirements. Then make it go forwards and backwards, untill it finds the spaces at either end of the email, then you can import all of the characters between them.
I would first recommend using a delimeter between the different pieces of information (i.e. a comma).
Example
Ulric Schwartz, ullamcorper#Quisque.ca, Fringilla Donec, PC urna convallis erat
Now if all your lines will have the same number of "categories (info between each comma)" of information (the above example would have 4). Then you can load each item into an array and then pull out #2,6,10, etc..
If the categories will vary then you would have to do as D3sast3r stated, find the #, then scan forwards and backwards to the spaces.
Try something like this.
Scan the entire file into an arraylist. arrays by default use whitespace as a delimiter, since there is no whitespace in a valid email address you will be fine.
while(inputFile.hasNext()) {
ArrayList.add(inputFile.next());
}
This put every character into an element of the array, using spaces to separate them. So element 0 = Urlic, element 1 = Schwartz, etc... Now you can use a regex object as gtgaxiola suggested to compare each element of the array too
String email = "\\w+#\\w{3,}\\.\\w{2,}";
This is basically an string object based on your requirements. "stuff" then a # symbol then at least 3 characters then a period then at least 2 more characters
Now search the array with a for loop and an if statement
for(i = 0; i < ArrayList.length(); i++) {
if(ArrayList.get(i).contains(email) {
//do something with the email address
}
}