简体   繁体   English

第一个字符出现在字符串中的次数

[英]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”. 例如,如果用户输入“ PEPER PIPER PICKED A PECKED PEPPERS”,您的程序应输出“ P发生9次”。

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. 此代码的问题在于,仅当字符'a'出现在索引点0中时,它才会输出。我的任务是允许用户输入任何字符串,从用户输入的索引点0中获取字符,并且准确计算该字符在输入中再次出现的次数。 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. 对于PETER PIPER示例,系统应打印出“ 6”,因为这是索引0位置的字符出现了多少次。 But if the user input abcdcbabcdcda, it should print out "3." 但是,如果用户输入abcdcbabcdcda,则应打印出“ 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. 由于您已经知道如何使用userInput.charAt(n)检索字符, userInput.charAt(n)应该在for循环之前使用索引0将第一个字符另存为targetCharacter You can now use the for loop to check every character for equality against that character and count those. 现在,您可以使用for循环检查每个字符是否与该字符相等,并对这些字符计数。 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. 然后,您可以在for循环之后打印出计数(这意味着在for循环的花括号之后。如果仍然遇到问题,请更改原始问题。

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) . 此方法使用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. 您正在问“字符0( 空字符 )的第一个出现位置(索引)在哪里。这没有用,因为您想要的是相反的-您想要索引 0处第一个字符 。这就是charAt所做的。 String文档对您有所帮助-阅读它们。

Not only that but you are also assigning this result to count . 不仅如此,您还需要将此结果分配给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. 您将需要记住索引0处的字符(提示,一个字符,而不是int ),但是如果您刚开始在字符串的开头循环,则还需要从0开始计数。 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. i为0开始循环,然后递增直到字符串的最后一个索引。 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? 这会检查i处的字符是否为'a' -为什么? 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. 还要注意,if块(再次是{ ... } )的工作方式与for循环相同。 It's best practice to use them on every if , else , for , while , etc. until you really know what you are doing. 最好在每个ifelseforwhile等上使用它们,直到您真正知道自己在做什么。 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). 这是您想要的,如果您的count正确(但事实并非如此,请记住)。

    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. 对我来说看起来不错,但是请记住,这不在循环块中,但是您已经缩进了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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