• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 256
  • Last Modified:

How do i count the number of elements in an array?

I am splitting the string using StringTokenizer. I also want to find the top and the bottom element of an array.

String mCust = request.getQueryString("cust");
StringTokenizer st = new StringTokenizer(mCust, ",");
  String[] tokens = new String[st.countTokens()];
  int i = 0;
  while(st.hasMoreElements())
     tokens[i++] = (String)st.nextElement();

---
Ramkumar
0
ramkumar_s1
Asked:
ramkumar_s1
1 Solution
 
allahabadCommented:
String mCust = Request.QueryString("cust");
StringTokenizer st = new StringTokenizer(mCust, ",");
    int totTokens = st.countTokens();
    String[] tokens = new String[totTokens];
    int i = 0;
    while(st.hasMoreElements()) {
      tokens[i++] = (String)st.nextElement();
    }
   System.out.println("Top token : " + tokens[0]);
   System.out.println("Bottom token : " + tokens[totTokens-1]);
0
 
cheekycjCommented:
PLEASE DO NOT AWARD PTS TO ME SINCE A SOLUTION HAS ALREADY BEEN GIVEN.  I AM ONLY GIVING AN ALTERNATIVE.  Pts should goto allahabad.

that is a good way to get all and show the top and bottom.

but if you just want the top and bottom just store the first and last in two string vars rather than using an array

String mCust = Request.QueryString("cust");
StringTokenizer st = new StringTokenizer(mCust, ",");
   int totTokens = st.countTokens();
   String firstToken = null;
   String lastToken = null;
   int i = 0;
   while(st.hasMoreElements()) {
     if (i == 0) {
       firstToken = st.nextToken();
     }
     else if (i == (totTokens-1)) {
       lastToken = st.nextToken();
     }
     else {
       String dummyString = st.nextToken();
       dummyString = null;
     }
     i++;
   }
  System.out.println("Top token : " + firstToken);
  System.out.println("Bottom token : " + lastToken);

CJ
0
 
girionisCommented:
No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:

- Points to allahabad

Please leave any comments here within the next seven days.

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

girionis
EE Cleanup Volunteer
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now