【问题标题】:java characters in a string字符串中的java字符
【发布时间】:2016-10-04 22:38:40
【问题描述】:

所以我的问题是我需要让用户输入string。然后他们将输入一个他们想要计算的字符。所以程序应该是count how many times the character他们输入的字符串会出现,这是我的问题。如果有人能给我一些有关如何执行此操作的信息,将不胜感激。

import java.util.Scanner;
public class LetterCounter {

public static void main(String[] args) {
    Scanner keyboard= new Scanner(System.in);

    System.out.println("please enter a word");//get the word from the user
    String word= keyboard.nextLine();
    System.out.println("Enter a character");//Ask the user to enter the character they wan counted in the string
    String character= keyboard.nextLine();

}

}

【问题讨论】:

    标签: java string character


    【解决方案1】:

    这是取自 this 之前提出的问题的解决方案,并经过编辑以更好地适应您的情况。

    1. 要么让用户输入一个字符,要么从 他们使用character.chatAt(0) 输入的字符串。
    2. 使用word.length 计算字符串的长度
    3. 创建一个 for 循环并使用word.charAt() 计算您的角色出现的次数。

      System.out.println("please enter a word");//get the word from the user
      String word= keyboard.nextLine();
      System.out.println("Enter a character");//Ask the user to enter the character they want counted in the string
      String character = keyboard.nextLine();
      char myChar = character.charAt(0);
      
      int charCount = 0;
      for (int i = 1; i < word.length();i++)
      {
          if (word.charAt(i) == myChar)
          {
              charCount++;
          }
      }
      
      System.out.printf("It appears %d times",charCount);
      

    【讨论】:

      【解决方案2】:

      应该这样做。它的作用是获取要查看的字符串,获取要查看的字符,遍历字符串以查找匹配项,计算匹配项的数量,然后返回信息。有更优雅的方法可以做到这一点(例如,使用正则表达式匹配器也可以)。

      @SuppressWarnings("resource") Scanner scanner = new Scanner(System.in);
      
      System.out.print("Enter a string:\t");
      String word = scanner.nextLine();
      
      System.out.print("Enter a character:\t");
      String character = scanner.nextLine();
      
      char charVar = 0;
      if (character.length() > 1) {
          System.err.println("Please input only one character.");
      } else {
          charVar = character.charAt(0);
      }
      
      int count = 0;
      for (char x : word.toCharArray()) {
          if (x == charVar) {
              count++;
          }
      }
      
      System.out.println("Character " + charVar + " appears " + count + (count == 1 ? " time" : " times"));
      

      【讨论】:

      • 很棒的工作,我只有一个问题,为什么 charVar=0 开头?
      • 它需要被初始化,因为它是一个字符。所有字符也是整数,所以 0 看起来和任何值一样好。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-09
      • 2011-11-27
      • 2016-03-10
      • 2015-06-19
      • 2015-12-23
      • 2019-02-09
      • 1970-01-01
      相关资源
      最近更新 更多