Java 变量解除限制错误未解决
我正在尝试用java编写一个程序,它可以在一个数字范围内计算“1”的个数 例如:如果我们从范围1-20看,我们将得到121的Java 变量解除限制错误未解决,java,console-application,Java,Console Application,我正在尝试用java编写一个程序,它可以在一个数字范围内计算“1”的个数 例如:如果我们从范围1-20看,我们将得到121的 1,2,3…9,10,1119,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; c
1,2,3…9,10,1119,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);
}
}
你能解释一下我在代码中做错了什么吗。我从来没有遇到过Integer.parseInt的问题,这个取消引用的问题对我来说是新问题。我刚在awt类中听说过这个问题,但我从来没有真正面对过它。在Java中不能对基元类型调用方法。使用静态方法
Integer.toString
:
char b[] = Integer.toString(a).toCharArray();
您实际上也不需要转换为字符数组。您可以使用索引索引到字符串中
方法
parseInt
接受字符串,而不是字符,因此此行不起作用:
if( Integer.parseInt(b[j]) == 1 )
而是与char'1'
进行比较:
if (b[j] == '1')
在这里,这应该可以为您做到:
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);
}
}
公共类计数\u个
{
公共静态void main(字符串参数[])
{
整数计数=0;
对于(int i=1;它有很多缺点。你能解释一下为什么我在Integet.parseInt
中出错。我需要数一数数字中的所有1,例如:1011001有4个1。我不知道charAt是否能帮上忙。@abhinav:theparseInt()
方法只接受字符串
作为参数,但您通过b[j]
为其提供了一个字符
@david:abhinav在mark的回答中的注释中问了另一个问题……我根据他的要求对其进行了修改。我不想从mark那里拿走任何东西。
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);
}
}