Read integers from Strings

Hi,
I'm trying to make a program that scans a String for integers and then counts the integers,
for example:
the String s: lahd123kgfkg898 has two numbers, 123 and 898.
Does anyone have an idea?

It reminds me when I was a kid and asked my mother
what a word meant. She'd tell me to look it up in the
dictionary.omg, you just brought up my greatest pet peeve.
i was raised to be curious and to find my answers in dictionaries,
encyclopedias and book indices.
id take a wild guess that 50% of americans dont know what an
index is or when to use it. it is absolutely infuriating.
sigh... not that it matters. in 10 years everything will be online.

Similar Messages

  • Reading integers from file problem...

    I managed to read integers from a file but only the ones from the first line. I can't somehow read the remaining lines.
    The format is...
    33 212 3111 12 1
    1
    123
    2 3 4
    I know that the first while loop pretty much does nothing...
    Any help is appreciated :)
    import java.util.*;
    import java.io.*;
    public class TokenTest {
          public static void main(String[] args) throws Exception {
                BufferedReader in = new BufferedReader(new FileReader("numbers.txt"));
                String line = in.readLine();
                StringTokenizer st = new StringTokenizer(line);
                while (in.readLine() != null) {
                      while (st.hasMoreTokens()) {
                            String s = st.nextToken();
                            int j = Integer.parseInt(s);
                            System.out.print(j + " ");
    }

    Ok i kind of done it. For the input...
    0 56 3
    23 6 10 12
    3 2 4
    1
    It returns 23 6 10 12 3 2 4 1. Basically all the numbers except for the first line.
    import java.util.*;
    import java.io.*;
    public class TokenTest {
          public static void main(String[] args) throws Exception {
                BufferedReader in = new BufferedReader(new FileReader("numbers.txt"));
                String line = in.readLine();
                while ((line = in.readLine()) != null) {
                      StringTokenizer st = new StringTokenizer(line);
                      while (st.hasMoreTokens()) {
                            String s = st.nextToken();
                            int j = Integer.parseInt(s);
                            System.out.print(j + " ");
    }

  • Reading integers from a .txt file and computing means

    I have a program that uses for loops to produce ten integers (1-10) are returns the average mean, geometric mean, and harmonic mean.
    Now i need to change this program to read integers from a .txt file and return the same data. Basically i need to change my for statements that are incrementing to read the text file.
    Thanks guys.

    You haven't asked a question. You haven't posted code. What are you expecting here?
    But I guess I'll take a stab at it and say you should look at the Scanner class
    http://java.sun.com/javase/6/docs/api/java/util/Scanner.html
    or BufferedReader
    http://java.sun.com/javase/6/docs/api/java/io/BufferedReader.html
    I'll never understand what makes people come to the forums, create an account, and ask a lazy question, when they could get a great answer much quicker through Google.
    http://www.google.com/search?q=java+file+input (hint: look at the second search result)

  • Reading integers from keyboard

    Hi,
    To my understanding,always we have to use the BufferedReader along with the InputStream reader to read the stream(here the stream is the keyboard).
    Now this will be a string input taken from it.To make it an integer,we have to use the Integer.parseInt() method thus it is integer.
    Is this the right method to read integers.Or is there someother method.Any help would
    Thanks
    AS

    Merriam Webster:
    Main Entry: doubt
    Function: noun
    1 a : uncertainty of belief or opinion that often interferes with decision-making b : a deliberate suspension of judgment
    2 : a state of affairs giving rise to uncertainty, hesitation, or suspense
    3 a : a lack of confidence : DISTRUST b : an inclination not to believe or accept

  • Problem in reading integers data

    hi all,
    i'm reading integers from console and storing them in a file and then reading back, but my data is inconsistent.can anybody tell me the reason for this.
    heres my code snippet...
    DataInputStream in = new DataInputStream(System.in);
              DataOutputStream out = new DataOutputStream(new FileOutputStream("intdata.txt"));
              try{
                   int a = in.readInt();
                   out.writeInt(a);
                   out.close();
                   in.close();
              }catch(EOFException eofe){
                   throw new RuntimeException(eofe);
              DataInputStream in2 = new DataInputStream(new FileInputStream("intdata.txt"));
              System.out.println(in2.readInt());
              in2.close();

    The whole problem here is in that last phrase "a readInt() function which should function exactly as i'm expecting." What it actually does do in the posted code is sit there doing nothing, or rather it waits for more input. It's doing exactly what its API documentation says it will do.
    But you say it "should function exactly as i'm expecting." Now unless you pay Sun a very, very big sum of money DataInputStreams are going to go on behaving as documented in the API. That isn't going to change. You had better change what you are expecting.
    If you throw a String like "58" at a DataInputStream readInt() will not produce 58. (And nowhere in the documentation of the class does it suggest it will.) What it will do - and I've tried this - is sit there and do nothing. This was sort of what Ceci was getting at by "Broken As Designed". It's not that DIS is broken, after in2 (see below) works fine. But using it to read keyboard input is a Bad Thing.
    Having changed what we expect, we need to rethink that "apart from parseInt" bit. We need a plan B, and here it is. We are reading a string (a bunch of characters such as people produce when they hammer a keyboard) - so we'll use a Reader. We want an entire line, so we'll make it a BufferedReader and use its readline() method. And we want to obtain an int from that string, which pretty much suggests ... parseInt().
    At any rate, that's my suggestion! Something along the lines of:import java.io.BufferedReader;
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.EOFException;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.InputStreamReader;
    public class Test {
        public static void main(String[] args) throws Exception {
            //DataInputStream in = new DataInputStream(System.in);
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            DataOutputStream out = new DataOutputStream(new FileOutputStream("intdata.txt"));
            try{
                //int a = in.readInt();
                int a = Integer.parseInt(in.readLine());
                     * Add this line to see what int the DataInputStream
                     * is creating based on your "85"
                System.out.println("The number I typed in was " + a);
                out.writeInt(a);
                out.close();
                 //in.close();
            } catch(EOFException eofe) {
                throw new RuntimeException(eofe);
            DataInputStream in2 = new DataInputStream(new FileInputStream("intdata.txt"));
            System.out.println(in2.readInt());
            in2.close();
    }Which results in58
    The number I typed in was 58
    58

  • Reading strings and integers from a text file

    I want to read the contents of a text file and print them to screen, but am having problems reading integers. The file contains employee's personal info and basically looks like this:
    Warren Laing
    32 //age, data type is int
    M //gender, data type is String
    Sharon Smith
    44
    F
    Here's what I've done so far. The method should continue reading the file until there's no lines left. When I call it from main, I get a numberFormatException error. I'm not sure why because the data types of the set and get methods are correct, the right packages have been imported, and I'm sure I've used Integer.parseInt() correctly (if not, pls let me know). Can anyone suggest why I'm getting errors, or where my code is going wrong?
    many thanks
    Chris
    public void readFile() throws IOException{
    BufferedReader read = new BufferedReader(new FileReader("personal.txt"));
    int age = 0;
    String input = "";
    input = read.readLine();
    while (input != null){
    setName(input);
    age = Integer.parseInt(input);
    setAge(age);
    input = read.readLine();
    setGender(input);
    System.out.println("Name: " + getName() + " Age: " + getAge() + " Gender: " + getGender());
    read.close();

    To answer your question - I'm teaching myself java and I haven't covered enumeration classes yet.
    With the setGender("Q") scenario, the data in the text file has already been validated by other methods before being written to the file. Anyway I worked out my problems were caused by "input = read.readLine()" being in the wrong places. The code below works fine though I've left out the set and get methods for the time being.
    Chris
    public static void readFile()throws IOException{
    String name = "";
    String gender = "";
    int age = 0;
    BufferedReader read = new BufferedReader(new FileReader("myfile.txt"));
    String input = read.readLine();
    while(input != null){
    name = input;
    input = read.readLine();
    gender = input;
    input = read.readLine();
    age = Integer.parseInt(input);
    input = read.readLine();
    System.out.println("Name: " + name + " Gender: " + gender + " Age: " + age);
    read.close();

  • Reading 16 & 22 bit signed integers using Scan From String

    Last week it was suggested to use Scan from String which is a new tool for me and worked well to be able to read in ans parse strings.
    After parsing the string, I'm having trouble converting the numbers into signed integers. The magnitude of some of the the outputs are unreasonably high then flip to near 0 then back up again.
    Sample String (With spaces added)
    $ 00 FCCE 00F6 3FFA93 0BFE 0C89 0DDB
    Message Format:
    Bytes 3-6 FCCE Heave acceleration bits 15-0 15-bit data, sign extended to 16 bits LSB : 0.001261g Sign “+” when accelerating upward
    Bytes 11-16 3FFA93 FOG Gyro 1 bits 21-0 Bits 22-23 are always zero 22-bit signed data LSB = 97.275 µ˚/s Sign corresponds to MEMS axis
    Sample Data File:
    $00FCCE00F13FFD78100910A811FA
    $00FCDF00F13FFCD3141614C71619
    $00FCD600F33FFD20182118E61A39
    $00FCDA00F73FFB3E1C2D1D051E58
    $00FCDD00F73FFC32203921242278
    $00FCDD00EF3FFDDC244525442697
    The vi and a longer sample data file are uploaded to the ni ftp site. The zip file is named: IMU (9-15-08).zip. (Can't attach files to this message for some reason)
    Any help appreciated.
    Thanks,
    Chris

    Files uploaded to the "incoming" directory cannot be downloaded. That folder is intended to be used for submitting code to NI to investigate bugs and such things, not for forum posts.
    What are you expecting FCCE to be? If the string is made of the characters "F", followed by the character "C", etc. (as opposed to the hex value of F, followed by the hex value of C, etc), then you can simply use Hexadecimal String to Number. Otherwise you need to use Type Cast.
    Attachments:
    Example_VI.png ‏5 KB

  • Reading in integers from a text file

    Hi, I am going to go for the 'reading in from a text file' action as I haven't done this before. So I have been looking at all the examples and am trying the one out below :) My question is that though the structure seems pretty straightforward, what is the action of the 'token' and why doesn't java recognise it as it is used in many different examples that I have seen?
    public static int[] getIntegersFromFile(String fileName) throws IOException {
                   StringWriter writer = new StringWriter();
                   BufferedReader reader = new BufferedReader(new FileReader(fileName));
                   List<Integer> list = new ArrayList<Integer>();
                   for (String line = reader.readLine(); line != null; line = reader.readLine()) {
                   writer.write(line + " ");
                   StringTokenizer tokens = new StringTokenizer(writertoString());
                   while (tokens.hasMoreTokens()) {
                        String str = tokens.nextToken();
                        try {
                             list.add(new Integer(str));
                             } catch (NumberFormatException e) {
                                  System.out.println("Error '" + str + "' is not an integer.");
                   int[] array = new int[list.size()];
                        for( int i = 0; i < array.length; i++){
                        array[i] = list.get(i);
                   return array;
         }

    Hey, first of all, a piece of advice, try formatting your codes you make easier
    to understand for the people who help you. You can check out the
    formatting tips
    Now, A think that could help you a lot, is the next link, seek out the
    documentation for the StringTokenizer class
    http://java.sun.com/j2se/1.5.0/docs/api/
    Here your code formated and later my interpretation of your question.
    public static int[] getIntegersFromFile(String fileName) throws IOException {
       StringWriter writer = new StringWriter();
       BufferedReader reader = new BufferedReader(new FileReader(fileName));
       List<Integer> list = new ArrayList<Integer>();
       for (String line = reader.readLine(); line != null; line = reader.readLine()) {
          writer.write(line + " ");
       StringTokenizer tokens = new StringTokenizer(writertoString());
       while (tokens.hasMoreTokens()) {
          String str = tokens.nextToken();
          try {
             list.add(new Integer(str));
          } catch (NumberFormatException e) {
             System.out.println("Error '" + str + "' is not an integer.");
       int[] array = new int[list.size()];
       for( int i = 0; i < array.length; i++){
          array = list.get(i);
       return array;
    }StringTokenizer separates the string contained by the space character, and
    each piece of the separated string is stored into the token.
    Further on, could you extend your question about "why doesn't Java
    recognize what?" please, because I don't know if you have a problem
    iterating or is just that it doesn't compile or what.
    Expecting your answer, to complete mine, cya around.
    -Best Regards.

  • Reading parameters from Query string : Sender SOAP adapter.

    Hello Experts,
    I have a SOAP to SOAP scenario. Here we will have multiple receivers and dynamic receiver determination is needed.
    The sender will send a Value in Query string of URL to sender SOAP adapter. This value in Query string parameter will decide the receiver at runtime.
    I need to know, how can we read values from Query string of incoming call? I did tried to search blogs & forum threads but unfortunately not able to hit the right links.
    Any inputs will be of great help.
    Should i use "Use Query String" on sender soap channel? I tried it, but i was not able to find any query string parameters in SOAP header or payload.
    Please guide me, its bit urgent.
    Regards,
    Abhi.

    > But the argument provided from their side is: They are using standard XSD and this service is provided out of box with sender application.
    If they can add a URL parameter, they can also add a field to the structure.
    > They cant control the value mapping of parameters in payload to the extent required to implement this change.
    Adding a new field to the structure would not affect any existing mapping.
    > Since they have this custom requirement of multiple receivers & receiver to be determined at runtime, they need to go for Query string.
    This can be done based on any field of the payload.
    > I need to find a way to read the query string in any case.
    This is not supported by SOAP adapter.
    > Can I use one of the header parameters to be mapped to this value  (By selecting "Use Query string" & "Keep Headers" flag in sender CC) & then extract this value from header using Dynamic configuration ?
    This feature works only for XI header fields, like message ID or QoS.
    Not for individual parameters.

  • How do I avoid Error 85 in Scan From String scanning VISA read buffer?

    I have encountered an Error 85 with my Scan From String VI. I have a timed
    loop to read data from a device (flowmeter) using a serial port. This device takes
    periodic measurements and sends the reading which contains a numerical value to the serial port COM1. It cannot be read continuously, and the period
    between measurements may vary, so I decided a timed loop would be better than a while loop.
    The VI begins with VISA Configure Serial Port and then
    goes to a VISA Write which sends the message to the device to begin
    taking measurements. After this, the device usually says "TAKE FLOWMETER READINGS" to the terminal, thereafter only sending numbers. Then begins my timed loop containing VISA Read. I
    am taking the read buffer two places.
    First, I am taking it to an Array to Spreadsheet String with the
    Format String %.3f, as was in the Write to Text File example. Then I am
    using Concatenate Strings with this string and also a string containing
    the System Time. This string goes to Write to Text File, which I have
    configured using Open/Create/Replace File outside of the loop.
    Second, I am taking the read buffer to a waveform chart. I thought
    it would be a good idea to use Scan From String to convert the string
    into a DBL which I am then sending to the waveform
    chart.
    I am not sure if the initial "TAKE READINGS" message is giving me an error. I was able to get one reading saved to my text file from the device.
    Also the format string for my Scan From String is %.3f
    I am getting the Error 85 at the Scan From String only sometimes.
    When this happens, there is no data being written to the text file. But
    other times, I get data and it writes to the text file just fine (but
    rounds to nearest whole number).
    Any help would be greatly appreciated! This serial port device has been giving me a lot of trouble.

    Is this what you mean? Did I wire the shift registers correctly?
    I didn't know if you meant to Concatenate before Scan From String or Concantenate before or after VISA Read?
    Message Edited by YeungJohn on 11-20-2008 03:48 PM
    Message Edited by YeungJohn on 11-20-2008 03:49 PM
    Attachments:
    SerialShiftVI.JPG ‏87 KB

  • Reading Hex data- how to typecast from string

    Hi,
    I am reading a file having hex data ( say 100 lines).When i read it i think it is being read as a string.
    How can i typecast or convert it to int .
    I am using dis.readLine() to read from file and assigning it to a variable(int).
    Thanks.
    Edited by: Motorcycle on Jun 10, 2009 3:16 PM

    Sorry for that..:)
    ok a few lines of the file are as folloes
    0x004D1202
    0x0002E1E5
    0x004C1202
    0x0002E1EB
    0x004E1202
    I tried reading it as data [indr][indc].tag = ( int ) dis.readLine() ;
    It said " cannot convert from String to int.
    data is a structure having int variables.
    Thanks.

  • How can I convert/read out from a string Hex (8-bit), the bit 0 length 1

    How can I convert/read out from Hex (8-bit), the bit 0 length 1 (string subset!!??) and convert it to decimal.
    With respect to one complement and two complement ?

    Just like Jeff, purely guessing here.
    It almost sounds like you just need to Read from Binary File?
    AND the 8-bit number with 1?
    Need more details.  What exactly do you have to start with?  What exactly are you trying to get out of it?  Examples help.
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines

  • Read text from a string control in a compiled LabView executable from C#

    I have a third party complied LabVIEW executable and no source code.  I need to read values from the front panel in C#.  I know that LabVIEW controls and indicators are not actual windows.  Is there a way to programmatically access this information(i.e. without using screenshots and OCR)?  I couldn't find this exact question answered in this forum.  I've read a few things about VI Server doing this from LabVIEW, but I don't think you can access VI Server from C#.  Any help would be appreciated.
    Thanks in advance.

    You should certainly be able to access VI Server from C#. LabVIEW has an ActiveX server built in that allows other applications to access a sizeable subset of VI Server functionality. I would guess you could access ActiveX servers directly from C#, but the worst-case scenario would be to wrap the ActiveX calls into a .NET assembly. I've seen this done before. This blog entry is slightly off topic, but might help you.
    Actually, I do need to revise this answer... If you are working with a LabVIEW DLL, the DLL would have to be compiled with the ActiveX Server option enabled. Otherwise, LabVIEW won't include the code that allows the DLL to be hooked into using this method. So if you don't have the source and you can't recompile it, you might be out of luck. Does the DLL really not have a function that exports this string value?
    Message Edited by Jarrod S. on 10-26-2006 01:39 PM
    Jarrod S.
    National Instruments

  • Problem in reading data from Excel sheet to 2D string array (ActiveX & LabView).

    I am trying to read data from Excel sheet to 2D string array (ActiveX & LabView). Error -2147352571 is generated (type mismatch) if cell value is "#NULL!", "#N/A" etc. What should I do?

    Hello �
    Is the error happening when the cell value is #NULL or #NA only?
    Sometimes these errors occur because of an ActiveX object mismatch. The version of the ActiveX object might have changed or been updated since the VI was created. The VI tries to use an earlier, incompatible version of the ActiveX object.
    To solve the problem, you need to link automation refnum terminal to the correct ActiveX object. To do so, right-click an automation refnum terminal and choose Select ActiveX Class»Browse from the shortcut menu. From the Type Library pull-down menu, select the latest version of the library you want to use, such as Microsoft Excel Object Library. In the Objects list, select an ActiveX object, and click the OK button. Link ea
    ch automation refnum terminal in the VI and its subVIs until the run arrow is not broken. Also, you might have to replace some or all of the Invoke Nodes and Property Nodes for the ActiveX objects.
    Also, I came across this Knowledgebase. The error number is slightly different but it is always good to check it out and make sure it is not your case.
    Hope this helps.
    S Vences
    Applications Engineer
    National Instruments

  • Can not read data from URL!

    Hello,
    I want to read data from URL (http://84.100.130.82:8000/;stream.nsv). But can not do it. Because when try to call function openDataInputStream() shows this error: java.io.IOException: response does not start with HTTP it starts with: ICY. How I can fix this bug?
    HttpConnection c = null;
    InputStream is = null;
    OutputStream os = null;
    StringBuffer b = new StringBuffer();
    String           response,
    responseLitle;
    c = (HttpConnection)Connector.open(&#8220;http://84.100.130.82:8000/;stream.nsv&#8221;);
    os = c.openOutputStream();
    os.flush();
    is = c.openDataInputStream();     // ERROR CODE HERE
    int ch;
    // receive output
    while ((ch = is.read()) != -1)
    b.append((char) ch);
    response = b.toString();Regards, Ramunas

    Hi, I�m trying to do the same as above, get MP3 from a Shoutcast server.
    I got the same fault ("response does not start with HTTP it starts with: ICY") when I tried to open an HttpConnection as bellow:
    ============================================
    HttpConnection conn = (HttpConnection) Connector.open("http://64.236.34.196/stream/1074");
    Then I tried to open a socket connection as bellow:
    ======================================
    SocketConnection conn = (SocketConnection) Connector.open("socket://64.236.34.196:80");
    String get = "GET /stream/1074 HTTP/1.1";
    DataOutputStream os = conn.openDataOutputStream();
    os.writeUTF(get);
    InputStream is = conn.openInputStream();
    But then I got the following error:
    =========================
    java.lang.SecurityException: Target port denied to untrusted applications
    Could someone help me to find out what is going on?
    Thanks a lot!

Maybe you are looking for

  • IPod Sync issues in Windows 7

    I know that there is little to no support for Windows 7 yet, but, is anyone else having an issues syncing their iPod 5th G with iTunes? It will appear in Windows and in iTunes and then it will be "ejected" and disappears from Windows. iTunes will giv

  • Mapping Header Values to Item Nodes

    Using the graphical mapping editor, I need to map values from a source header level node to a target item level node for each item in the source structure. eg. <b>Source</b> <HEADER>   <H1>HeaderValue1</H1> </HEADER> <ITEM>   <I1>Item1Value</I1> </IT

  • Creating java doc

    i had ever used even a single comment in my program.. now i learned the java documentations theariticaly .. please give me a guide how to create it . iam using myeclipse ide.. say me what are the steps i have to follow in the following example.. * cl

  • New Muse pages won't upload when using Dreamweaver

    I create new pages in a existing Muse website and upload through Dreamweaver, like I always have. Then I get this error. The pages are fine when previewing them in my browser or even on a business catalyst site. File Transfer failed due to following

  • Every time I try to download or update an app I receive a notice that says The item is not currently available in The UK store. ***? I'm in California

    Everytime I try to download or an app or Download an update for an app I have, I receive a notice that says "unavailable in the U.K. store" What the heck? I am in California