简体   繁体   中英

How many times the first character appears in a string

What I am Trying to Achieve:

Write a program that will ask the user to input a String. Then output the number of times the first letter of that String occurs. Assume the user will enter a String with all uppercase letters. For example, if the user enters “PETER PIPER PICKED A PECK OF PICKLED PEPPERS” your program should output “P occurs 9 times”.

What I have so far:

import javax.swing.JOptionPane;

public class counterCharacter {

  public static void main(String[] args)
  {
    String userInput = JOptionPane.showInputDialog("Input a string");
    int count = userInput.indexOf(0);
    for(int i =0; i < userInput.length(); i++)

        if(userInput.charAt(i) == 'a')  
          count++;
        System.out.println(count);
    }
}

The problem with this code is that it only prints the character 'a' and only if it occurs in index point 0. My task is to allow a user to input any string, take the character from index point 0 of the users input, and count exactly how many times that character reoccurs within the input. For the PETER PIPER example, the system should print out "6" because that is how many times the character in the index 0 position occurs. But if the user input abcdcbabcdcda, it should print out "3."

Any help with this would be much appreciated as I am a new programmer and missed a day of class and am now far behind and trying to catch up. If you can, please explain why you used the specific code you used and any reference materials I can use to learn how to use that specific thing. Thank You!

First you'll want to store the first character:

char firstChar = userInput.charAt(0);

Make a variably to keep track of the amount of matches you have found:

int count = 0;

Loop through the String and increase count if applicable:

for(int i=0; i<userInput.length(); i++){
  if(userInput.charAt(i) == firstChar){
    count++
  }
 }

EDIT: All you were basically missing is storing the first letter in a seperate variable.

I am not willing to give you working code, since it is no help to deliver the homework for you. Since you already know how to retrieve a character with userInput.charAt(n) you should save the first character as targetCharacter using the index 0 before the for-loop. You can now use the for loop to check every character for equality against that character and count those. For better readability you should correctly indent the code and use braces, like this:

if(userInput.charAt(i) == 'a') {
  count++;
}

Then you can print out the count after the for loop (which means after the curly brace of the for-loop. If you still have any trouble, alter your original question.

I would try it like this:

import javax.swing.JOptionPane;

public class CounterCharacter {
 public static void main(String[] args) {
    String userInput = JOptionPane.showInputDialog("Input a string");
    // Use charAt to retrieve a character at a specific position
    char firstChar = userInput.charAt(0);
    int count=0;

    for(int i =0; i < userInput.length(); i++)
        if(userInput.charAt(i) == firstChar)
      {
         count++;
      }
   System.out.println(count);
 }
}

public class CountCharacter {

 public static void main(String[] args) { int count = 1; String userInput = JOptionPane.showInputDialog("Input a string"); char ch = userInput.charAt(0); for(int i =1; i < userInput.length(); i++) { if(userInput.charAt(i) == ch) count++; } System.out.println(count); } } 

This will give you the output you intended to produce ....

You've described the problem fairly well, so you really need to just take your description of it and turn it into code.

This is probably difficult right now because you don't seem to understand why your code is doing what it is right now. Once you understand it -- line by line -- it should be easier to achieve the result you want.

I'll help you understand what you have now, you can take it and turn it into the working result:

String userInput = JOptionPane.showInputDialog("Input a string");

Get an input string to operate on.

int count = userInput.indexOf(0);

This method is using indexOf(int) . You are asking "where is the first occurrence (index) of character 0 ( null character ). This is not helpful, because what you want is the opposite -- you want the first character at index 0 . That's what charAt does instead. The docs for String are helpful -- read them.

Not only that but you are also assigning this result to count . Why?

You will you need to remember the character at index 0 (hint, a character, not an int ) but you also need to start a count -- at 0 if you start looping right at the beginning of the string. So I think you'll need to start with two variables.

for(int i =0; i < userInput.length(); i++)

Start a loop with i at 0 and increment until the last index of the string. That sounds right to me.

However, notice that you haven't included a { to open a block - this means that only the next statement (up to the next semicolon) will be included in the loop. This doesn't mean your code is broken, but this can be easy to turn into a bug later, if you add any more statements that you want to be in your loop.

    if(userInput.charAt(i) == 'a')

This checks if the character at i is 'a' -- why? What you really need is to see if it matches the first character.

Also be aware that if blocks (again, { ... } ) work the same way as for loops. It's best practice to use them on every if , else , for , while , etc. until you really know what you are doing. That way you won't get accidentally tripped up.

    count++;

Increment the count. This is what you want if your count is correct (but it wasn't, remember).

    System.out.println(count);

Looks good to me, except remember that this not in the loop block, but you've indented it like it is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM