Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variable dereferancing error is not solving

I am trying to write a program in java which can count number of '1' in a range of numbers.

For examples: if we look from range 1 - 20 we will get 12 1's
1, 2,3....9, 1 0, 1 1 .... 1 9, 20.

here is the code i have written.

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);
} 

}

I am getting two errors on compiling.

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>

Can you also explain what i did wrong in the code. i never had problem with Integer.parseInt and this de-referencing problem is new to me. i just heard about it in awt class but i never actually faced it.

like image 270
Abhinav Kulshreshtha Avatar asked Dec 29 '25 20:12

Abhinav Kulshreshtha


1 Answers

You can't call methods on primitive types in Java. Use the static method Integer.toString instead:

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

You also don't actually need to convert to a character array. You can index into a string using charAt.


The method parseInt accepts a string, not a char, so this line doesn't work:

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

Instead do the comparison with the char '1':

if (b[j] == '1')
like image 156
Mark Byers Avatar answered Dec 31 '25 08:12

Mark Byers