【问题标题】:variable dereferancing error is not solving变量解引用错误未解决
【发布时间】:2012-06-02 03:29:44
【问题描述】:

我正在尝试用 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课上听说过,但我从未真正面对过。

【问题讨论】:

    标签: java console-application


    【解决方案1】:

    您不能在 Java 中调用原始类型的方法。改用静态方法Integer.toString

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

    您实际上也不需要转换为字符数组。您可以使用charAt 对字符串进行索引。


    parseInt 方法接受一个字符串,而不是一个字符,所以这行不起作用:

    if( Integer.parseInt(b[j]) == 1 )
    

    改为与字符'1'进行比较:

    if (b[j] == '1')
    

    【讨论】:

    • 非常感谢。你能解释一下为什么我在Integet.parseInt 中出现错误。
    • 我需要计算数字中的所有 1,例如:1011001 有 4 个 1。我不知道 charAt 是否可以在这里提供帮助。
    • @abhinav:parseInt() 方法只接受 String 作为参数,但您通过 b[j] 提供了 character
    【解决方案2】:

    这里,这应该为你做:

    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 = (new Integer(i)).toString().toCharArray();
    
    
          for ( int j = 0; j < b.length; j++ )
          {
            if( b[j] == '1' )
            {
                count++; // checking and counting if the element in array is 1 or not.
            }
          }
        }
    
        System.out.println("number of ones is : " + count);
    } 
    
    }
    

    【讨论】:

    • @david:abhinav 在马克回答的评论中问了另一个问题......我根据他的要求对其进行了修改。不想从马克那里拿走任何东西。
    猜你喜欢
    • 2014-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-31
    • 2018-10-08
    • 1970-01-01
    • 1970-01-01
    • 2020-11-13
    相关资源
    最近更新 更多