Searching arrays using ascii

I am trying to solve a book problem. I created an array with letters and numbers and I'm supposed to figure out how to count the number of letters in the array. I tried the following code:
public class ArrayBasics1
  public static void main(String[] args)
     char[] myChar = {'1','2','3','a','b','c','d','e','f'};
     int count = 0, uncount = 0, x = 0;
     for(x = 0; x < myChar.length; ++x)
       //myChar[x] = (char)x; Doesn't work
       if(myChar[x] > 96 && myChar[x] < 123)
          count += 1;
       else
               uncount += 1;
       System.out.println("The number of letters in myChar is " + count);
       System.out.println("The number of characters in myChar which are not letters is " + uncount);
}  I think I'm searching the subscripts rather than the content of the array. Any help would be appreciated.

I just ran your code and it gave the output:
The number of letters in myChar is 6
The number of characters in myChar which are not letters is 3
This looks good to me - what were you expecting? I'm not sure what you were trying to do with "//myChar[x] = (char)x; Doesn't work", but you don't need that line.
One improvement you might want to make is to use the Character.isLetter() method which also includes upper case letters. e.g. replace
if(myChar[x] > 96 && myChar[x] < 123)with
if (Character.isLetter(myChar[x]))Good Luck

Similar Messages

  • Search given string array and replace with another string array using Regex

    Hi All,
    I want to search the given string array and replace with another string array using regex in java
    for example,
    String news = "If you wish to search for any of these characters, they must be preceded by the character to be interpreted"
    String fromValue[] = {"you", "search", "for", "any"}
    String toValue[] = {"me", "dont search", "never", "trip"}
    so the string "you" needs to be converted to "me" i.e you --> me. Similarly
    you --> me
    search --> don't search
    for --> never
    any --> trip
    I want a SINGLE Regular Expression with search and replaces and returns a SINGLE String after replacing all.
    I don't like to iterate one by one and applying regex for each from and to value. Instead i want to iterate the array and form a SINGLE Regulare expression and use to replace the contents of the Entire String.
    One Single regular expression which matches the pattern and solve the issue.
    the output should be as:
    If me wish to don't search never trip etc...,
    Please help me to resolve this.
    Thanks In Advance,
    Kathir

    As stated, no, it can't be done. But that doesn't mean you have to make a separate pass over the input for each word you want to replace. You can employ a regex that matches any word, then use the lower-level Matcher methods to replace the word or not depending on what was matched. Here's an example: import java.util.*;
    import java.util.regex.*;
    public class Test
      static final List<String> oldWords =
          Arrays.asList("you", "search", "for", "any");
      static final List<String> newWords =
          Arrays.asList("me", "dont search", "never", "trip");
      public static void main(String[] args) throws Exception
        String str = "If you wish to search for any of these characters, "
            + "they must be preceded by the character to be interpreted";
        System.out.println(doReplace(str));
      public static String doReplace(String str)
        Pattern p = Pattern.compile("\\b\\w+\\b");
        Matcher m = p.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (m.find())
          int pos = oldWords.indexOf(m.group());
          if (pos > -1)
            m.appendReplacement(sb, "");
            sb.append(newWords.get(pos));
        m.appendTail(sb);
        return sb.toString();
    } This is just a demonstration of the technique; a real-world solution would require a more complicated regex, and I would probably use a Map instead of the two Lists (or arrays).

  • Search Array with multiple values

    Hello,
    I've been helped with the prototype below by blemmo (thanks).
    It allows me to search my array using one property == a
    value.
    Now, I'd like to use it to:
    if ((prop1 == val1) &&(prop2 == val2) &&
    (prop3 == val3) {
    // search array for all values in array with the values of
    val1, val2 and val3
    Also, a way to search if one of the prop and val's are blank,
    ie...
    ((prop1 == val1) &&(prop2 == val2) && (prop3
    == val3)
    where prop2 and val2 are "undefined"
    so the search will only search for the prop and val that are
    not "undefined"
    make since? Don't know where to start.
    help and thanks in advance.

    it is an array like this.. but with more properties... also,
    is it better to use XML to load large arrays or is it ok to use
    actionscript in the file.
    which is faster to load? say if I had an array of 150
    elements?
    myArray = [{myname:"bob", county:"skagit", city:"Sedro
    Woolley", id:1,
    pic:"1.jpg",pic1:"2.jpg",pic2:"3.jpg",pic3:"4.jpg"},
    {myname:"bob", county:"skagit", city:"Sedro Woolley", id:1,
    pic:"1.jpg",pic1:"2.jpg",pic2:"3.jpg",pic3:"4.jpg"

  • Using ASCII in java

    How can i use ascii in java programming. For example i want convert binary to decimal and use operator such XOR etc to campare to another decimal number. After that convert into ascii code.
    thank you

    If you have a string, then you can convert it into an array of char. Chars are just numbers. (They're numbers that represent unicode characters, but they're still numbers.)
    And all the primitive types in java are essentially binary; you don't have to convert anything to binary unless you mean to convert it for display purposes.
    If you have a string and want to convert it to ascii, then you can specify the encoding type (ascii) while converting to bytes or writing output to a file, etc.
    Hope this helps.

  • How to get the values of an Array using JSP Tags

    Hey guys,
    I need some help. I've splited a String using
    fn:split(String, delim) where String = "1,2,3,4" and delim is ,
    This method returns an Array of splited Strings. how do i get the values from this array using jsp tags. I don't wanna put java code to achive that.
    Any help would be highly appreciated
    Thanks

    The JSTL forEach tag.
    In fact if all you want to do is iterate over the comma separated list, the forEach tag supports that without having to use the split function.
    <c:set var="list" value="1,2,3,4"/>
    <c:forEach var="num" items="${list}">
      <c:out value="${num}"/>
    </c:forEach>The c:forTokens method will let you do this with delimiters other than a comma, but the forEach tag works well just with the comma-delimited string.

  • How can I use ASCII Characters on the iPad?

    I have an iPad (1) and use iOS 4.3.5. Is there an easier Way of using ASCII Characters than having to use the "copy-Paste" procedure? If not, can we expect to see the feature of entering the ASCII code straight through the standard keyboard soon?

    Norisouro wrote:
    . Is there an easier Way of using ASCII Characters than having to use the "copy-Paste" procedure?
    You need to give some details about what it is you want to do, because ASCII Characters are what are already on the keyboard.  It is non-ASCII that you might need to copy/paste.
    http://en.wikipedia.org/wiki/ASCII
    I think you can be sure that Apple is never going to include a feature in iOS that has you input special characters by typing in numbers like Windows does it.  Mac's have always used a different approach.

  • How to populate multi-cluster arrays using matlab code?

    Hi,
    I have an array of clusters containing two 'Double' elements in each cluster. I am looking for a method to populate this array using MATLAB code. I need around 1000 clusters in the array, so populating it using the front panel is not practical. There is also some calculation involved in deciding the value in each element. If there is an example or a method to do this, please point me in the right direction.
    Thanks

    altenbach wrote:
    Can you attach a typical file so we know that the structure is? It is easy to convert from any data structure to any other data structure. You could even read it as a 1D string array and parse each line into a cluster, for example. It all depends on how the fil is arranged. You could also read the file as a flat string and chop it up into the desired structure later.
    I have attached the .vi file. I need to convert the spreadsheet to an array of clusters, thats where I'm getting stuck. (The vi is an example from help libraries)
    That is the part where I need to change so that I can use a spreadsheet.
    Attachments:
    Buffered counter.vi ‏52 KB

  • Given filename or path contains Unicode or double-byte characters.Retry using ASCII characters for filename and path What does this mean? it happen when I publish an OAM

    Given file name or path contains Unicode or double-byte characters. Retry using ASCII characters for filename and path
    What does this mean? It is happening when I try to publish an OAM for Dreamweaver.
    Also: How can I specify the browser in Edge Animate? It is just going wherever. Are there no Preferences for Edge Animate?
    BTW. Just call it Edge. Seriously. Do you call it Illustrator Draw? Photoshop Retouching?

    No, my file name is mainContent.oam
    My project name is mainContent.an
    This error happens when I try to import into Dreamweaver. Sorry, I wasn't clear on that earlier.
    I thought maybe it was because I had saved my image as a png. So re-saved as a svg, still get the error.
    DO I have a setting is Dreamweaver CC that is wrong? Should I try this in Dreamweaver CS6? I might try that next.
    Why is this program so difficult? I know Flash. I know After Effects. I can work the timeline part just great. It's always in the export that I have problems.
    On a MacPro, 10.7.
    Are you an Adobe person or just a nice helper?

  • I am getting a 404 error when trying to access any search link using google, I can get to a website if I enter the url directly.  I have cleared my history, emptied the cache and reset safari.

    I keep getting a 404 error when trying to access any search link using google, I can get to a website by directly using the URL.  I have cleared history, empited the cache and reset safari.  Any suggestions.

    Right. If you are using delegated privs and sudo, make sure that sudo is configured to pass on the PERL5LIB and ORACLE_HOME environment variables at least.

  • Playing a wav file (byte array) using JMF

    Hi,
    I want to play a wav file in form of a byte array using JMF. I have 2 classes, MyDataSource and MyPullBufferStream. MyDataSource class is inherited from PullStreamDataSource, and MyPullBufferStream is derived from PullBufferStream. When I run the following piece of code, I got an error saying "EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x7c9108b2, pid=3800, tid=1111". Any idea what might be the problem? Thanks.
    File file = new File(filename);
    byte[] data = FileUtils.readFileToByteArray(file);
    MyDataSource ds = new MyDataSource(data);
    ds.connect();
    try
        player = Manager.createPlayer(ds);
    catch (NoPlayerException e)
        e.printStackTrace();
    if (player != null)
         this.filename = filename;
         JMFrame jmframe = new JMFrame(player, filename);
        desktop.add(jmframe);
    import java.io.IOException;
    import javax.media.Time;
    import javax.media.protocol.PullBufferDataSource;
    import javax.media.protocol.PullBufferStream;
    public class MyDataSource extends PullBufferDataSource
        protected Object[] controls = new Object[0];
        protected boolean started = false;
        protected String contentType = "raw";
        protected boolean connected = false;
        protected Time duration = DURATION_UNKNOWN;
        protected PullBufferStream[] streams = null;
        protected PullBufferStream stream = null;
        protected final byte[] data;
        public MyDataSource(final byte[] data)
            this.data = data;
        public String getContentType()
            if (!connected)
                System.err.println("Error: DataSource not connected");
                return null;
            return contentType;
        public void connect() throws IOException
            if (connected)
                return;
            stream = new MyPullBufferStream(data);
            streams = new MyPullBufferStream[1];
            streams[0] = this.stream;
            connected = true;
        public void disconnect()
            try
                if (started)
                    stop();
            catch (IOException e)
            connected = false;
        public void start() throws IOException
            // we need to throw error if connect() has not been called
            if (!connected)
                throw new java.lang.Error(
                        "DataSource must be connected before it can be started");
            if (started)
                return;
            started = true;
        public void stop() throws IOException
            if (!connected || !started)
                return;
            started = false;
        public Object[] getControls()
            return controls;
        public Object getControl(String controlType)
            try
                Class cls = Class.forName(controlType);
                Object cs[] = getControls();
                for (int i = 0; i < cs.length; i++)
                    if (cls.isInstance(cs))
    return cs[i];
    return null;
    catch (Exception e)
    // no such controlType or such control
    return null;
    public Time getDuration()
    return duration;
    public PullBufferStream[] getStreams()
    if (streams == null)
    streams = new MyPullBufferStream[1];
    stream = streams[0] = new MyPullBufferStream(data);
    return streams;
    import java.io.ByteArrayInputStream;
    import java.io.IOException;
    import javax.media.Buffer;
    import javax.media.Control;
    import javax.media.Format;
    import javax.media.format.AudioFormat;
    import javax.media.protocol.ContentDescriptor;
    import javax.media.protocol.PullBufferStream;
    public class MyPullBufferStream implements PullBufferStream
    private static final int BLOCK_SIZE = 500;
    protected final ContentDescriptor cd = new ContentDescriptor(ContentDescriptor.RAW);
    protected AudioFormat audioFormat = new AudioFormat(AudioFormat.GSM_MS, 8000.0, 8, 1,
    Format.NOT_SPECIFIED, AudioFormat.SIGNED, 8, Format.NOT_SPECIFIED,
    Format.byteArray);
    private int seqNo = 0;
    private final byte[] data;
    private final ByteArrayInputStream bais;
    protected Control[] controls = new Control[0];
    public MyPullBufferStream(final byte[] data)
    this.data = data;
    bais = new ByteArrayInputStream(data);
    public Format getFormat()
    return audioFormat;
    public void read(Buffer buffer) throws IOException
    synchronized (this)
    Object outdata = buffer.getData();
    if (outdata == null || !(outdata.getClass() == Format.byteArray)
    || ((byte[]) outdata).length < BLOCK_SIZE)
    outdata = new byte[BLOCK_SIZE];
    buffer.setData(outdata);
    byte[] data = (byte[])buffer.getData();
    int bytes = bais.read(data);
    buffer.setData(data);
    buffer.setFormat(audioFormat);
    buffer.setTimeStamp(System.currentTimeMillis());
    buffer.setSequenceNumber(seqNo);
    buffer.setLength(BLOCK_SIZE);
    buffer.setFlags(0);
    buffer.setHeader(null);
    seqNo++;
    public boolean willReadBlock()
    return bais.available() > 0;
    public boolean endOfStream()
    return willReadBlock();
    public ContentDescriptor getContentDescriptor()
    return cd;
    public long getContentLength()
    return (long)data.length;
    public Object getControl(String controlType)
    try
    Class cls = Class.forName(controlType);
    Object cs[] = getControls();
    for (int i = 0; i < cs.length; i++)
    if (cls.isInstance(cs[i]))
    return cs[i];
    return null;
    catch (Exception e)
    // no such controlType or such control
    return null;
    public Object[] getControls()
    return controls;

    Here's some additional information. After making the following changes to MyPullBufferStream class, I can play a wav file with gsm-ms encoding with one issue: the wav file is played many times faster.
    protected AudioFormat audioFormat = new AudioFormat(AudioFormat.GSM, 8000.0, 8, 1,
                Format.NOT_SPECIFIED, AudioFormat.SIGNED, 8, Format.NOT_SPECIFIED,
                Format.byteArray);
    // put the entire byte array into the buffer in one shot instead of
    // giving a portion of it multiple times
    public void read(Buffer buffer) throws IOException
            synchronized (this)
                Object outdata = buffer.getData();
                if (outdata == null || !(outdata.getClass() == Format.byteArray)
                        || ((byte[]) outdata).length < BLOCK_SIZE)
                    outdata = new byte[BLOCK_SIZE];
                    buffer.setData(outdata);
                buffer.setLength(this.data.length);
                buffer.setOffset(0);
                buffer.setFormat(audioFormat);
                buffer.setData(this.data);
                seqNo++;
        }

  • Trying to compare string array using equals not working

    Hi,
    im prolly being really dumb here, but i am trying to compare 2 string arrays using the following code:
    if(array.equals(copymearray))
    System.out.println("they match");
    else
    {System.out.println("dont match");}
    the trouble is that even though they do match i keep getting dont match, can anyone tell me why?

    try
    if (Arrays.equals(array, copymearray))
    System.out.println("they match");
    else
    {System.out.println("dont match");}

  • How to make a form-based search API using HTTPClient

    Hi,
    I am getting trouble to make an API that is related to making a site search by using a form-based search API by help of HTTPClient

    Hi,
    Something seems to get added to the form action because of "http". Hence I am removing it.
    You need to write a procedure with the values in the as parameters. Say for example you want to insert a record into dept
    table then
    Dynamic page code
    <html>
    <body>
    <form action="portalschema.insert_dept">
    <input type="text" name="p_deptno">
    <input type="text" name="p_dname">
    <input type="submit" name="p_action" value="save">
    </form>
    </body>
    </html>
    Procedure code.
    create or replace procedure insert_dept
    (p_deptno in number,
    p_dname in varchar2,
    p_action in varchar2)
    is begin
    if p_action = 'save' then
    insert into scott.dept(deptno,dname) values(p_deptno,p_dname);
    commit;
    end if;
    end;
    grant execute on insert_dept to public;
    Hope this helps.
    Thanks,
    Sharmila

  • Problem showing Trademark symbol using ascii code in Flex 3

    I am facing problem in displaying trademark symbol (™) using ascii codes(it is showing square symbol). I have ascii code stored in the database for trademark symbol(ascii code "&#153;" ). So I can't use Hexa code instead of ascii code. But using ascii code I am able to show copyright symbol. Following is the sample code :
    <?xml version="1.0"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical">
        <mx:Script>
            var trademarkSymbol = "\u2122";
            var trademarkSymbol1 = "&#153;";
            var copyrightSymbol = "\u00A9";
            var copyrightSymbol1 = "&#169;";
        </mx:Script>
        <mx:Label text="Macromedia™"/>
        <mx:Label text="Macromedia{trademarkSymbol}"/>
        <mx:Label text="Macromedia{trademarkSymbol1}"/>      \\ problem  code
        <mx:Label text="Macromedia©"/>
        <mx:Label text="Macromedia{copyrightSymbol}"/>
        <mx:Label text="Macromedia{copyrightSymbol1}"/>
    </mx:Application>
    Please suggest some solution.
    Regards
    Rajat Sahni

    You must use Unicode values, not Windows extended ASCII values.
    The Unicode value of a copyright symbol is hex 00A9 or decimal 169. This happens to be the same as where it is in a Windows' extended ASCII character set, but this is irrelevant. The Unicode value of a copyright symbol is hex 2122 or decimal 8482. In Windows' extended ASCII it has a different value, hex 99 or decimal 153, but again this is irrelevant.
    So the reason you think it "works" for the copyright and not for the trademark is that the two character sets agree on the value of the copyright but disagree on the value of the trademark.
    Moral: Find a good Unicode table.
    Gordon Smith
    Adobe Flex SDK Team

  • WRE54G v3 - WEP key setting when using ASCII passphrase

    When entering WEP information for this device you may notice that the range expander is asking for the WEP key in hex (for example: 128 bits 26 hex digits). If the key that you have set in your router is using a passphrase then you will need to convert it to hex. Entering the passphrase and clicking the generate button will not work if your router is set to use ASCII as the WEP key format. The result seems to be that the PC may attempt to connect (and/or show as connected) but will not receive an IP address and does not really connect to your network. Strangely, the WRE54G will show that it has connected sucessfully to the router. Instead, convert the passphrase to hex one character at a time then enter the hex digits as the hex key. For example: if you are using 128 bit and your passkey is: 1234567890123 then enter 31323334353637383930313233 as the 128bit hex key (1 in ASCII = 31 in hex, 2 in ASCII = 32 in hex, etc...). http://www.asciitable.com/ 

    Hi, The solution I posted above works for me . I can ping the WRE from the network and access the configuration page. The wireless router I am connecting to is a TP-LINK TL-WR340G. The extender is a WRE54G ver. 3 running v3.04.01 firmware. Instead of converting the passphrase to hex I could just set the TP-LINK router to use a hex key instead but thats a pain. Then I would have to type in a long hex key when adding another wireless device to the network or when allowing a guest device on the network. An ASCII passphrase is so much easier to remember and much less typing. If I leave the TP-LINK router set to accept an ASCII passphrase then convert the ASCII passphrase to hex and enter it into the WRE extender then I can use an ASCII passphrase when connecting a device through the extender .
    What I found confusing initially though (before finding the solution) was that if I enter the ASCII passphrase into the extender setup and click the generate button for it to generate the 4 hex keys, the extender claims to connect successfully. I cannot ping it from the network and a wireless device will not get a connection through it but the light does turn blue and the setup screen shows the correct mac address in the link status section. Seems like a bug...

  • How to create an array using reflection.

    How to create an array using reflection.
    I want to achive something like this,Object o;
    o = (Object)(new TestClass[10]);but by use of reflection.
    To create a single object is simple:Object o;
    o = Class.forName("TestClass").newInstance();But how do I create an array of objects, when the class of objects is known only by name? (Can't use Object[] because even though an Object[] array can be filled with "TestClass" elements only, it Cannot be casted to a TestClass[] array)
    Anybody knows?":-)
    Ragnvald Barth
    Software enigneer

    Found it!
    the java.lang.reflect.Array class solves it!
    Yes !!!

Maybe you are looking for

  • Feedback for my site, please

    Dear Friends, Can you please give me some feedback about my site http://www.anonser.pl Let me know what you think about the design and give me some tips about making the site better for Google. Thanks Already. Kind Regards,

  • Help opening ports ...

    i have high speed DSL and i wireless linksys router that i use to play a PS3 online. i can play games online just fine but when i attempt to connect directly to other players (attempting to join squads, parties, one on one football matches, etc.) i a

  • How do I get the directory name that a class is located in?

    How do I get the directory name that a class is located in? I have a class located under /com/dhcmc and I want to be able to retrieve the "/com/dhcmc" that the class is residing under so that I can then use this directoy name to build a relative path

  • Reformated my computer, need help!

    I just did a reformat of my computer which means that im starting from scratch all over again. i have all my songs on my ipod but i had to download a new itunes. whenever i connect my ipod to my new itunes i get the choices of "erase and sync" or "tr

  • Error in IDOC BLAORD03

    Hi all, I'm transfering the purchase contract to Backend. There in bd87 I have an error: No batch input data for screen SAPMM06E 0514. Does anybody seen the same problem? Regards, Vlad