ParseInt crashes on longer numbers - java

After a few weeks i finally found out how to parse my numbers through my app. But now the app crashes when given a number in the following format: 92839283982938 or 22.483.84.3883.
I just dont know how to make it accept those number formats. The problem is connected to a barcode scanner, so i really need it to accept those number formats.
The code i used to parse is:
JSONObject c = user.getJSONObject(Integer.parseInt(xyz)-1);

For longer number you should use Long.parseLong() instead of Integer.parseInt().
Next case 22.483.84.3883 not a numeric. You will get NumberFormatException from here.
You can use
try{
long val=Long.parseLong("xxxx")
}catch(NumberFormatException e){
// exception
}
If you want to consider 22.483.84.3883 or 22-483-84-3883 as a valid case, you need to replace . or - first.
Eg:
long val=Long.parseLong("22.483.84.3883".replaceAll("\\.", ""));
System.out.println(val);

Use Long.parseLong instead. Integer type can't contain such large numbers (the max value of Integer is 2^31-1, which is much smaller than 92839283982938). In addition, you should eliminate the dots.
Try :
JSONObject c = user.getJSONObject(Long.parseLong(xyz.replace(".",""))-1);

Related

get binary int, java

I want to pull an int from a getMethod() that is in binary format. Does anyone know how to use: int i = 0b10101010;(taken from a previous post on Stack Overflow thank you all) with a variable.
int i = 0bgetMethod(); does not work in any of the multiple ways I have tried it (0b + var, etc). I do not have the actual value, so I cannot hard code the 1's & 0's.
Any help would be appreciated. This is for an assembler, this binary number is selecting the register in the register file, passed in string format to preserve it until I parse it.
A digital computer stores all int(s) in binary (even those you encode in decimal). You can use Integer.toBinaryString(int) to see the binary representation of any int.
If you need to parse a binary String, you can use Integer.parseInt(String, int) where the first argument is the String to be parsed and second argument is a radix (for binary that would be 2).
code: int i = Integer.parseInt(Micro.RegSel, 2); produces an error(the method is not applicable for enumbody).
Micro.RegSel is an enum implements enumbody that results in a string of 4 1's & 0's. If I simply print it, it prints out dropping all the leading zeros. I need the leading zeros. My code needs a total of 32bits, and this is part of it.
one of the switch statements has: Micro.RegSel.setFourBit("0011"); This will print "11". printing the string directly from the enum: 0011
int i = Integer.parseInt(Micro.RegSel.getFourBit().toString(), 2); produces a java.lang.NumberFormatException even though Micro.RegSel.getFourBit().toString() prints all 4 digits
After trying several options (that's where I asked my question) and reading the stack trace, I realized that the problem was the default was "xxxx" for the opcodes that do not select a register.
so I rewrote it like this:
int i = 0;
String j = Micro.RegSel.getFourBit().toString();
if(j.matches("[\d]")){
i = Integer.parseInt(j, 2);
}
It works like I need it to. Thanks

Java: invoking methods in main program, but getting an error

I'm just learning Java and am practicing creating methods and then invoking them in my main program. To practice this I created a simple program that's supposed to gather data from a prospective horse rider.
Here is the main application:
public class CompleteApp {
public static void main(String[] args) {
TaskOne weight1 = new TaskOne();
TaskTwo nameagehealth1 = new TaskTwo();
TaskThree phoneaddress1 = new TaskThree();
if (weight1.Weight() < 250) {
nameagehealth1.NameAgeHealth();
phoneaddress1.AddressPhone();
}
else {
System.out.println("Thanks for checking!");
}
}
}
I've created three separate classes to do different tasks. Here is the class that's having prompting the error:
import java.util.Scanner;
public class TaskThree {
static void AddressPhone() {
Scanner input = new Scanner(System.in);
System.out.println("Please tell me your address: ");
String address = input.nextLine();
System.out.println("Please tell me your phone number: ");
int phone = input.nextInt();
System.out.println("You said your address is " + address + " and your phone is " + phone + ".");
System.out.println("Thank you for the information, we'll be in touch soon to schedule your ride.");
}
}
The error:
Exception in thread "main" java.util.InputMismatchException: For input string: "3037201234"
at java.util.Scanner.nextInt(Scanner.java:2123)
at java.util.Scanner.nextInt(Scanner.java:2076)
at TaskThree.AddressPhone(TaskThree.java:10)
at CompleteApp.main(CompleteApp.java:13)
It seems to indicate that the error is in the phone number and that is being read as a String, yet I made it an integer. I'm not sure where I'm going wrong here. Also, how would I handle it if a user entered their phone number like this: 303-720-1234 vs 3037201234?
Thanks so much for the help!
Since it can't be stored as an int due to the length as Sibbo mentioned, and you're concerned about formatting then you should store it as a String. If you have to do any type of checking to make sure the user inputs data in the correct format (either 1234567890 or 123-456-7890) then you should look into regular expressions. If you run a regular expression on your string then you will be able to get a boolean result to tell you whether or not it is valid.
Why not represent the phone number as a String and use scanner.next()? As mentioned before, when a phonenumber start with a 0 this zero would be removed if you use anything other than String, so I think it's the best way to go.
From your comments, I read that parsing it to a Long works for you. I would strongly recommend using a String though, for several reasons:
Phone numbers with leading zeroes (like international phone numbers). Integers and Longs 'trim' leading zeroes, rendering your phone numbers useless.
If you want to do some extra stuff when presenting your phone numbers (like adding dashes or anything), you will have to parse your Integer/Long back to a String and do your representation magic anyway.
As you just found out, not every phone number can be stored in a 32-bit Integer, but you already worked around that using a Long.
There are probably more reasons for this, but these 2 come to mind.
The int data type is a 32-bit signed two's complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). Your input value is out of the range of int.
You should store phone number as String rather than int. If you want to handle numbers like 303-720-1234, parse it as string, remove the - character and then use it.
The input 3037201234 is too large to be represented as an int, so it cannot be parsed as an int.
Integers in Java range from −2,147,483,648 to 2,147,483,647.
Instead of using int for variable phone declare it as long and instead of input.nextInt() use method input.nextLong(). I think this will solve your problem.

Android:how to get a value from a RSS feed and subtract it from a value in another RSS feed

Hey i have these two RSS feeds - http://www.petrolprices.com/feeds/averages.xml?search_type=town&search_value=kilmarnock and http://www.petrolprices.com/feeds/averages.xml?search_type=town&search_value=glasgow. Now what i want to do is take a value from one RSS feed and calculate it with a value from the other RSS feed. So for example
132.9 - 133.1
How would i go about doing this?
The basic idea is that the user creates the RSS URLs and then the onClick takes all the values from each of the RSS feeds and compares it against the other so that the user gets the difference so the overall money saved by selecting one or the other
To my understanding, your question has a simple answer, and a more specifically helpful answer. I'll state the simple answer of how to convert character data to a number (whether an int, double, float, etc.) first for the record, specifically focusing on the exception cases, then delve into the detail that specifically applies to your problem.
Any time you have a String representation of something you believe is a certain type of number, you can call the appropriate valueOf() or parseXYZ() method for the target wrapper class. E.g. if you're looking for an integer: theInt is the String "42". Integer.valueOf(theInt) would return an Integer with the value 42, and Integer.parseInt(theInt) would return int 42.
http://developer.android.com/reference/java/lang/Double.html
If theInt represented, say, "forty-two" or "42.0" either method would throw NumberFormatException. Parsing a floating-point number follows much the same process, except that "42.0" would parse correctly, and "42.0.0" will throw a NumberFormatException on Android. The whole string passed to one of these methods must be a valid number of the chosen type. Whitespace at the end will also throw the exception.
If you're using a Scanner, you can use hasNextXYZ() and nextXYZ() to check for and get the next number, where XYZ can be any of the primitive types. The Scanner will operate on the next token, which it will define based on the delimiters you have set.
http://developer.android.com/reference/java/util/Scanner.html
"Great, so when, where, and how should one take the numbers in the XML and pass them to any of the above methods?" You should have a data structure to hold each value, which you populate as the XML is being parsed. Based on the state of things over at your related question, it is my understanding that parsing the XML into tokens has been solved. Therefore, update your parser to call the right String-to-number conversion method for the values of highest, average, and lowest elements. The Strings you need are already correctly trimmed and are passing through the parser at each stage.
Or, to decouple your code further, create an object the hold the data sets you will be comparing, then have the parser simply instantiate and call setters. FuelData could be that object.
class FuelData {
String KEY_TYPE;
double highest;
double average;
double lowest;
// if future support for currency types needed, would go here, hook in to units attribute in xml
FuelData(String type) { // call this every time a type is encountered parsing html
KEY_TYPE = type;
}
void setHighest(String val) { // here, val is value of "Highest" element
try {
highest = Double.parseDouble(val); // because you're not using a Scanner to parse
} catch (NumberFormatException e) {
// handle appropriately
}
// perhaps sanity check: disallow negatives, check not less than lowest, etc.
}
// and so on for average and lowest
double computeSavings(FuelData pricesB) { // called by onClick
// your subtraction goes here. Perhaps you decide it's reasonable to use this method
// to compute savings for Regular vs. Premium and therefore do not check type,
// perhaps you decide that's illogical and do check types.
// Note: good arguments can be made that this method should exist in a different
// class. I've placed it here for simplicity's sake.
}
}
Collect the FuelData in a logical way, that can be accessed after parsing has finished, such as feed1 being parsed into a Set of FuelData, feed2 to a set of FuelData, etc, then have onClick take all the FuelData that was parsed out of each of the RSS feeds, do the comparisons via computeSavings, and return the results.

org.json.JSONObject messing with data

I got a different type of numbers in my json string. So parsing this numbers with JSONObject leads to 3.7E-4-like representation of this numbers. I prefer to see numbers as a string. What to do? How to prevent such conversion?
{"data":
{"number1":0.0004,
"number2":0.00038,
"number3":0.00037
}}
Simply, create a string before putting your number to JSON.
or
int number = 0;
json.put(number + "");
Can you give an example number, not represented like above?
I think it is some limitation of this particular json library. As a workaround, you could convert parsed values to BigDecimal and use it, unless the double conversion does not lose precision significantly.
For more details read this: How to prevent JSONObject from json.jar converts decimal numbers string into double

Converting string to integer, but preceding zero is being removed -Follow up

This question has been answered so please close it...
Thanks for the clarifications!!
I looked at the question above but there is an use case which we should consider before closing the issue:
I have a situation where I raise an order and the system generates a reference number as: 0000002443
I store that number as a string.
When the system sends the order out, it sends two documents. One as a requisition with the above reference number and the other as a Purchase order with a reference: 0000002444
I need to be able to store the first reference number (i.e. 0000002443) as an Integer keeping the preceding zeroes and add +1 and store as a PO reference number (i.e.0000002444) to verify the orders later.
If I keep the first reference number as a String then I won't be able to add 1 to the reference number to get the PO reference Number.
It's a Follow up question:
https://stackoverflow.com/questions/15025136/converting-string-to-integer-but-preceding-zero-is-being-removed
Integers do not have leading zeros (as it says in that other question)
You'd need to convert it to an int, add one, and then pad it back into a String:
def ref = '0000002443'
def refPlusOne = "${ref.toInteger() + 1}".padLeft( ref.length(), '0' )
Simply put, an integer doesn't have a number of leading zeroes. It doesn't even have information about whether it's decimal, hex, or anything like that. It's just an integer.
If you really need to follow your existing design, I suggest you parse it as an integer, add one, and then repad with as many zeroes as you need to get back to the original length.
To be honest, if it's really just meant to be a number, it would be better if you stored it as a number instead of using a string at all.

Categories