计算字符串字母

时间:2014-01-02 06:17:22

标签: java arrays string

程序需要计算您输入的“O”和“P”的数量。它将输出“O”的数量和“P”的数量,如果输入X,程序将终止,然后如果它与使用数组相等或不相等则输出。有人可以给我这个代码或算法吗?

这是我的代码

public static void main( String[] args ) 
{

    Scanner scn=new Scanner(System.in);
    int x=0;
    String input;
    String a[] = { "A", "a"};
    String b[] = { "B", "b"};        

    while(x==0)
    {
        input=scn.nextLine();
        if(input.equals("X")||input.equals("x"))
        {
            System.out.println("Terminated");
            break;
        }
        //what to do next?
    }
}

提前致谢。

2 个答案:

答案 0 :(得分:2)

似乎只是一个功课,所以只是提示。

  • 您正在检查字母x是否已终止。还有另外两个 if语句检查字符是p还是0。
  • 声明两个变量来计算P和O的数量。
  • 如果字符是P,则增加P.的变量 O操作。

答案 1 :(得分:0)

public static void main( String[] args ) 
{
  Scanner scn=new Scanner(System.in);
  int x=0;
  int countO=0;
  int countP=0;
  String input;
  String a[] = { "A", "a"};
  String b[] = { "B", "b"};        

  while(x==0)
  {
    input=scn.nextLine();
    if(input.equals("X")||input.equals("x"))
    {
        System.out.println("Terminated");
        System.out.println("number of O = " + countO);
        System.out.println("number of P = " + countP);
        break;
    }
  // In the same way as you check for X check input for O then P
  // If it is O then increase the count for O.
  //If it is P then increase the count for P.
}