Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

for loops

Posted on 2005-03-15
11
Medium Priority
?
270 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
  • 4
  • 3
  • 2
9 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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
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

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

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

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
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…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
Suggested Courses
Course of the Month12 days, 12 hours left to enroll

578 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