here is an exemple of code :
private JFormattedTextField jftf2 = new JFormattedTextField();
try{
MaskFormatter mask = new MaskFormatter("###-####");
mask.install(jftf2);
}catch(ParseException e){e.printStackTrace();}
when I execute it, it shows 3 spaces then '-' then 4 spaces,i want to know how not to have those spaces, a simple empty textfield that receives no more than the characters i write. i know that there is a method mask.setPlaceholderCharacter(' '); that changes the space to another character but I just want to delete it, not to change it.
another problem is while changing the text, for exemple let's take the same mask ###-#### the string 111-1234 is valid in that mask but when i delete the 3 for exemple it shows 111-12 4 instead of 111-124 , it adds a space, how to resolve that ?
thanx
It’s not quite clear what you want as it is a bit strange to use a MaskFormatter and complain that it behaves like a MaskFormatter. But maybe you wish to do something like this:
JFormattedTextField jftf2 = new JFormattedTextField();
final InternationalFormatter fmt=new InternationalFormatter(
new MessageFormat("{0,number,000}-{1,number,0000}"));
jftf2.setFormatterFactory(new JFormattedTextField.AbstractFormatterFactory() {
public JFormattedTextField.AbstractFormatter
getFormatter(JFormattedTextField tf) {
return fmt;
}
});
jftf2.setValue(new Object[]{111,1234});
With this format the value property of the JFormattedTextField will be expressed as an object array of length 2 containing two numbers. The 000 and 0000 in the format specifier above tell it to format the numbers with leading zeros by default (though the user does not need to input them to make a valid input). But you can change it to 0 for compact numbers.
Related
is java have method to trimming text/string? like this one :
int comaNumber = input.nextInt();
string number = "234,56789";
int coma = number.indexOf(",");
string number = number.substring(0,coma(comaNumber+1));
note : it will search coma character and then it will trim the number based on amount of coma in comaNumber, the result is 234,56 (works)
is any method in java to trimming decimal number to simplify my works? (not trim() function)
Edit: the number of decimal place is specified by user input.
The easiest way is to use DecimalFormat. Although, to get that working with a comma you will need to modify the FormatSymbols.
It would be something like this:
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator(',');//this tels DecimalFormat to use ',' as the decimal separator
String pattern = "#.00";//this means that you want only 2 decimals
DecimalFormat decimalFormat = new DecimalFormat(pattern, symbols);
System.out.println(decimalFormat.parse("221012,28").doubleValue());
System.out.println(decimalFormat.format(1234.123121));
That prints
221012.28
1234,12
You could try using String.format. First switch the comma with a period. For example,
number = number.replace(",",".");
double y = Double.parseDouble(number);
String x = String.format("%.2d",number);
x = x.replace(".",",");
First, you replace the comma with a period. Then you use the parseDouble method(documentation https://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#parseDouble(java.lang.String)). Then you use String.format to save it with only two places after the decimal point. Then change decimal back to comma.
Hope this helps!
As far as I know, there is no such method. My advice is to create your own method, and then reference it whenever you need it.
I have a simple question, but it's rather difficult to google. I have an input field for a number, and I need to make this number into a currency. So, if a user inputs 120, I need to format that into $1.20. Then, if they add another digit, say the number becomes 1204, I need to format this as $12.04. I'm using a Double.ParseDouble, but for say 120, this yields $120.00. So, I guess I need something like ParseDouble that will turn a value like 120 into $1.20 instead of $120.00. How do I do this?
use Double.parseDouble(double number);, but easily multiply with 0.01 :)
Then you have your currency and everything is fine ;)
Devlen
You can do it without even parsing in a numeric.
Use a StringBuilder object to do so:
String input = "120";
String output = new StringBuilder(input).insert(input.length() - 2,".")
.insert(0, "$").toString();
System.out.println(output); // Prints $1.20
public String getNumberCurrency(double number){
NumberFormat formatter = NumberFormat.getCurrencyInstance(Locale.getDefault());
String moneyString = formatter.format(number/100);
return moneyString;
}
I have some issue like this
in my textview Rs. 99.99
String val = textview.getText().toString();
Result :: val :: Rs.99.99
i am converting that into float using this way
float value = Float.parseFloat(val);
i am getting NumberFormatException: Rs.99.99 cannot convert
any one guide me
You can do the following before converting it to float
String substring = str.length() > 2 ? str.substring(str.length() - 3) : str;
You can try this way.
System.out.println(Float.parseFloat("Rs.99.99".substring(3)));
Note: You need to make sure the string always contain "Rs." in the beginning.
i am getting numberFormat Exception Rs.99.99 cannot convert
Yes, because in method
Float.parseFloat(String s);
You get
NumberFormatException -- if the string does not contain a parsable float.
And In your case it isn't,
So best option is to apply Validation to enter only floating point numbers inside text View.
It's not entirely clear what the problem is (do all the strings that cause problems begin with Rs., or are users putting other kinds of garbage at the beginning of the input)? Here's a way to remove all characters from the string, up to (but not including) the first digit:
val = val.replaceFirst("^[^0-9]*", "");
This finds the first occurrence of a pattern that starts at the beginning of the string (the first ^) and consists of 0 or more occurrences of nondigits ([^0-9]).
I couldn't find an answer to this problem, having tried several answer here combined to find something that works, to no avail.
An application I'm working on uses a users name to create PDF's with that name in it. However, when someones name contains a special character like "Yağmur" the pdf creator freaks out and omits this special character.
However, when it gets the unicode equivalent ("Yağmur"), it prints "Yağmur" in the pdf as it should.
How do I check a name/string for any special character (regex = "[^a-z0-9 ]") and when found, replace that character with its unicode equivalent and returning the new unicoded string?
I will try to give the solution in generic way as the frame work you are using is not mentioned as the part of your problem statement.
I too faced the same kind of issue long time back. This should be handled by the pdf engine if you set the text/char encoding as UTF-8. Please find how you can set encoding in your framework for pdf generation and try it out. Hope it helps !!
One hackish way to do this would be as follows:
/*
* TODO: poorly named
*/
public static String convertUnicodePoints(String input) {
// getting char array from input
char[] chars = input.toCharArray();
// initializing output
StringBuilder sb = new StringBuilder();
// iterating input chars
for (int i = 0; i < input.length(); i++) {
// checking character code point to infer whether "conversion" is required
// here, picking an arbitrary code point 125 as boundary
if (Character.codePointAt(input, i) < 125) {
sb.append(chars[i]);
}
// need to "convert", code point > boundary
else {
// for hex representation: prepends as many 0s as required
// to get a hex string of the char code point, 4 characters long
// sb.append(String.format("&#xu%04X;", (int)chars[i]));
// for decimal representation, which is what you want here
sb.append(String.format("&#%d;", (int)chars[i]));
}
}
return sb.toString();
}
If you execute: System.out.println(convertUnicodePoints("Yağmur"));...
... you'll get: Yağmur.
Of course, you can play with the "conversion" logic and decide which ranges get converted.
Thanks in advance for your patience. This is my problem.
I'm writing a program in Java that works best with a big set of different characters.
I have to store all the characters in a String. I started with
private static final String values = "0123456789";
Then I added A-Z, a-z and all the commons symbols.
But they are still too few, so I tought that maybe Unicode could be the solution.
The problem is now: what is the best way to get all the unicode characters that can be displayed in Eclipse (my algorithm will probably fail if there are unrecognized characters - those displayed like little rectangles). Is it possible to build a string (or some strings) with all the characters present here (en.wikipedia.org/wiki/List_of_Unicode_characters) correctly displayed?
I can do a rough copy-paste from http://www.terena.org/activities/multiling/euroml/tests/test-ucspages1ucs.html or http://zenoplex.jp/tools/unicoderange_generator.html, but I would appreciate some cleaner solution.
I don't know if there is a way to extract characters fron a font (the Unifont one). Or maybe I should parse this (www. utf8-chartable.de/unicode-utf8-table.pl) webpage.
Moreover, by adding all the characters into a String I will probably get the error:
"The type generates a string that requires more than 65535 bytes to encode in Utf8 format in the constant pool" (discussed in this question on SO: /questions/10798769/how-to-process-a-string-with-823237-characters).
Hybrid solutions can be accepted. I can remove duplicates following this question on SO questions/4989091/removing-duplicates-from-a-string-in-java)
Finally: every solution to get the longest only-different-characters string is accepted.
Thanks!
You are mixing some things up. The question whether a character can be displayed in Eclipse depends on the font you have chosen; and whether the source file can be processed correctly depends on which character encoding you have set up for the source file. When choosing UTF-8 and a good unicode font you can use and display almost any character, at least more than fit into a single String literal.
But is it really required to show the character in Eclipse? You can use the unicode escapes, e.g. \u20ac to refer to characters, regardless of whether they can be displayed or if the file encoding can handle them.
And if it is not a requirement to blow up your source code, it’s easy to create a String containing all existing characters:
// all chars (i.e. UTF-16 values)
StringBuilder sb=new StringBuilder(Character.MAX_VALUE);
for(char c=0; c<Character.MAX_VALUE; c++) sb.append(c);
String s=sb.toString();
// if it should behave like a compile-time constant:
s=s.intern();
or
// all unicode characters (aka code points)
StringBuilder sb=new StringBuilder(2162686);
for(int c=0; c<Character.MAX_CODE_POINT; c++) sb.appendCodePoint(c);
String s=sb.toString();
// if it should behave like a compile-time constant:
s=s.intern();
If you wan’t the String to contain valid unicode characters only you can use if(Character.isDefined(c)) … inside the loop. But that’s a moving target— newer JRE’s will most probably know more defined characters.
Smply use Apache classes, org.apache.commons.lang.RandomStringUtils (commons-lang) can solve your purpose.
http://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/RandomStringUtils.html
Also please refer to below code for api usage,
import org.apache.commons.lang3.RandomStringUtils;
public class RandomString {
public static void main(String[] args) {
// Random string only with numbers
String string = RandomStringUtils.random(64, false, true);
System.out.println("Random 0 = " + string);
// Random alphabetic string
string = RandomStringUtils.randomAlphabetic(64);
System.out.println("Random 1 = " + string);
// Random ASCII string
string = RandomStringUtils.randomAscii(32);
System.out.println("Random 2 = " + string);
// Create a random string with indexes from the given array of chars
string = RandomStringUtils.random(32, 0, 20, true, true, "bj81G5RDED3DC6142kasok".toCharArray());
System.out.println("Random 3 = " + string);
}
}