Put only numeric strings into hashmap [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm trying to build a hashMap from an ArrayList which contains all the variables I need plus their respective values.
The problem is, my arrayList contains variables with non numeric values (eg: var1 = "*$&/#"). How could I filter the data contained in the arrayList to get only the numeric strings.
I tried using regular expressions but the data get filtered too much and some of the variables I need get lost. I guess i'm not using the legit regex. So I tried matching the following regex and if not, assign "0" to my variable. Here's roughly what I've tried thus far:
private static final String REGEX = "-?\\d+(\\.\\d+)?";
//...
if (val_ens1_sol.matches(REGEX) && val_ens1_bord.matches(REGEX)) {
reslutatsMap.put(key_ens1_sol, val_ens1_sol);
reslutatsMap.put(key_ens1_bord, val_ens1_bord);
} else {
val_ens1_sol = "0";
val_ens1_sol = "0";
}

This was already answered somewhere else (How to check if a String is numeric in Java) but to discuss the possibilities: Either you assume that you have numeric strings, parse the string is integer or double and catch the number format exception, or you use a regex.

You can do this using BigDecimal, which will parse all integers/decimal point floats/scientific floats:
try {
new BigDecimal(val_ens1_sol);
new BigDecimal(val_ens1_bord);
} catch (NumberFormatException ignored) {
// deal with at least one value not being a number
}

Related

java: string split loose last element [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 months ago.
Improve this question
im sorry for the screen shot
the strange result for me,
while result of split does not contain the last element,
from my pov the correct result must be
['[','xtrue','']
am i right?
public static List<String> splitString(String source, String delimiter) {
if (Objects.equals(delimiter, "[")) {
return Arrays.asList(source.split("\\["));
}
String[] sArr = source.split(delimiter);
return Arrays.asList(sArr);
}
sure, guess im not safe with split operator, but a little search on google do not solve my question how to use for get as i want
A per documentation:
Trailing empty strings are therefore not included in the resulting array.
So the output is correct.
If you want trailing empty strings you'll have to use the two-parameters version of split passing a negative integer as the second parameter, since
If the limit is negative then the pattern will be applied as many times as possible and the [resulting] array can have any length
So, like you say in your own answer
source.split(delimiter, -1);
will include the empty string after the last " .
for the community
the solution for my case
source.split(delimiter, -1);
thx

I want to print digit value but its not working [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I want to print 157.30 but print 15730
The code is
String Printprice="$157.30";
double value = Integer.parseInt(Printprice.replaceAll("[^0-9]",""));
Output:
15730
First problem
Printprice.replaceAll("[^0-9]","") removes everything that is not a digit, also the decimal point.
If you want to keep the decimal point, you need to change the regex to [^0-9.] (note the . after the 0-9):
Second problem
Furthermore, Integer.parseInt parses an int, not a double. If you want a double, you should use Double.parseDouble instead:
double value = Double.parseDouble(Printprice.replaceAll("[^0-9.]",""));
Other approach
If you just want everything after the first character, you can use String#substring in order to remove the first character:
double value = Double.parseDouble(Printprice.substring(1));
Things woth noting
It shoud also be noted that variables should be camelCase by convention. Instead of Printprice, you should use printPrice:
String printPrice="$157.30";
double value = Double.parseDouble(printPrice.substring(1));
Yet another thing worth noting is that you shouldn't use IEEE floating point numbers for currency calculations as those are a bit weird. Instead, you may want to save the price in cents (as a long value) or use NumberFormat/Currency as suggested by Achintya Jha.
Try using NumberFormat class
https://docs.oracle.com/javase/8/docs/api/java/text/NumberFormat.html
NumberFormat numberformat = NumberFormat.getCurrencyInstance();
Number number = null;
try {
number = numberformat.parse("$157.30");
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(number.toString());
String price ="$157.30";
float value = Float.parseFloat(price.replace("$",""));
System.out.println(value);

How to get average in Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
How to get average using functional programming in java?
This is what I tried ...
It seems like its not working at IntStream.of
I would like to get average from a specific row of the array
public static void average(List<List<String>> rows){
IntStream stream = IntStream.of(e -> Integer.parseInt(e.get(2)));
OptionalDouble obj = stream.average();
if (obj.isPresent()) {
System.out.println(obj.getAsDouble());
}
else {
System.out.println("-1");
}
}
rows is the array are rows read from an excel file.
Stream.of(elem1, elem2) creates a stream with the stated elements.
Imagine you have a box with 100 fotos in it.
If you do Stream.of(box), you get a stream of boxes, returning 1 box.
What you wanted was a stream of fotos. To get that, you want box.stream(), not Stream.of(box).
Your next problem then is that you don't seem to understand what reduce does. You need to tell the system how to integrate two results, not just how to get a result.
What you want here isn't reducing in the first place, you want to map a given 'foto' (a List of string in your case) to an integer, which requires not just e.get(), but also an Integer.parseInt, and you want map, not reduce.

How to create error message if text field isn't a numeric value? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm trying to create a Concert ticket order form for a class assignment and want is so if they don't type a number in the Quantity field it sets a label to "Na" and if it is a numeric value it sets that label to the numeric value. I'm still new at Java and don't know what to do.
How to create error message if text field isn't a numeric value?
Solution after the discussion in the comments...
To check if the string (test) written inside the jlabel is a number or not, I used the Integer.parseInt() function, which throws "NumberFormatException" if this string is not convertible into a numeric value, an Integer in particular.
Solution
JLabel jLabel1 = new JLabel();
String test = jLabel2.getText();
try {
// Converts the string into a number
int value = Integer.parseInt(test);
// Set this number into the jlabel
jlabel1.setText(""+value);
} catch (NumberFormatException e) {
jLabel1.setText("Na");
}
If you don't know how to use the try-catch, take a look at this: The try block.

Parsing specific words out of a string [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
For a Java program I need to write, I am supplied with a string that can contain any number of the following words in any order: char, double, int
So it could look like any of these:
"charintdouble"
"charchar"
"intdoublechardouble"
I then want to store each word in an array in the order they appear in the string. So an input string of "intdoublechardouble" would result in an array that looks like this:
{"int", "double", "char", "double"}
What would be the best way of parsing the string to get all of the words out of it?
You can use replace and split methods of string
String str="intdoublechardouble";
str=str.replace("char", "char-").replace("double", "double-").replace("int", "int-");
String[] tokens=str.split("-");
Now tokens contain [int, double, char, double]
I'd start with thinking about how you might do this in real life and try turning that into a Java algorithm. A somewhat inefficient way would be to string.split on the string for each element in a string array {"char", "int", "double"}, and put all the tokens created by string.split in the correct order.
If you need an effective solution for this particular problem, this should do the trick
public Object extractWords(String s) {
ArrayList<String> array = new ArrayList<String>();
s = s.replace("t", "t,");
s = s.replace("r", "r,");
s = s.replace("e", "e,");
StringTokenizer tokenizer = new StringTokenizer(s, ",");
while (tokenizer.hasMoreTokens()) {
array.add(tokenizer.nextToken());
}
return array;
}
Obviously, this won't work in general. For other cases I guess you would have to traverse the input string char by char and compare it to the list of target words, as you have suggested.

Categories

Resources