无与伦比的类型:char和string [英] Incomparable types: char and string

查看:93
本文介绍了无与伦比的类型:char和string的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import java.util.*;
import java.lang.*;
public class MyClass {
  public static void main(String args[]) {
    Scanner in = new Scanner(System.in);
    int count = 0;
    String inputEntry = in .nextLine();
    String inputCharacter = in .nextLine();
    if (inputCharacter.length() != 1) {
      System.out.println("Please enter single character");
System.exit(0);

    } else {
      for (int i = 0; i < inputEntry.length(); i++) {
        if (inputEntry.charAt(i) == inputCharacter) {
          count++;
        }
      }
      System.out.println("There is " + count + " occurence(s) of '" + inputCharacter + "' in " + inputEntry);
    }
  }
}





我尝试了什么:



请调试错误。它显示行中的错误if(inputEntry.charAt(i)== inputCharacter)我不明白如何调试它。



What I have tried:

debug the error please. it shows an error in the line if (inputEntry.charAt(i) == inputCharacter) i dont understand how to debug this.

推荐答案

快速版本将是如下:



The fast version would be as follows:

if (inputEntry.charAt(i) == inputCharacter.charAt(0)) {
	          count++;
	        }





发生的事情是你已经将inputCharacter声明为String对象,所以显然不是真正的char或char []。

你的小代码片段会有更好的版本(因为你的小字符总是单个单元大小):





What happens is that you have declared inputCharacter as a String object, so obviously is not really a char or char[].
A better version for your little code snippet would be (since your little char will always be of single unit size):

int countz = StringUtils.countMatches(inputEntry, inputCharacter);





这也允许进行实际的子串比较。如果你真的,真的确定你想要在你的字符串中只需要一个字符,那么就使用这样的东西:





This allows for actual substring comparisons also. If you are really, really sure you want just one character inside your string, to be accounted for, then just use something like this:

int countz = StringUtils.countMatches(inputEntry, inputCharacter.charAt(0));


这篇关于无与伦比的类型:char和string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆