I am converting string to Integer, so when I receive any character, exception is thrown and execution is getting stopped. I want to skip that character and print all the remaining numbers so I kept catch inside the while loop. But now for each and every exception one error will be thrown and the remaining numbers are getting printed as per exception, but code has to send mail to the team once an exception is thrown (I will place the mailing part inside catch). It will not be good if code sends mail when each and every time exception is thrown so I have to collect all the exceptions inside that while loop and send mail at once regarding all the exception. Is it possible?
I will place the simple sample code. (Mailing part I will handle later as of please tell me the logic to collect all the exception and printing at once.)
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class dummy {
public static void main(String args[]) {
String getEach="";
List A = new ArrayList();
A.add("1");
A.add("2");
A.add("3");
A.add("AA");
A.add("4");
A.add("5");
A.add("dsfgfdsgfdshg");
A.add("30");
Iterator<String> map = A.iterator();
while (map.hasNext()) {
try {
getEach = map.next();
int getValue = Integer.parseInt(getEach);
System.out.println("Value:::::: "+getValue);
} catch (Exception E) {
System.out.println("There is an exception c" +E.getMessage());
}
}
}
}
Declare a List class with an Exception object then collect it.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class dummy {
public static void main(String args[])
{
String getEach = "";
List<String> A = new ArrayList<String>();
A.add("1");
A.add("2");
A.add("3");
A.add("AA");
A.add("4");
A.add("5");
A.add("dsfgfdsgfdshg");
A.add("30");
Iterator<String> map = A.iterator();
List<Exception> errList = new ArrayList<Exception>();
while (map.hasNext()) {
try {
getEach = map.next();
int getValue = Integer.parseInt(getEach);
System.out.println("Value:::::: " + getValue);
} catch (Exception E)
{
//System.out.println("There is an exception c" + E.getMessage());
errList.add(E);
}
}
if(!errList.isEmpty())
{
for(Iterator<Exception> eIter = errList.iterator();eIter.hasNext();)
{
Exception e = eIter.next();
System.out.println("There is an exception c" + e.getMessage());
}
}
}
}
You could I suppose just drop the try/catch altogether and use something like this:
while(map.hasNext()) {
getEach = map.next();
// If getEach contains the string representation of
// a Numerical value. The regular expression within
// the matcher below will handle signed, unsigned,
// integer, and double numerical values. If getEach
// holds a numerical value then print it.
if (getEach.matches("-?\\d+(\\.\\d+)?")) {
int getValue = Integer.parseInt(getEach);
System.out.println("Value:::::: "+getValue);
}
}
Related
I am checking if number the user entered is Zeckendorf and I want to display an exception if it is not, how do i do that? Also how do I convert the Zeckondorf to its decimal equivalent?
import java.util.Scanner;
public class IZeckendorfNumberConvertor {
static String number;
int zeckonderEquivalent;
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
convertToZeckonderNumber();
isTrueZeckonderNumber();
}
private static boolean isTrueZeckonderNumber() {
System.out.println("Enter a Zeckonder Number:");
number = scanner.nextLine();
if (number.equals("10100"))
{
return true; }
else if (number.equals("010011") || number.equals("010100"))
{
return false; }
return false;
}
private static void convertToZeckonderNumber() {
}}
I advise you not to display an exception (i.e. trace and such) as it is very user Unfriendly.
You can use the throw syntax to throw a proper exception :
throw new Exception("Given number is not a Zeckendorf number");
but be sure to catch it and display a nice and clean message :
try {
// Your input code goes here
} catch (Exception e) {
System.out.println(e.getMessage());
}
Another easier option will be to just check the return value of the method and print the results accordingly.
I will recommend to use the latter solution as exceptions are used when something bad and unexpected happens in your program and you want to handle it gracefully. In your case the behavior is expected (i.e. user giving a wrong number) so checking the return value will be much clean and easier.
Use try catch block for catch an exception
try {
} catch (Exception e) {
e.printStackTrace();
}
Also use throw for throw a new exception
Assuming to really do want to display the exception, and not a more user friendly message, the first step is probably to get the exception as a string. Then you can do what you like with that string (echo to console, place in a javax.swing.JTextArea, email it, etc).
If you just want the message from the exception, then getMessage() will do:
try { ... }
catch(FooException e) {
String msg = e.getMessage();
}
However, if you want the whole exception, stack trace and all, you'll want something like this:
public static String stackTrace(Exception e) {
StringWriter w = new StringWriter();
e.printStackTrace(new PrintWriter(w));
return w.toString();
}
// ...
try { ... }
catch(FooException e) {
String st = stackTrace(e);
}
If you just want to echo the full stack trace to the console, there is the printStackTrace(), no-arg method:
try { ... }
catch(FooException e) {
e.printStackTrace();
}
If you want to take more control of the presentation of the stack trace you can get the details with:
try { ... }
catch(FooException e) {
StackTraceElement[] stes = e.getStackTrace();
// Do something pretty with 'stes' here...
}
You can just print a error message to the user saying that the input is wrong using a simple if.
if(yourCondition){
// Happy scenario
// Go shead
}else{
// Error Scenario
System.out.println("Error. Invalid Input.");
// If you persist to throw an exception, then you can do something like this
// throw new Exception("Exception Explanation"); // I've commented this, but you can uncomment it if needed
// But the advice is to display an error message, than throw a exception.
}
And regarding the conversion, you can convert binary to decimal like this
int i = Integer.parseInt(binaryString, 2); // 2 indicates the radix here, since you want to convert from binary.
With this code snippet you can convert the String into an integer :
int numberAsInt;
try {
numberAsInt = Integer.parseInt(number);
} catch (NumberFormatException e) {
//Will throw an Exception
}
If you want to create your own Exception class, you can do it like shown here or just throw a RuntimeException with
throw new RuntimeException("Your Message");
My opinion, you can try some thing like following
public static void main(String[] args) {
if(!isTrueZeckonderNumber()){
// your message should goes here
System.out.println("Your message");
}
}
If you really want to throws an exception do following
private static boolean isTrueZeckonderNumber() throws Exception{
System.out.println("Enter a Zeckonder Number:");
number = scanner.nextLine();
if (number.equals("10100")) {
return true;
} else{
throw new Exception("your message");
}
}
What do you mean you want to display an exception?
I would suggest just giving the user feedback instead, as exceptions are used more commonly for EXCEPTIONAL actions that are not supposed to happen.
However if you do want to, you can print a message explaining what happened.
try {
} catch (Exception e) {
System.out.println(e.getMessage());
}
I have a response coming from a web service, data is in JSON form.
JSONObject event:-
{
"15:00":{"type":1,"status":null,"appointment_id":null},
"16:00":{"type":1,"status":null,"appointment_id":null},
"17:00":{"type":1,"status":null,"appointment_id":null},
"18:00":{"type":1,"status":"1","appointment_id":5}
}
I don't know the key values, they are random. So when i iterate the data using iterator by fetching keys and hasNext(). It returns the data but changes the order of coming data.
Iterator AppoinmentIter = event.keys();
while(AppoinmentIter.hasNext()){
String appointmentTime = (String)AppoinmentIter.next();
JSONObject appointmentDetails = event.getJSONObject(appointmentTime);
}
I want the data in exact order in which it is coming.
I checked this link, it suggests to use LinkedHashMap. But here they are inserting the value by keys. And i don't know the keys in my data. So how can i iterate the data in correct order. Please help..
That's not how JSON works. It assumes order doesn't matter unless you have an array. If you want order to matter, you're using the wrong format- you need yo use an array of times->values rather than just times->value.
For your particular application, you can get the set of keys, then sort them with a custom comparator that uses the value parsed as a time to order them. But the built in libraries won't do it for you, because you aren't using JSON as its designed.
Vikas, as far as i understood your problem i managed to retrieve json object in expected format, hope this will help you. Enjoy!!
String s = "{ \"15:00\":{\"type\":1,\"status\":null,\"appointment_id\":null},\"16:00\":{\"type\":1,\"status\":null,\"appointment_id\":null},\"17:00\":{\"type\":1,\"status\":null,\"appointment_id\":null},\"18:00\":{\"type\":1,\"status\":\"1\",\"appointment_id\":5}}";
try {
JSONObject jobj = new JSONObject(s);
Iterator iter = jobj.keys();
while(iter.hasNext()){
String appointmentTime = String.valueOf(iter.next());
aRRaY.add(appointmentTime);
}
Collections.sort(aRRaY);
for(String key : aRRaY){
JSONObject appointmentDetails = jobj.getJSONObject(key);
System.out.println(key +" ----- "+appointmentDetails);
}
}
catch (JSONException e) {
e.printStackTrace();
}
I don't know the implementation you have done, and what 3pp you involved. But anyway, try below codes, you would get what you want.
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
public class Test {
private static final ObjectMapper mapper = new ObjectMapper();
public static void main(String[] args) {
String json = "{"
+ "\"15:00\":{\"type\":1,\"status\":null,\"appointment_id\":null}, "
+ "\"16:00\":{\"type\":1,\"status\":null,\"appointment_id\":null},"
+ "\"17:00\":{\"type\":1,\"status\":null,\"appointment_id\":null},"
+ "\"18:00\":{\"type\":1,\"status\":\"1\",\"appointment_id\":5}"
+ "}";
LinkedHashMap<String, LinkedHashMap<String, Integer>> fromJSON = fromJSON(
json, LinkedHashMap.class);
for (Entry<String, LinkedHashMap<String, Integer>> entry : fromJSON
.entrySet()) {
System.out.print(entry.getKey());
System.out
.println(" || status = " + entry.getValue().get("status"));
}
}
public static <T> T fromJSON(String input, Class<T> clazz) {
try {
return mapper.readValue(input != null ? input : "null", clazz);
} catch (JsonParseException e) {
throw new RuntimeException(e);
} catch (JsonMappingException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
I'm writing a wrapper that needs to import some functions from the weka library; however, it's throwing me the following error:
unreported exception java.lang.Exception; must be caught or declared to be thrown
My code is below:
import java.io.*;
import weka.core.Instances;
import java.io.BufferedReader;
import java.io.FileReader;
import weka.core.converters.ConverterUtils.DataSource;
import java.lang.Integer;
public class wrapper
{
public static void main(String[] args)
{
try
{
Runtime r = Runtime.getRuntime();
Process p = r.exec("python frequency_counter_two.py nono 400 0");
BufferedReader br = new BufferedReader(new
InputStreamReader(p.getInputStream()));
p.waitFor();
String line = "";
while (br.ready())
System.out.println(br.readLine());
}
catch (Exception e)
{
String cause = e.getMessage();
if (cause.equals("python: not found"))
System.out.println("No python interpreter found.");
}
run_weka();
}
public static int run_weka()
{
DataSource source = new DataSource("features_ten_topics_10_unigrams_0_bigrams.csv");
Instances data = source.getDataSet();
// setting class attribute if the data format does not provide this information
// For example, the XRFF format saves the class attribute information as well
if (data.classIndex() == -1)
data.setClassIndex(data.numAttributes() - 1);
/*
double percent = 66.0;
Instances inst = data; // your full training set
instances.randomize(java.util.Random);
int trainSize = (int) Math.round(inst.numInstances() * percent / 100);
int testSize = inst.numInstances() - trainSize;
Instances train = new Instances(inst, 0, trainSize);
Instances test = new Instances(inst, trainSize, testSize);
// train classifier
Classifier cls = new J48();
cls.buildClassifier(train);
// evaluate classifier and print some statistics
Evaluation eval = new Evaluation(train);
eval.evaluateModel(cls, test);
System.out.println(eval.toSummaryString("\nResults\n======\n", false));
*/
}
}
any idea of what might be going on?
You have to handle the Exceptions thrown from the DataSource constructor and getDataSet() in run_weka().
If you check the docs you can see that they both throw java.lang.Exception: http://crdd.osdd.net/man/wiki/weka/core/converters/ConverterUtils.DataSource.html
Basically it is saying that some of the weka methods could throw an Exception, so you need to write some code to handle this occurance.
In this case, you would probably change your method to do something like this...
public static int run_weka() {
Instances data;
try {
DataSource source = new DataSource("features_ten_topics_10_unigrams_0_bigrams.csv");
data = source.getDataSet();
}
catch (Exception e){
System.out.println("An error occurred: " + e);
return -1;
}
// setting class attribute if the data format does not provide this information
// For example, the XRFF format saves the class attribute information as well
if (data.classIndex() == -1)
data.setClassIndex(data.numAttributes() - 1);
/*
Your commented code...
*/
}
}
Using stack data structure(s): If the input file is not balanced, the un-balance cause and the in-file localization details will be supplied. For flexibility reasons, read the balancing pairs of symbols from a text file. Test your program by considering the following pairs of symbols: ( ), { }, [ ], /* */
I'm having trouble with the last requirement: /* */
I also can't seem to grasp how to print the in-file localization details? i.e which line number of the text file the error has occured on?
The text file looks like this:
(()(()
{}}}{}{
[[[]][][]
((}})){{]
()
[]
{}
[]{}
()()()[]
*/ /*
(a+b) = c
The code:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class P1 {
private boolean match = true;
// The stack
private java.util.Stack<Character> matchStack = new java.util.Stack<Character>();
// What to do with a match
public boolean ismatch() {
return match && matchStack.isEmpty();
}
// Finding a match
public void add(char c) {
Character k = leftSide(c);
if (k == null)
;
else if (k.charValue() == c)
matchStack.push(k);
else {
if (matchStack.isEmpty() || !matchStack.pop().equals(k))
match = false;
}
}
// Add string values
public void add(String s) {
for (int i = 0; i < s.length(); i++)
add(s.charAt(i));
}
// The various symbol pairs
protected static Character leftSide(char c) {
switch (c) {
case '(':
case ')':
return new Character('(');
case '[':
case ']':
return new Character('[');
case '{':
case '}':
return new Character('{');
default:
return null;
}
}
// Main method. Welcome message, read the test file, build the array, print
// results.
public static void main(String args[]) {
List<String[]> arrays = new ArrayList<String[]>();
// Welcome message
System.out
.println("Project #1\n"
+ "Welcome! The following program ensures both elements of various paired symbols are present.\n"
+ "Test Data will appear below: \n"
+ "-------------------------------");
// Read the file
try {
BufferedReader in = new BufferedReader(new FileReader(
"testfile.txt"));
String str;
// Keep reading while there is still more data
while ((str = in.readLine()) != null) {
// Line by line read & add to array
String arr[] = str.split(" ");
if (arr.length > 0)
arrays.add(arr);
// Let the user know the match status (i.e. print the results)
P1 mp = new P1();
mp.add(str);
System.out.print(mp.ismatch() ? "\nSuccessful Match:\n"
: "\nThis match is not complete:\n");
System.out.println(str);
}
in.close();
// Catch exceptions
} catch (FileNotFoundException e) {
System.out
.println("We're sorry, we are unable to find that file: \n"
+ e.getMessage());
} catch (IOException e) {
System.out
.println("We're sorry, we are unable to read that file: \n"
+ e.getMessage());
}
}
}
An easy way to implement this would be using a map of stacks such as Map<String, Stack<Location>>, where Location is a class you create that holds two ints (a line number and a character number). That can be your location info. The key (String) to this map would be your left side (opener) part of your pairs. Every time you have an opener you look up the appropriate Stack in the map and push a new Location on it for that opener. Each time you encounter a closer you look up its opener, use the opener to look up the correct Stack in the map and then pop it once. The reason I say use String for your key is because not all your openers can be represented by Character namely your /* opener, so a String will have to do. Since you can't switch on Strings for your leftSide(char) (which will now be leftSide(String)) function you'll either have to use if-else or use a map (Map<String, String>) to create the closer to opener mappings.
When the end of the file is reached the only Location objects remaining in the Stack objects should be unclosed openers.
This question already has answers here:
How to check if a String is numeric in Java
(41 answers)
Closed 5 years ago.
I have conversion to Map problem in Core Java.
Below is requirement:
Given a String array below
String str[] = {"abc","123","def","456","ghi","789","lmn","101112","opq"};
Convert it into a Map such that the resultant output is below
Output
====== ======
key Value
====== ======
abc true
123 false
def true
456 false
The above should be printed for each element in the array. I have written the code but it's not working and I'm stuck. Please let me know how it can be resolved. Thanks in advance.
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class CoversionToMap {
/**
* #param args
*/
public static void main(String[] args) {
String str[] = {"abc","123","def","456","ghi","789","lmn","101112","opq"};
Map m = new HashMap();
for(int i=0;i<str.length;i++){
if(Integer.parseInt(str[i]) < 0){
m.put(str[i],true);
}else{
m.put(str[i],false);
}
}
//Print the map values finally
printMap(m);
}
public static void printMap(Map mp) {
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
System.out.println(pairs.getKey() + " = " + pairs.getValue());
}
}
}
exception:
Exception in thread "main" java.lang.NumberFormatException: For input string: "abc"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at CoversionToMap.main(CoversionToMap.java:22)
Everyone is suggesting using exception handling for this, there is nothing exceptional here to warrant using exceptions like this, you don't try turning left in your car and if you crash go right do you? Something like this should do it
Map<String, Boolean> m = new HashMap<String, Boolean>();
for (String str: strs) {
m.put(str, isInteger(str));
}
public boolean isInteger(String str) {
int size = str.length();
for (int i = 0; i < size; i++) {
if (!Character.isDigit(str.charAt(i))) {
return false;
}
}
return size > 0;
}
Much clearer and more efficient that catching throwing exception, even when there are 99% integers as the integer value is not even needed so no conversion required.
Integer.parseInt(..) throws an exception for invalid input.
Your if clause should look like this:
if (isNumber(str[i])) {
...
} else {
...
}
Where isNumber can be implemented in multiple ways. For example:
using try { Integer.parseInt(..) } catch (NumberFormatException ex) (see this related question)
using commons-lang NumberUtils.isNumber(..)
You check if parseInt returns a number smaller than 0 to see if the input is non-numeric.
However, that method doesn't return any value at all, if the input is non-numeric. Instead it throws an exception, as you have seen.
The simplest way to do what you want is to catch that exception and act accordingly:
try {
Integer.parseInt(str[i]);
// str[i] is numeric
} catch (NumberFormatException ignored) {
// str[i] is not numeric
}
If you want to check if the string is a valid Java number you can use the method isNumber from the org.apache.commons.lang.math (doc here: http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/math/NumberUtils.html).
This way you won't have to write your own implementation of isNumber
You need to use a try/catch block instead of testing the return value for parseInt.
try {
Integer.parseInt(str[i]);
m.put(str[i],true);
} catch(NumberFormatException e) {
m.put(str[i],false);
}
Your error occurs here:
if(Integer.parseInt(str[i]) < 0){
Integer.parseInt throws a NumberFormatException when the input isn't a number, so you need to use a try/catch block, for example:
try{
int number = Integer.parseInt(str[i]);
m.put(str[i],false);
}catch NumberFormatException nfe{
m.put(str[i],true);
}
Assuming you won't use any external libraries, you can also use a Regular Expression Matcher to do that. Just like
for (String element : str) {
m.put(element, element.matches("\\d+"));
}
Note that this works only with non-negative integers, but you can adapt the regular expression to match the number formats you want to map as true. Also, if element is null, you'll get a NullPointerException, so a little defensive code is required here.
Here is an improved answer which can be used for numbers with negative value, decimal points etc. It uses Regular Expressions.
Here it it:
public class StringValidator {
public static void printMap(Map<String, Boolean> map) {
Iterator it = map.entrySet().iterator();
for(Map.Entry<String, Boolean> entry:map.entrySet()){
System.out.println(entry.getKey()+" = "+ entry.getValue());
}
}
}
class ValidateArray{
public static void main(String[] args) {
String str[] = {"abcd", "123", "101.112", "-1.54774"};
Map<String, Boolean> m = new HashMap<String, Boolean>();
for (String s : str) {
m.put(s, isNumber(s));
}
StringValidator.printMap(m);
}
public static boolean isNumber(String str) {
Pattern pattern = Pattern.compile("^-?\\d+\\.?\\d*$");
Matcher matcher = pattern.matcher(str);
return matcher.matches();
}
}
Replace your parseInt line with a call to isInteger(str[i]) where isInteger is defined by:
public static boolean isInteger(String text) {
try {
new Integer(text);
return true;
} catch (NumberFormatException e) {
return false;
}
}
I would like to enter the contrary view on 'don't use exception handling' here. The following code:
try
{
InputStream in = new FileInputStream(file);
}
catch (FileNotFoundException exc)
{
// ...
}
is entirely equivalent to:
if (!file.exists())
{
// ...
}
else
try
{
InputStream in = new FileInputStream(file);
}
catch (FileNotFoundException exc)
{
// ...
}
except that in the former case:
The existence of the file is only checked once
There is no timing-window between the two checks during which things can change.
The processing at // ... is only programmed once.
So you don't see code like the second case. At least you shouldn't.
The present case is identical except that because it's a String there is no timing window. Integer.parseInt() has to check the input for validity anyway, and it throws an exception which must be caught somewhere anyway (unless you like RTEs stopping your threads). So why do everything twice?
The counter-argument that you shouldn't use exceptions for normal flow control just begs the question. Is it normal flow control? or is it an error in the input? [In fact I've always understood that principle to mean more specifically 'don't throw exceptions to your own code' within the method, and even then there are rare cases when it's the best answer. I'm not a fan of blanket rules of any kind.]
Another example detecting EOF on an ObjectInputStream. You do it by catching EOFException. There is no other way apart from prefixing a count to the stream, which is a design change and a format change. So, is EOF part of the normal flow, or is it an exception? and how can it be part of the normal flow given that it is only reported via an exception?
Here's a more general way to validate, avoiding exceptions, and using what the Format subclasses already know. For example the SimpleDateFormat knows that Feb 31 is not valid, as long as you tell it not to be lenient.
import java.text.Format;
import java.text.NumberFormat;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
public class ValidatesByParsePosition {
private static NumberFormat _numFormat = NumberFormat.getInstance();
private static SimpleDateFormat _dateFormat = new SimpleDateFormat(
"MM/dd/yyyy");
public static void printMap(Map<String, Boolean> map) {
for (Map.Entry<String, Boolean> entry : map.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
}
public static void main(String[] args) {
System.out.println("Validating Nums with ParsePosition:");
String numStrings[] = { "abcd", "123", "101.112", "-1.54774", "1.40t3" };
Map<String, Boolean> rslts = new HashMap<String, Boolean>();
for (String s : numStrings) {
rslts.put(s, isOk(_numFormat, s));
}
ValidatesByParsePosition.printMap(rslts);
System.out.println("\nValidating dates with ParsePosition:");
String dateStrings[] = { "3/11/1952", "02/31/2013", "03/14/2014",
"05/25/2014", "3/uncle george/2015" };
rslts = new HashMap<String, Boolean>();
_dateFormat.setLenient(false);
for (String s : dateStrings) {
rslts.put(s, isOk(_dateFormat, s));
}
ValidatesByParsePosition.printMap(rslts);
}
public static boolean isOk(Format format, String str) {
boolean isOK = true;
int errorIndx = -1;
int parseIndx = 0;
ParsePosition pos = new ParsePosition(parseIndx);
while (isOK && parseIndx < str.length() - 1) {
format.parseObject(str, pos);
parseIndx = pos.getIndex();
errorIndx = pos.getErrorIndex();
isOK = errorIndx < 0;
}
if (!isOK) {
System.out.println("value \"" + str
+ "\" not parsed; error at char index " + errorIndx);
}
return isOK;
}
}
boolean intVal = false;
for(int i=0;i<str.length;i++) {
intVal = false;
try {
if (Integer.parseInt(str[i]) > 0) {
intVal = true;
}
} catch (java.lang.NumberFormatException e) {
intVal = false;
}
m.put(str[i], !intVal);
}