java-变量解引用错误无法解决
作者:互联网
我正在尝试用Java编写一个程序,该程序可以在一个数字范围内计数“ 1”的数量.
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.
这是我写的代码.
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中的原始类型上调用方法.请使用静态方法Integer.toString:
char b[] = Integer.toString(a).toCharArray();
您实际上也不需要转换为字符数组.您可以使用charAt
索引到字符串.
方法parseInt接受字符串,而不是char,因此此行不起作用:
if( Integer.parseInt(b[j]) == 1 )
而是使用char’1’进行比较:
if (b[j] == '1')
标签:console-application,java 来源: https://codeday.me/bug/20191201/2079630.html