Help trying to convert string to int

Hey im trying to input a string in an applet then turn it into a integer so i can use it any ideas?

long val = Long.parseLong(string);
if(val > Integer.MAX_VALUE || val <
Integer.MIN_VALUE) {
throw new Error("I don't like you :p");
int intVal = (int) val;No real need to use parseLong and check explicitly the limits. The check for MIN and MAX is performed implicitely inside Integer.parseInt(string, 10), which is called by both new Integer(string).intValue() and Integer.parseInt(string) . When the check fails, it throws a NumberFormatException.
The only difference between post#1 and post#2 is that the latter it stores the int value in the internal int data member after the call to Integer.parseInt(string, 10), hence the intValue() subsequent call.

Similar Messages

  • Exception thrown trying to convert string to int

    Hey Guys,
    i imported a csv file into my app which i divide using the split() method and put into an array then I divided the array into variables;
    fruit = piece[0];
    price = piece[1];
    unit = piece[2];Now since price has to be a double i converted it into a double;
    price2 = Double.parseDouble(price);which worked grand
    but when i try to convert unit to an integer
    unit2 = Integer.parseInt(unit);i got error
    Exception in thread "main" java.lang.NumberFormatException: For input string: "3
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    so i tried removing white spaces as follows
    target = unit.replace(" ", "");which worked and displayed grand, then i tried converting to int again but the same exception was thrown, can anyone help me with this problem, thanks
    mark

    sorry for the messed up format previously.
    Like you said the unit.replaceAll(" ", ""); did not do the trick, when displayed as a string it looked like 3 was on its own but still did not convert to int. I assume line break or something existed in the csv file like you mentioned earlier as unit was the last word in the csv file.
    when i used unit.trim(); and tried to convert to integer it worked perfectly.
    thanks all for your help,
    Mark

  • Need help, trying to print strings backwards while ignoring certain things.

    To clarify the topic what I mean is I want to spell the words the user inputs backwards while skipping over certain characters. Here's my code:
    import javax.swing.*;
    import java.util.*;
    import java.text.*;
    import java.io.*;
    class SConvert{
    private static final char BLANK = ' ';
    private static final String stop = "STOP";
    public static void main(String[] args){
    char[] ignore = new char[21];
    ignore[0] = '.';
    ignore[1] = '/';
    ignore[2] = '>';
    ignore[3] = '<';
    ignore[4] = ',';
    ignore[5] = '?';
    ignore[6] = '-';
    ignore[7] = '~';
    ignore[8] = '!';
    ignore[9] = '@';
    ignore[10] = '#';
    ignore[11] = '$';
    ignore[12] = '*';
    ignore[13] = '&';
    ignore[14] = '^';
    ignore[15] = '%';
    ignore[16] = '`';
    ignore[17] = '_';
    ignore[18] = '+';
    ignore[19] = '=';
    ignore[20] = '|';
    String word, statement, append;
    boolean go = true;
    int i, numOfchar, index;
    char[] chr;
    index = 0;
    word = " ";
    statement = " ";
    append = " ";
    Scanner scanner = new Scanner(System.in);
    while (go){
    System.out.println("Enter a word");
    word = scanner.next();
    chr = word.toCharArray();
    numOfchar = word.length();
    if (word.equals(stop)){
         break;
    else if (index < numOfchar && word.charAt(index) == BLANK + BLANK){
         index = BLANK;
    else if (index < numOfchar && word.charAt(index) == (int)ignore[19]){ //Trying to range for entire array, I don't know how.
         index++;
    else
           for (i = word.length() - 1; i >= 0; i--)
              statement = statement + chr;
              append = append + " " + statement;
    System.out.print(append + " ");
    What's messing me up is the fact that whenever I try to enter words into the program, printing append only repeat EVERY occurance of statement. For example, say I type in "Ham with gravy." I get "maH htiwmaH yvarghtiwmaH".
    That's not what I want. Also, I don't know how to make the entire array of ignore available to the program, anyway to do that?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    Wow. What's with the hostility? Even I was in error of detecting anything that could have solve the problem completely there's no need to use such a negative tone, epsecaility with someone who is learning to program in OOP, let alone the syntax of Java. Also, no your program did not solve all of my problems in it's original form. Let's take a look at it.
    Here's your code:
    import java.lang.String;
    import java.util.*;
    public class ReverseString {
      public void ReverseString(){
      public void printReverse(String s){
         int i;
        String noPrint = "no print'";
        char ch = '*';
        if(s.length()>1) printReverse(s.substring(1));
         ch = s.charAt(0);
        if (!noPrint.contains(ch + " ")) System.out.print(ch);
        return;
      public static void main(String[] args) {
          String myString = Here is my String.;
       System.out.print("My String: " + myString + " Reverse: ");
       new ReverseString().printReverse(add);
       System.out.println();
    }In it's original state the program doesn't allow for any user input, which is something I needed (and added on my own), it doesn't convert the ignore[] I had in my original code to anything readable (however this can be done in the noprint String quite easy as someone else mentioned earlier.) the if command does in fact ignore the special characters in noprint String HOWEVER it doesn' t not print those characters as they would appear in the myString String in the position that it original appeared in (which is the primary problem I am having.) That is the problem with your code and why it is not the complete to soultion to my homework problem. I've modified your code to satisifed all but one of the problems.
    Modified:
    import java.lang.String;
    import java.util.*;
    public class ReverseString {
      public void ReverseString(){
      public void printReverse(String s){
         int i;
        String noPrint = "~`!@#$%^&()-=+[{]}\':;?/>.<,'";
        char ch = '*';
        if(s.length()>1) printReverse(s.substring(1));
         ch = s.charAt(0);
        if (!noPrint.contains(ch + " ")) System.out.print(ch);
        return;
      public static void main(String[] args) {
           Scanner scanner = new Scanner(System.in);
          String myString;
          String add = " ";
           while (true) {
       System.out.println("Please input String.");
       myString = scanner.next();
       add = add + myString;
              if (myString.equals("STOP")){
                   break;
       System.out.print("My String: " + add + " Reverse: ");
       new ReverseString().printReverse(add);
       System.out.println();
    }If you run this code you'll see what am talking about. The only remaining problem, which I am about to restate if you are still unclear of it, is that the noprint String contents are ignored but not printed in the original position. If you are still having trouble understanding what I am talking about then let me show what I got by running the program.
    String: Ham with grav?y
    Reverse: yvarg htiw maH. [Note the ? is missing.]
    By removing the ! in the if command I get:
    Reverse: y?varg htiw maH. [Now the ? is in the wrong position.]
    It's suppose to be:
    String: Ham with grav?y
    Reverse: yvarg htiw ma?H.
    Secondly, I understand that you are frustrated with my apparent lack of understanding of proper Java tems and syntax but you must keep in mind I am student thus I am not fully aware of java as you are. With that one would expect you to act with a bit more patience, yet you not only took offense to an innocent comment you choose to slander my name and intelligence by erasing your code and calling my understanding of Java, ?ignorant.? I may be less than careful with my choice of words concerning Java but I do understand enough code to know the inner workings of a typical program, so please refrain from calling me ignorant or any variant of this in the future.
    I merely asked for help from general populous, do not think I owe you any particular praise for your code even if I find it is not exactly what I desired. I may be new to java but I am not new the message boards. With that said I find your response awfully rude and ask if you to refrain from do so in the future. I'm assuming you are an adult so act least act like someone with a bit of civility. If you were so committed to believing your code was the de facto solution to this problem then you could have simply asked why I say what I said, if had done so and shown me the error of my statement I would have not taken offense. Instead you choose to throw a fit and deleted your code. I do not know if you are like this around other board members but you should at least show courtesy to all members of this forum regardless of their time here.
    With that said, I think I've all ready found a solution to this problem I've had. I'll just tell the program to simply count over the position the character is in. That way it will stay in the same position.

  • How to convert String to int in JSP?

    Hi,
    I set a session attribute in Servlet and want use it in JSP, How can I convert it to int or Integer?
    the line in my code doesn't work:
    int quantity=(int)session.getAttribute("vehiclequantity") ;
    Thanks in advance.
    Wolf
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    <HTML>
    <HEAD>
    <TITLE>Using the for Statement</TITLE>
    </HEAD>
    <BODY>
    <H1>Using the for Statement</H1>
    <%=session.getAttribute("vehiclequantity") %>;
    <%
    int loopIndex;
    int quantity=(int)session.getAttribute("vehiclequantity") ;
    out.println(quantity);
    for (loopIndex = 1; loopIndex <=2; loopIndex++) {
    out.println("This is iteration number "
    + loopIndex + "<BR>");
    %>
    </BODY>
    </HTML>

    Learning how to read errors and understand them will help you solve your problems quicker by yourself... So lets take a look at the error and classes involved...
    The error says:
    "Cannor Resolve Symbol: method valueOf(java.lang.Object) in the class java.lang.Integer" and gives you line line where the error occurs: Integer quantity = Integer.valueOf(session.getAttribute("vehiclequantity"));
    Now, if we look at the API for the Integer we notice that are are only two valueOf methods: valueOf(java.lang.String s) and valueOf(java.lang.String s, int radix). Not valueOf(java.lang.Object) method.
    Now we look at the getAttribute(java.lang.String name) method of HttpSession we see that the method returns a java.lang.Object. Now, you know you put a java.lang.String into that attribute, but the get method returns an Object. This is because you could have put any object in there, an Integer, a String, or some other class instance. But you know it is a String, so you can cast the returned value to a String, so that you will be calling the valueOf(java.lang.String s) method of Integer with the Object returned from the HtttpSession's getAttribute(java.lang.String name) method:
    Integer quantity = Integer.valueOf((String)session.getAttribute("vehiclequantity"));

  • Converting string number int o percentage

    Hi. I have a textfield in which it accepts numbers (2.5 or 2.35 or 32.52)
    How am I going to convert it to double and in percentage format( .0025 or .0035 or .003252)
    Thanks
    Please help

    > and just converting it back to string again. I made
    the division but converting it back to string.
    what function do i need to use?
    In Java they're called "methods".
    http://java.sun.com/developer/JDCTechTips/2004/tt1005.html#2
    http://java.sun.com/docs/books/tutorial/i18n/format/decimalFormat.html
    ~

  • Converting string to int

    I cannot convert this string to integer.
    int tempI = Integer.parseInt("fdcedfbd", 16);
    it returns a numberFormatException
    but if I do this then there will be no problem.
    int tempI = 0xfdcedfbd
    Can anybody help me with this? Thank you.

    It sounds like the real problem here is that someone is giving you an 8-byte unsigned value represented as a 16-character hexadecimal string, and they want you to convert that into the actual 8 bytes. Are they going to do bit manipulation on it or something?
    If you successfully convert it into a long and they then try to do math with it, they'll run into the sign/overflow problems everyone else has been talking about. If they just want to look at the individual bits then it would make sense to do the conversion into a long.
    You could do something like this:
      private static final String highOrderDigits = "89abcdef";
      public long hexToLong(String hex) {
        // Only process exactly 16-digit strings.
        if (hex.length() != 16) {
          throw new IllegalArgumentException("Expect 16-digit hex value");
        boolean overflow = false;
        // Check for most significant digit > 7, which would
        // cause problem for parseLong.
        int highOrderIndex = highOrderDigits.indexOf(hex.charAt(0));
        if (highOrderIndex > -1) {
          // Clear most-significant bit and set overflow flag.
          overflow = true;
          hex = "" + highOrderIndex + hex.substring(1);
        long result = Long.parseLong(hex, 16);
        if (overflow) {
          // Manually set most significant bit in result.
          result |= 0x8000000000000000L;
        return result;
      }I more or less tested this and it looks to work.

  • Trying to convert String to java.sql.Date

    I need to convert a String (in the format "yyyy-mm-dd") to java.sql.Date
    It was suggested I use the following,
    SimpleDateFormat formater = new SimpleDateFormat("yyyy-mm-dd");
    Date result = formater.parse(dbirth.getText());
    However, It seem to produce a java.util.Date
    Error: found java.util.Date
    Required : java.sql.Date
    Can anyone help?
    Thanks, Marika

    I need to convert a String (in the format
    "yyyy-mm-dd") to java.sql.Date
    It was suggested I use the following,
    SimpleDateFormat formater = new
    SimpleDateFormat("yyyy-mm-dd");
    Date result = formater.parse(dbirth.getText());
    However, It seem to produce a java.util.Date
    Error: found java.util.Date
    Required : java.sql.Date
    Can anyone help?
    Thanks, Marika SimpleDateFormat formater = new SimpleDateFormat("yyyy-mm-dd");
    java.util.Date parsedDate = formater.parse(dbirth.getText());
    java.sql.Date result = new java.sql.Date(parsedDate.getTime());

  • Combo Box, Converting string to int

    The user is able to select the month, year etc for a TimerTask using a combo box.
    The problem I have is converting say, "January" to an integer 0 for use to set in a calendar for the date.
    The combo box is populated with every month but i cannot link it with the int variable "month" where 0= january, 1- feb etc for use in the TimerTask.
    In other words, when the user selects "January" in the combo box i want the integer value for the variable "month" to equal 0, for "Febuary", month to equal 1, "March", month equal 2 etc etc.
    Any help would be excellent!!

    if January is the first item in the box, February is the second, all the way to December:
    month = monthComboBox().getSelectedIndex();

  • Converting String to int again...

    telno.addActionListener(this);
    public void actionPerformed(ActionEvent e){
    int x, p, y;
    if(e.getSource()==telno){
    x = Integer.parceInt(telno.getText());
         p = x/10000;
              y = x%10000;
    there's an error 'cannot resolve symbol' when I try to compile.
    Help please, anyone!
    Thanks

    Hi,
    parseInt() and not parceInt() I think.
    Hope it helps
    S�bastien

  • Need a little help trying to convert an array into a cluster..

    I'm having a difficulty converting the output of the AI Acquire Waveforms.vi from an array into a cluster. On my display panel I have a radial termperature gauge with two needles displaying the temperature of two different inputs. The input to this radial guage is of the cluster type, hence the need to convert.
    Any help is appreciated. Heck even if there is a better way let me know.

    The output of "AI Acquire Waveforms.vi" is an array of waveforms (waveform data type). You must first isolate the two elements of that array that correspond with the channels to which your temperature sensing devices are wired. If those are the only channels in your scan list, then the array should only be two elements in size. You can apply a shortcut if that is the case, but first the general solution.
    1) Index the array of waveforms with an Index Array function found in the Array pallette. Stretch the Index Array function so that it gives you two inputs and outputs. Wire the index of the first and second temperature channels to the bottom inputs of the Index Array function. Wire the output of "AI Acquire Waveforms.vi" to the top input of the Ind
    ex Array function. The outputs of the Index Array function are each a waveform for the corresponding channel you selected.
    2) Get the "Y" waveform component for each channel. Use the Get Waveform Components function in the Waveform pallette. It looks alot like an unbundle function. Get two of those guys and wire then to each of your outputs from the Index Array function. Select "Y" for each Waveform component.
    3) Average (or otherwise reduce) the acquired signals. The output of the "Y" component is an array of floats. You can wire that array up to an Average function to give you a scalar value. Do that for each output and now you just have two numbers.
    4) Bundle your numbers. Use the bundle function.
    5) Wire the bundle to your indicator.
    Enjoy,
    Daniel L. Press
    www.primetest.com

  • Problem converting string to int

    I want to display records of flights from my database with the things that i get from a form...One of them is the number of passengers...the code is shown below;
    " SELECT * FROM flights WHERE kalkis LIKE ? AND inis LIKE ? AND DepartureDate LIKE ? AND NumPass >= ? ";
    Everything comes up right except the NumPass value...i get the ? value by saying;
    sorgulama.setInt(4,Integer.parseInt(request.getParameter("NumPass")));
    But it won't display the values that are >=...Displays nothing...
    Also the NumPass value is "int" type in the database...
    Any idea to solve this...kinda urgent ..

    Log the parameters being used in your application.
    Run the query directly against the database using the parameters your app is using, verify you find something.

  • Help trying to convert old Apache XPath methods to J2SE5 XPath

    Previously using Apache XPath before it was part of J2SE I loaded the xml file into a DOM Document, and then had a method that could lookup by xpath
    DocumentBuildFactory  dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(false);
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document d = db.parse(new File("testfile.xml");
    node = XPathAPI.selectSingleNode(d.getDocumentElement(),xpath);
    return node;but in the J2SE, XPath only seems to work with (SAX) Input Source, I don't see why It can't be run against a DOM Document.
    XPathFactory xpf = XPathFactory.newInstance();
    XPath path = xpf.newXPath();
    XPathExpression xPathExpression = path.compile(xpath);
    return xPathExpression.evaluate(is); Could anybody clarify this for me, thanks Paul

    I don't think it's really the documentation's fault, I think it's a lazy design.
    It looks to me like you can pass a Node or a NodeList to that Object parameter, but not much else. Then why not two overloaded methods, one with a Node parameter and the other with a NodeList parameter, and both with decent documentation?

  • Converting String type to inte type

    Can any one tell me how I can convert an array of Strings into an array of integers??

    it's simple ..... it's like this...
       // some code goes here....
       String num[]={"23", "342", "21", "1"};
        int n[]= new int[num.length];
        for(int i=0; i<num.length; i++)
             n=Integer.parseInt(num[i]); // << -- convert string to int then copied it to int[]
    // rest of your code....

  • Converting from unsigned int / short to byte[]

    Can anybody help me, I am trying to convert from:
    - unsigned int to byte[]
    - unsigned short to byte[]
    I will appreciate your help lots. thanks.

    @Op.
    This code converts an integer to a byte[], but you have to consider the byte order:
            int value = 0x12345678;
            byte[] result = new byte[4];
            for (int i=3; i>=0; i--) {
                result[i] = (byte)(value & 0xff);
                value = value >> 8;
            }This is another option:
            int dummy = 7;
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            os.write(dummy);
            byte[] bytes = os.toByteArray();Kaj

  • Converting string to xml in xslt

    Hi we are trying to convert string to xml in xslt but it is getting errored out.
    We have followed the procedure mentioned at http://download.oracle.com/docs/cd/A91202_01/901_doc/appdev.901/a88894/adx04xsl.htm under the section "How Do I Convert A String to a Nodeset in XSL?".
    Standard procedure mentioned by oracle is not working. Is it a known bug?

    Chk this thread.
    Re: Regd: File Conversion to XML format

Maybe you are looking for