Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / February 2007

Tip: Looking for answers? Try searching our database.

String and Char Help

Thread view: 
BlackJackal - 31 Jan 2007 21:44 GMT
I have a few questions but first here is my code.

   public class CountVowels
  {
      public static void main(String[] args)
     {
        int vowel = 0;
        int i;
        char pos;
        String String1 = "Event Handlers is dedicated to making your
event a most memorable one.";
        int length = String1.length();
        for(i = 0; i < length - 1 ; i++);
        {
           pos = String1.charAt(i);
          if (pos == 'A' || pos == 'a' || pos == 'E' || pos == 'e' ||
pos == 'I' || pos == 'i' || pos == 'O' || pos == 'o' || pos == 'U' ||
pos == 'u') {
              vowel += 1;
           }
        }
        System.out.println("There are " + vowel + " vowels in this
String");
     }
  }

Question one is why does String1.length() return 70 when there are
only 69 chars.  Second question is why does this code not count the
vowels in the String.

Thanks  in advance

Robert
Knute Johnson - 31 Jan 2007 21:53 GMT
> I have a few questions but first here is my code.
>
[quoted text clipped - 29 lines]
>
> Robert

You still can't count and the problem is in the for loop!

Signature

Knute Johnson
email s/nospam/knute/

Alex Hunsley - 31 Jan 2007 22:07 GMT
> I have a few questions but first here is my code.
>
[quoted text clipped - 3 lines]
>       {
>  
[snip]

Didn't you just post this very same question 20 mins ago?
Hint: newsgroup posts don't always appear immediately. Give it at least
a couple of hours before assuming your message may have gone astray.
Annoying, I know....
cp - 31 Jan 2007 22:25 GMT
Your counting is off. And is you bothered to check your for-loop with the
syntax you'd probably locate the error.
cp - 31 Jan 2007 22:29 GMT
Oh and you should really consider replacing the if x || y || z.... with a
switch. It clutters the code otherwise.
Michael Rauscher - 01 Feb 2007 05:34 GMT
cp schrieb:
> Oh and you should really consider replacing the if x || y || z.... with a
> switch. It clutters the code otherwise.

In fact, I'd replace the whole if/switch thing with a simple

String vowels = "aAeEoOuU";

if ( vowels.indexOf(pos) != -1 )

or with a Map or ...

Bye
Michael
Michael Rauscher - 01 Feb 2007 22:35 GMT
Michael Rauscher schrieb:
> cp schrieb:
>> Oh and you should really consider replacing the if x || y || z....
[quoted text clipped - 3 lines]
>
> String vowels = "aAeEoOuU";

Which would be wrong, use

String vowels = "aAeEIiOoUu";

instead :)

Bye
Michael
Lew - 01 Feb 2007 23:27 GMT
> Which would be wrong, use
>
> String vowels = "aAeEIiOoUu";
>
> instead :)

"ÀàÁáÂâÃãÄäÅ寿ÈèÉéÊêËëÌìÍíÎîÏïÒòÓóÔôÕõÖöÙùÚúÛûÜüÝýŁłŒœαεΗηΥυΩωЮюийאוי" ...

- Lew
Michael Rauscher - 02 Feb 2007 02:21 GMT
Lew schrieb:
>> Which would be wrong, use
>>
[quoted text clipped - 3 lines]
>
> "ÀàÁáÂâÃãÄäÅ寿ÈèÉéÊêËëÌìÍíÎîÏïÒòÓóÔôÕõÖöÙùÚúÛûÜüÝýŁłŒœαεΗηΥυΩωЮюийאוי" ...

OP:

if (pos == 'A' || pos == 'a' || pos == 'E' || pos == 'e' ||
pos == 'I' || pos == 'i' || pos == 'O' || pos == 'o' || pos == 'U' ||
pos == 'u')

==>

"ÀàÁáÂâÃãÄäÅ寿ÈèÉéÊêËëÌìÍíÎîÏïÒòÓóÔôÕõÖöÙùÚúÛûÜüÝýŁłŒœαεΗηΥυΩωЮюийאוי" ?!?

;)

Bye
Michael
Randolf Richardson - 02 Feb 2007 03:27 GMT
> cp schrieb:
>
[quoted text clipped - 3 lines]
>
> String vowels = "aAeEoOuU";

    And sometimes i?  ;-)

    I'd also declare it like this:

        final String VOWELS = "aeiouAEIOU";

> if ( vowels.indexOf(pos) != -1 )
[sNip]

    The reason I'd re-order the variables to begin with lower-case is for  
efficiency since words are almost always mostly made up of combinations of  
lower-case letters, but of course the application of this must also be  
considered.  Anyway, by placing the more commonly used variations first,  
fewer iterations by the String.indexOf() method are required, and the  
application works just a tiny bit faster as a result.

    Now, with that in mind, if this little search is being used repeatedly in  
a loop, then the benefits of such optimizations become more clear.  With  
regards to optimization, one may wish to also investigate the possibility  
that "e" may be more common than "a" or that some other order would be  
better suited.

Signature

Randolf Richardson - kingpin+nntp@lumbercartel.ca
The Lumber Cartel, local 42 (Canadian branch)
http://www.lumbercartel.ca/

Chris Uppal - 02 Feb 2007 16:43 GMT
> I'd also declare it like this:
>
[quoted text clipped - 9 lines]
> fewer iterations by the String.indexOf() method are required, and the
> application works just a tiny bit faster as a result.

It would be interesting to know whether the overhead of the method call (and
it's internal logic too) would be quicker than an explicit switch statement.

Actually, it's quite hard to imagine a situation where the performance of
either technique would matter much -- bulk text is by its very nature IO
limited, and if there isn't a huge bulk of text to scan, why should ultra-fast
scanning be worth the effort ?   (Except for pure intellectual interest, of
course).

   -- chris
Randolf Richardson - 03 Feb 2007 08:23 GMT
[sNip]
> It would be interesting to know whether the overhead of the method call  
> (and it's internal logic too) would be quicker than an explicit switch  
> statement.

    That's a very good question.  If the method call is actually implemented  
with a machine language CALL instruction (at this point for me this is  
purely a case of second-guessing the JVM's byte-code interpreter), then  
call gates that result in task switches and other overhead issues  
involving stacks, various descriptor tables, etc., certainly can  
potentially cause a degree of serious performance hits with repeated use.

    To implement a switch statement in assembler (which is actually a lot  
more common than most people realize) requires conditional branching  
instructions, which may or may not have inherent overhead issues depending  
on the architecture.  My exposure to machine language is mostly limited to  
the ~1 MHz 6502 (on the Commodore 64 in my elementary school years) and  
Intel's 8088...Pentium (but mostly the 8088 and the 80386), so I don't  
know how CALL instructions on RISC and other well-known processors work  
under-the-hood and what effects they have.

> Actually, it's quite hard to imagine a situation where the performance of
> either technique would matter much -- bulk text is by its very nature IO
> limited, and if there isn't a huge bulk of text to scan, why should  
> ultra-fast scanning be worth the effort ?

    The nature of I/O is limited today, but may not be at some point in the  
future.  In fact, the use of USB Memory Sticks and RAM disks come to mind  
immediately as current real-world examples of breaking one type of such  
expected/assumed I/O speed limits.  With faster mass storage technologies,  
constantly improving caching algorithms (e.g., Novell's NetWare has an  
extremely effective read-ahead cache that has been light-years ahead of  
the industry for well over a decade, and is one of the reasons for its  
long-standing reputation as being the best Network Operating System for  
File and Print services), and a smattering of related hardware solutions  
(e.g., caching SCSI and SASCSI controllers with vast amounts of  
high-performance RAM installed), I firmly believe that I/O in most (if not  
all) areas will continue to improve (demand and marketplace competition  
are two key driving forces).

    Just because a situation where performance is crucial can't be fathomed,  
doesn't mean that one or more such situations don't, or won't, exist.  
There are a number of areas in computer programming, and a few other  
topics, that I know very well, but there are also a great deal more that I  
know little or nothing about (or even that they exist), thus I'm certain  
that assuming I could consider all possible uses or scenarios for anything  
is simply not realistic (although there's certainly nothing wrong with  
going through the exercise of trying to achieve this over any period of  
time).

    Regarding "worth," how would one measure this?  Optimization is clearly  
the "right" thing to do in many cases, although it may not be  
"economic"ally viable.  Understanding the reality of "getting paid for our  
work so we can continue to survive, etc." is obviously paramount, but if  
we develop a tendancy to ignore "right" in favour of "economic"  
considerations, then we also increase the risk losing at some [usually]  
undeterminable point in the future.  In essence, finding the optimal  
balance for the long term will more likley help to consider "worth"  
correctly.

    Also, understanding the "bigger picture" of what an entire application is  
designed for is a very helpful aid in determining which areas (if any) are  
the best candidates for optimization.

> (Except for pure intellectual interest, of course).

    I used to do a lot of assembler programming (Roedy Green got me  
interested in it many years ago), and I've had a somewhat keen interest in  
code optimization ever since (but only as time allows).

    One unexpected side-effect of code optimization that I discovered early  
on was that subtle "bugs" that would likely go undiscovered for many years  
were suddenly obvious, often in an "out of the blue" sort of way.  So, in  
addition to both the intellectual and performance considerations, the  
discovery of unexpected programming errors is an excellent justification  
for even attempting a small amount of optimization since it can  
potentially result in much better code.

Signature

Randolf Richardson - kingpin+nntp@lumbercartel.ca
The Lumber Cartel, local 42 (Canadian branch)
http://www.lumbercartel.ca/



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.