我正在尝试用Java编写一个程序,该程序可以在一个数字范围内计数“1”的数量。

例如:如果我们从1到20的范围看,将会得到 12 1
1 ,2,3 .... 9, 1 0, 1 1 .... 1 9,20。

这是我写的代码。

public class Count_no_of_ones
{
public static void main( String args[] )
{
    int count = 0;

    for ( int i = 1; i<=20; i++ )
    {
      int a=i;
      char b[] = a.toString().toCharArray(); //converting a number to single digit array

      for ( int j = 0; j < b.length; j++ )
      {
        if( Integer.parseInt(b[j]) == 1 )
        {
            count++; // checking and counting if the element in array is 1 or not.
        }
      }
    }

    System.out.println("number of ones is : " + count);
}

}

我在编译时遇到两个错误。
D:\Programs\Java>javac Count_no_of_ones.java

Count_no_of_ones.java:10: error: int cannot be dereferenced
char b[] = a.toString().toCharArray(); //converting a number to single digit array
            ^
Count_no_of_ones.java:14: error: no suitable method found for parseInt(char)
if( Integer.parseInt(b[j]) == 1 )
           ^
method Integer.parseInt(String) is not applicable
(actual argument char cannot be converted to String by method invocation conversion)

method Integer.parseInt(String,int) is not applicable
(actual and formal argument lists differ in length)

2 errors
D:\Programs\Java>

您能否也解释一下我在代码中做错了什么。我从未遇到过Integer.parseInt的问题,这个取消引用的问题对我来说是新的。我只是在awt class 听说过它,但我从未真正面对过它。

最佳答案

您不能在Java中的原始类型上调用方法。请使用静态方法Integer.toString代替:

char b[] = Integer.toString(a).toCharArray();

您实际上也不需要转换为字符数组。您可以使用 charAt 索引成字符串。
parseInt方法接受一个字符串,而不是一个char,因此此行不起作用:
if( Integer.parseInt(b[j]) == 1 )

而是使用char '1'进行比较:
if (b[j] == '1')

10-08 08:30
查看更多