?
Solved

for loops

Posted on 2005-03-15
11
Medium Priority
?
267 Views
Last Modified: 2010-03-31
i need to know how to use a for loop in a program that asks the user to enter a sentence, and the program has to figure out how many spaces there are in the sentences. I am using BlueJ by the way. Thanks!
0
Comment
Question by:rkjohnson2005
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
  • 2
11 Comments
 

Expert Comment

by:dream2k5
ID: 13551182
you could use this method to count the spaces in your sentence:

   public int countSpaces(String sentence){
        int count = 0;
        for(int i = 0; i < sentence.length(); i++){
            if(sentence.charAt(i) == ' '){
                count++;
            }
        }
        return count;
    }

hope this helps.
0
 

Accepted Solution

by:
dream2k5 earned 1000 total points
ID: 13551675
here is the full source, with userinput option:

import java.io.*;

public class spaceCounter {
    public spaceCounter() {
    }

    public static void main(String[] args) {

        spaceCounter spacecounter = new spaceCounter();
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        System.out.print("Enter a sentence:");

        try {
           
            String sentence = br.readLine();
            int spaces = spacecounter.countSpaces(sentence);
            System.out.println("Your sentence contains " + spaces + " spaces.");
        } catch (IOException ex) {

        }
    }

    public int countSpaces(String sentence) {

        int count = 0;
        for (int i = 0; i < sentence.length(); i++) {

            if (sentence.charAt(i) == ' ') {

                count++;
            }
        }
        return count;
    }
}
0
 
LVL 19

Expert Comment

by:Jim Cakalic
ID: 13552526
Not bad, dream2k5.

One alternative method would be to use String.toCharArray to get a char[] copy of what the String holds and then iterate over the char[]. This avoids a method call to get each character of the String:

    char[] chars = sentence.toCharArray();
    for (int i = 0; i < chars.length; ++i) {
        if (chars[i] == ' ')
            ++count;
    }

A second alternative would be to use String.indexOf. This is the way that the Jakarta commons-lang StringUtils class does it. Here is the source method from that implementation:

    public static int countMatches(String str, String sub) {
        if (str == null || str.length() == 0 || sub == null || sub.length() == 0) {
            return 0;
        }
        int count = 0;
        int idx = 0;
        while ((idx = str.indexOf(sub, idx)) != -1) {
            count++;
            idx += sub.length();
        }
        return count;
    }

You'd call it this way:

    int matches = countMatches(string, " ");

I've sometimes wondered why a similar method isn't actually implemented by the String class.

Regards,
Jim Cakalic
0
Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

 
LVL 30

Expert Comment

by:Mayank S
ID: 13553076
Is that somebody's homework done ;-) ?
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 13553086
>> I've sometimes wondered why a similar method isn't actually implemented by the String class

It would be more like a utility method rather than a property of a String object. Otherwise we could think of innumerable possibilities like how many vowels does it have, how many consonants does it have, and so on :)
0
 

Expert Comment

by:dream2k5
ID: 13554497
Sorry Venabili,

i didnt know it was against the rules to post full sources, maybe i should read them a bit more carefully. Will read them again ;)
0
 
LVL 19

Expert Comment

by:Jim Cakalic
ID: 13555063
>> It would be more like a utility method rather than a property of a String object.

Seems to me it is no less reasonable for there to be a String.countMatches method than there is for String to directly have the methods matches and split.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 13562506
matches () and split () were introduced in 1.4, probably for the same types of concerns as you have. Maybe that they will introduce a countMatches () too.
0
 

Expert Comment

by:dream2k5
ID: 13602882
:)
0

Featured Post

Get real performance insights from real users

Key features:
- Total Pages Views and Load times
- Top Pages Viewed and Load Times
- Real Time Site Page Build Performance
- Users’ Browser and Platform Performance
- Geographic User Breakdown
- And more

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
In this post we will learn different types of Android Layout and some basics of an Android App.
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
Suggested Courses
Course of the Month12 days, 22 hours left to enroll

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question