Int from a string??

OK, before my contacts dry out & I go blind staring at this, please point out the friging error here.
I have the same baasic code for other numeric conversions but this one does not compile, why does javac not like "Int"?
TestNumericTypes.java:122: cannot resolve symbol
symbol  : variable Int
location: class biz.TestNumericTypes
            anInt  = Int.valueOf(s).intValue();
                     ^
1 error
    public static boolean TestanInt (String s, boolean popup)
        try
            anInt  = Int.valueOf(s).intValue();
            System.out.println("TestanInt: anInt = " + anInt);      
            j = true;           
        catch (NumberFormatException nfe)
            if (popup = true)                 // display on screen
             alertuser(" (int)");
            j = false;       
           }  // end-catch
        return j;          
    } //close method
//-----------------------------------thanks,
-- HSC --

The class is called "Integer". You can look it up in
the API docs:
http://java.sun.com/j2se/1.4.1/docs/api/java/lang/packa
e-summary.html
"anInt = Integer.parseInt(s)" is considered better
style and more efficient than "anInt =
Integer.valueOf(s).intValue()", by the way.thanks for the conversion tip, and the correct class name - sometimes I need another to see silly mistakes like this.

Similar Messages

  • Extract int from a string

    Hi,
    I am curious if there is an easy way to extract an int value from a String.
    For example, "Rb23" to get 23. The length of the part in front of the integer is variable.
    Thanks

    this seems to work:
    public int extract(String s) {
         String result = "";
         char c[] = s.toCharArray();
         int j = c.length-1;
         if (!Character.isDigit(c[j])) {
              return 0;
         do {
              result+=c[j--];
         } while (j > 0 && Character.isDigit(c[j]));
         return Integer.parseInt(new StringBuffer(result).reverse().toString());
    }it will return 0 if no numbers are found at the end of the string

  • Picking an int from a string

    I have to get the user to input a name and five int's (scores for a test) using a scanner
    so it would look like this "Casey 98 96 95 84 92"
    how would I pick the integers out of that?

    This is what the assingment says
    Repeatedly (i.e. in a loop) process the input file, placing the results into the output file in a formatted way. In particular:
    Read the student name and five exam scores for that student from the input file. You may assume that each line of the file starts with a String representing the student's (last) name, followed by whitespace followed by the five exam scores, each separated by whitespace. Your program does not have to handle the case where there are fewer that six items in the line or the case where the information in the line is not in the order specified.
    Does that change anything?

  • How to substract an int from a String?

    Hi,
    Here is my problem,
    I have to substract 4 integers out of a single string (in a single input using the JOptionPane.showInputDialog)
    these 4 integers are seberated by spaces (any number of spaces)
    I have to sign each number to an int variable
    also I have to multiply these 4 integers with doubles to get a final double variable result
    I need urgent help please
    (hint: it's about string manuplation)
    Thanks

    Hi,
    Here is my problem,
    I have to substract 4 integers out of a single string
    (in a single input using the
    JOptionPane.showInputDialog)
    these 4 integers are seberated by spaces (any number
    r of spaces)
    I have to sign each number to an int variable
    also I have to multiply these 4 integers with doubles
    to get a final double variable result I have no idea what you're asking. Can you clarify? Maybe provide some sample input and what the output will be.
    I need urgent help please I promise you, nobody here cares about your urgency, and mentioning it is guaranteed NOT to get you help any faster. If it has any effect at all, it will be the opposite--some people might decide to delay or skip answering your question simply out of irritation at you mentioning your urgency.
    (hint: it's about string manuplation)Yeah. We got that, thanks.

  • Reading an int from a particular location in a file

    Hi, I've seen other topics about reading ints from files/strings etc, but I don't think I've found one the same as this.
    I have an input file "maxSolution.sol" that contains an int that I need to use in my program
    c Parsing PB file...
    c Converting 0 PB-constraints to clauses...
    c -- Unit propagations: (none)
    c -- Detecting intervals from adjacent constraints: (none)
    c -- Clauses(.)/Splits(s): (none)
    c ==================================[MINISAT+]==================================
    c | Conflicts | Original | Learnt | Progress |
    c | | Clauses Literals | Max Clauses Literals LPC | |
    c ==============================================================================
    c | 0 | 0 0 | 0 0 0 nan | 0.000 % |
    c ==============================================================================
    c Found solution: -1
    c Optimal solution: -1
    s OPTIMUM FOUND
    v x0001 -x0101 -x0200 -x0201 -x0800
    c _______________________________________________________________________________
    c
    c restarts : 1
    c conflicts : 0 (nan /sec)
    c decisions : 2 (inf /sec)
    c propagations : 0 (nan /sec)
    c inspects : 0 (nan /sec)
    c CPU time : 0 s
    c _______________________________________________________________________________
    The int that I require is the one that appears after "Optimal Solution: ". I actually require the absolute value of this, so I have tried the following
    public int maxInputReader(String s) throws IOException
    String optimal = "Optimal Solution:";
    int mines = 0;
    File input = new File(s);
    Scanner filein = new Scanner(input);
    while(filein.hasNext())
    if(filein.next() == optimal)
    mines = Math.abs(Integer.parseInt(filein.next()));
    return mines;
    However, when I run this method, it returns 0, the initial value for the int mines, could anyone give me a hand as to what I am doing wrong?

    much better:
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.nio.ByteBuffer;
    import java.nio.CharBuffer;
    import java.nio.channels.FileChannel;
    import java.nio.charset.Charset;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    public class RegExpTest {
         public RegExpTest(){
              try {
                 // Create matcher on file
                 Pattern pattern = Pattern.compile("Optimal solution:\\s*(\\-)\\d");
                 Matcher matcher = pattern.matcher(fromFile("your_file_path_here.txt"));
                 // Find all matches
                 while (matcher.find()) {
                     // Get the matching string
                     String match = matcher.group();
                     System.out.println("Line : "+match);
                     int i = Integer.parseInt(match.substring(match.indexOf(':')+1).trim());
                     System.out.println("Number: "+i);
             } catch (IOException e) {
                  e.printStackTrace();
         //Converts the contents of a file into a CharSequence
        // suitable for use by the regex package.
        public CharSequence fromFile(String filename) throws IOException {
            FileInputStream fis = new FileInputStream(filename);
            FileChannel fc = fis.getChannel();
            // Create a read-only CharBuffer on the file
            ByteBuffer bbuf = fc.map(FileChannel.MapMode.READ_ONLY, 0, (int)fc.size());
            CharBuffer cbuf = Charset.forName("8859_1").newDecoder().decode(bbuf);
            return cbuf;
        public static void main(String[] args) {
              new RegExpTest();
    }

  • Dynamic Variable name (for int/long) from a String variable

    Hi,
    I want to give a int/long variable name from a String.
    for ex.
    String str = lookup + "Id";
    lookup is a String variable coming from XML. Now, for instance lookup="name". So str = "nameId".
    Now I want to create a int/long variable by nameId.
    Could anybody tell me the way how to do. Please don't tell to use MAP.
    Edited by: Shah on Dec 5, 2007 3:26 PM

    Well you can't. Use a Map.
    The compiler translates variable names into slot numbers, either within an object or withing the local "stack frame" and these slot numbers are assigned names at compile time. No new slots can be created at run time. Java is not Basic.
    Reflection allows you to find existing field names and methods (not local variables), so it's possible to map, for example, XML attribute names to field names or setters in an object but the names have to be known at compile time.

  • How can i store values from my String into Array

    Hi guys
    i wants to store all the values from my string into an array,,,, after converting them into intergers,,,, how i can do this becs i have a peice of code which just give me a value of a character at time,,,,charat(2)...BUT i want to the values from String to store in an Array
    here is my peice of code which i m using for 1 char at time
    int[] ExampleArray2 = new int[24];
    String tempci = "Battle of Midway";
    for(int i=0;i>=tempci.length();i++)
    int ascii = tempci.charAt(i); //Get ascii value for the first character.

    public class d1
         public static final void main( String args[] )
              int[] ExampleArray2 = new int[24];
              String tempci = "Battle of Midway";
              for(int i=0;i<tempci.length();i++)
                   int ascii = tempci.charAt(i);
                   ExampleArray2=ascii;
              for(int i=0;i<ExampleArray2.length;i++)
                   System.out.println(ExampleArray2[i]);

  • How to get the Values i need from a String???

    hi i need some help on my program,
    I have a Server that actually sent some data to my Client.
    The data consist of some messages and intergers . The whole piece of data is stores as a String message.
    ARRAY 'Monitor Chart' 2 5
    'Total OverFlow' 'Queued' 'Completed' 'Host Resets' 'Errors'''
    0.0 1.0 2.0 3.0 4.0
    'Series1' 11.0 0.6 8.6 11.5 6.6
    'Series2' 12.8 6.7 21.6 11.1 30.0Inside the Client i need to get the values out to showed on my textfields
    Example :
    Tf1 = 11.0
    Tf2 = 0.6
    Tf3 = 8.6
    Tf4 = 11.5
    Tf5 = 6.6
    Question: How to i get the values out from the String???

    using the split() method. i am able to split everything now
    so it appear somthing like this :
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    public class testing{
         String d1 =     "ARRAY 'Monitor Chart' 1 5";
         String d2 = "'Total OverFlow' 'Queued' 'Completed' 'Host Resets' 'Errors'";
         String d3 = "'' 0.0 1.0 2.0 3.0 4.0 ";
         String d4 = "'Series1' 11.0 0.6 8.6 11.5 6.6 ";
         String d5 = "'Series2' 12.8 6.7 21.6 11.1 30.0 ";
         String data = d1 + d2 + d3 + d4 + d5;     
         public testing(){
              System.out.println(data);
              String[] result = data.split("\\s");
              for(int x=0;x<result.length;x++)
              System.out.println(result[x]);
         public static void main (String args[])throws IOException{
            testing Application = new testing();
    }ARRAY
    'Monitor
    Chart'
    2
    5
    'Total OverFlow'
    'Queued'
    'Completed'
    'Host Resets'
    'Errors'''
    0.0
    1.0
    2.0
    3.0
    4.0
    'Series1'
    11.0
    0.6
    8.6
    11.5
    6.6
    'Series2'
    12.8
    6.7
    21.6
    11.1
    30.0
    but how do i get the values out ??how do i noe it is which index or wad?
    11.0
    0.6
    8.6
    11.5
    6.6

  • How do I make a Datagram Packet from a String?

    I am looking to make a Datagram Packet from a string. If I send a command to a server that allows remote connections via UDP, such as "restart" it will restart the server. I can accomplish this easily through the fput() method of PHP.
    I want a Java version of my utility, and am using the DatagramSocket and DatagramPacket classes. I see that I need to make a byte array and put it inside a DatagramPacket. How would I go about putting the string "restart" into a byte array?
    Thanks,

    Use the following code to send a Datagram:-
    import java.io.*;
    import java.net.*;
    // This class sends the specified text as a datagram to port 6010 of the
    // specified host.
    public class UDPSend {
        static final int port = 6010;
        public static void main(String args[]) throws Exception {
            if (args.length != 2) {
                System.out.println("Usage: java UDPSend <hostname> <message>");
                System.exit(0);
            // Get the internet address of the specified host
            InetAddress address = InetAddress.getByName(args[0]);
            // Convert the message to an array of bytes
            int msglen = args[1].length();
            byte[] message = new byte[msglen];
            args[1].getBytes(0, msglen, message, 0);
            // Initilize the packet with data and address
            DatagramPacket packet = new DatagramPacket(message, msglen,
                                   address, port);
            // Create a socket, and send the packet through it.
            DatagramSocket socket = new DatagramSocket();
            socket.send(packet);
    }This uses argments, if you want a string change the code accordingly.

  • Error "Conversion failed when converting date and/or time from character string" to execute one query in sql 2008 r2, run ok in 2005.

    I have  a table-valued function that run in sql 2005 and when try to execute in sql 2008 r2, return the next "Conversion failed when converting date and/or time from character string".
    USE [Runtime]
    GO
    /****** Object:  UserDefinedFunction [dbo].[f_Pinto_Graf_P_Opt]    Script Date: 06/11/2013 08:47:47 ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE   FUNCTION [dbo].[f_Pinto_Graf_P_Opt] (@fechaInicio datetime, @fechaFin datetime)  
    -- Declaramos la tabla "@Produc_Opt" que será devuelta por la funcion
    RETURNS @Produc_Opt table ( Hora datetime,NSACOS int, NSACOS_opt int)
    AS  
    BEGIN 
    -- Crea el Cursor
    DECLARE cursorHora CURSOR
    READ_ONLY
    FOR SELECT DateTime, Value FROM f_PP_Graficas ('Pinto_CON_SACOS',@fechaInicio, @fechaFin,'Pinto_PRODUCTO')
    -- Declaracion de variables locales
    DECLARE @produc_opt_hora int
    DECLARE @produc_opt_parc int
    DECLARE @nsacos int
    DECLARE @time_parc datetime
    -- Inicializamos VARIABLES
    SET @produc_opt_hora = (SELECT * FROM f_Valor (@fechaFin,'Pinto_PRODUC_OPT'))
    -- Abre y se crea el conjunto del cursor
    OPEN cursorHora
    -- Comenzamos los calculos 
    FETCH NEXT FROM cursorHora INTO @time_parc,@nsacos
    /************  BUCLE WHILE QUE SE VA A MOVER A TRAVES DEL CURSOR  ************/
    WHILE (@@fetch_status <> -1)
    BEGIN
    IF (@@fetch_status = -2)
    BEGIN
    -- Terminamos la ejecucion 
    BREAK
    END
    -- REALIZAMOS CÁLCULOS
    SET @produc_opt_parc = (SELECT dbo.f_P_Opt_Parc (@fechaInicio,@time_parc,@produc_opt_hora))
    -- INSERTAMOS VALORES EN LA TABLA
    INSERT @Produc_Opt VALUES (@time_parc,@nsacos, @produc_opt_parc)
    -- Avanzamos el cursor
    FETCH NEXT FROM cursorHora INTO @time_parc,@nsacos
    END
    /************  FIN DEL BUCLE QUE SE MUEVE A TRAVES DEL CURSOR  ***************/
    -- Cerramos el cursor
    CLOSE cursorHora
    -- Liberamos  los cursores
    DEALLOCATE cursorHora
    RETURN 
    END

    You can search the forums for that error message and find previous discussions - they all boil down to the same problem.  Somewhere in your query that calls this function, the code invoked implicitly converts from string to date/datetime.  In general,
    this works in any version of sql server if the runtime settings are correct for the format of the string data.  The fact that it works in one server and not in another server suggests that the query executes with different settings - and I'll assume for
    the moment that the format of the data involved in this conversion is consistent within the database/resultset and consistent between the 2 servers. 
    I suggest you read Tibor's guide to the datetime datatype (via the link to his site below) first - then go find the actual code that performs this conversion.  It may not be in the function you posted, since that function also executes other functions. 
    You also did not post the query that calls this function, so this function may not, in fact, be the source of the problem at all. 
    Tibor's site

  • Create Business Partner from XMl String not a file

    Hi,
    Is it possible to create a BP from an XML string. 
    I know about GetBusinessPartnerFromXml(string FileName, int index)
    but I dont want to save the string in a file before creating a BP from it
    Hope there's a method to do that

    Marc,
    This looks like it is a duplicate of this post, so I am closing this thread as it looks like you answered your own question!
    Create Business Partner from XMl String not a file
    Eddy

  • How to remove HTML tags from a String ?

    Hello,
    How can I remove all HTML Tags from a String ?
    Would you please to give me a simple example ?
    Best regards,
    Eric

    Here's some code I cooked up. I have created an object that processes code so that it can be incorporated directly into a project. There is some redundancy so that the it can be used in more than one way. Depending on your situation you might have to make the condition statement a little more sophisticated to catch stray ">" tags.
    I have also included a Tester application.
    //This removes Html tags from a String either by submitting the String during construction and then
    // calling getProcessedString() or
    // by simply calling " stringwithoutTags=removeHtmlTags(stringWithTagsSubmission); "
    //Note: This code assumes that all"<" tags are accompanied by a ">" tag in the proper order.
    public class HtmlTagRemover
         private String stringSubmission,processedString,stringBeingProcessed;
         private int indexOfTagStart,indexOfTagEnd;
         public HtmlTagRemover()
         public HtmlTagRemover(String s)
              removeHtmlTags(s);          
         public String removeHtmlTags(String s)
              stringSubmission=s;
              stringBeingProcessed=stringSubmission;
              removeNextTag();
              return processedString;
         private void removeNextTag()
              checkForNextTag();
              while((!(indexOfTagStart==-1||indexOfTagEnd==-1))&<indexOfTagEnd)
                   removeTag();
                   checkForNextTag();
              processedString=stringBeingProcessed;
         private void checkForNextTag()
              indexOfTagStart=stringBeingProcessed.indexOf("<");
              indexOfTagEnd=stringBeingProcessed.indexOf(">");
         private void removeTag()
              StringBuffer sb=new StringBuffer("");
              sb.append(stringBeingProcessed);
              sb.delete(indexOfTagStart,indexOfTagEnd+1);
              stringBeingProcessed=sb.toString();
         public String getProcessedString()
              return processedString;
         public String getLastStringSubmission()
              return stringSubmission;
    public class HtmlRemovalTester
         static void main(String[] args)
              String output;
              HtmlTagRemover h=new HtmlTagRemover();
              output="The processed String: "+h.removeHtmlTags("<Html tag>This is a test<another Html tag> string<yet another Html tag>.");
              output=output+"\n"+" The original string:"+h.getLastStringSubmission();
              System.out.print(output);

  • Parseing a Float from a string.

    Does anyone know how to parse a float from a string variable? The documentation says there is a method for it, it doesn't say what it is(?).
    I.e. the equavilent of int this_num.parseint(this_string) only for a float.
    Thanks.

    Thanks, that helped...now for another apparently stupid question....
    How do you add two floats??
    I have:
    fInvAmount = fInvAmount + Float.parseFloat(rsSmartStreamInvoice.getString("invoice_amt"))
    and it tells me that 'operator + cannot be applied to java.lang.Float,float'

  • Geting a variable from a String

    Hi, i need to get a variable from a string. For example:
    int test1;
    int test2;
    int test3;
    int test = getvariablefromstring("test"+3);
    ..................

    Reflection will work for member variables, not locals. It'sprobably not the right solution for you though.
    If you just want test1, test2, test3, ... testN, then you want an array or a List.
    http://java.sun.com/docs/books/tutorial/java/nutsandbolts/arrays.html
    http://java.sun.com/docs/books/tutorial/collections/

  • Remove $%&* characters from a String

    Hi,
    I have the following program that is supposed to detect a subsequence from a String (that contains $ signs) and remove it. This is a bit tricky, since because of $ signs, the replaceAll method for String does not work. When I use replaceAll for removing the part of the String w/ no $ signs, replaceAll works perfectly, but my code needs to cover the $ signs as well.
    So far, except for replaceAll, I have tried the following, with the intent to first remove $ signs from only that specific sequence in the String (in this case from $d $e $f) and then remove the remaining, which is d e f.
    If anyone has any idea on this, I would greatly appreciate it!
    Looking forward to your help!
    public class StringDivider {
         public static void main(String [] args)
              String symbols = "$a $b $c $d $e $f $g $h $i $j $k l m n o p";
             String removeSymbols = "$d $e $f";
             int startIndex = symbols.indexOf(removeSymbols);
             int endIndex = startIndex + removeSymbols.length()-1;
             for(int i=startIndex;i<endIndex+1;i++)
                  if(symbols.charAt(i)=='$')
                       //not sure what to do here, I tried using replace(oldChar, newChar), but I couldn't achieve my point, which is to
                       //delete $ signs from the specific sequence only (as opposed to all the $ signs)
             System.out.println(symbols);
    }

    A little modification on the last version:
    This one's more accurate.
    public class StringDivider {
         public static void main(String [] args){
              String symbols = "$a $b $c $d $e $f $g $h $i $j $k l m n o p";
                  String removeSymbols = "$d $e $f $g";
                  if(symbols.indexOf(removeSymbols)!=-1)
                       if(removeSymbols.indexOf("$")!=-1)
                            removeSymbols = removeSymbols.replace('$', ' ').trim();
                            removeSymbols = removeSymbols.replaceAll("[ ]+", " ");
                            String [] symbolsWithoutSpecialChars = removeSymbols.split(" ");
                            for(int i=0;i<symbolsWithoutSpecialChars.length;i++)
                                 symbols = symbols.replaceAll("[\\$]*"+symbolsWithoutSpecialChars, "");
                             symbols = symbols.replaceAll("[ ]+", " ");
                   else
                        symbols = symbols.replaceAll(removeSymbols, "");
              symbols = symbols.trim();
              System.out.println(symbols);

Maybe you are looking for

  • Unable to launch web start application

    Hi Please can any one help me. I have a problem in launching the web start application. As i am the beginner i need help from you people. I have created three class files as below. Aeon_PManager.java SimpleSerial.java SimpleSerialNative.java. We have

  • Problem with DimensionBuilder (Business Objects Financial Consolidation)

    Description of Problem or Question: Hi all, i try to create a new Dimension as described in the help by switching into "Definition Mode" of the Dimensionbuilder. In "data sources" I select the "amounts" folder and Select File -> New -> Dimension. Unf

  • Move ABAP code from Z-namespace to other namespace

    Hello, I wonder how one can move custom ABAP code that was created in the Z-namespace to a NEW namespace, that was just created upon a confirmed "request namespace". The Z-namespace ABAP code is developed to work in SAP ERP. I have learned that you n

  • [JOB] 2 F/T Flex Roles in NYC to 175k (Financial Services)

    Full details here: http://wp.me/pTfw1-4X

  • Creating new website

    hi guys, i have a wesite that has been operational for a few years which is hosted (http://www.angliaclipperservices.com/) and ranks fairly well for all my keywords this has obviously taken a bit of work, i have since been designing my own website to