我最近试图构建一个程序,它接受两个输入并检查它们是否在其他基础中均等表示(基数达到20)。但是我继续在第28行获得索引超出范围的例外......该怎么办?
例如:12(基数10)= 5(基数3)[均表示为' 12'在各自的基地。]
import java.util.Scanner;
import java.util.Arrays;
class Bases
{
public static void main()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter Two Numbers: ");
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println("Thank You for inputting the numbers!");
String basea[] = new String[20];
String baseb[] = new String[20];
int i=0 , j=0;
for( i=0;i<20;i++)
{
basea[i] = convert(a,i+1);
baseb[i] = convert(b,i+1);
}
for(i=0;i<=19;i++)
{
for(j=0;i<=19;j++)
{
if(basea[i].equals(baseb[j]))
{//this is where the exception keeps popping
break ;
}
}
}
if(i!=20){
if(i==0){
i=9;
System.out.println(a+"(base "+(i+1)+") ="+b+"(base "+(j+1)+")");
}
else
System.out.println(a+"(base "+(i+1)+") ="+b+"(base "+(j+1)+")");
}
else System.out.println("Numbers dont match at all till base 20!!");
}
private static String convert(int number,int base)
{
return Integer.toString(number,base);
}
}
答案 0 :(得分:1)
for(j=0;i<=19;j++)
上述循环应该是j <= 19
for(j=0;j<=19;j++)
答案 1 :(得分:0)
for(i=0;i<=19;i++)
{
for(j=0;i<=19;j++)
{
if(basea[i].equals(baseb[j]))
{//this is where the exception keeps popping
break ;
}
}
}
您可以在此原始代码段中看到您输入的拼写错误
for(i=0;i<=19;i++)
{
for(j=0;i<=19;j++) <---- the middle parameter is 'i' instead of 'j'
{
只需通过修正您的拼写错误来解决这个问题,如果您愿意,可以将其设为&lt; 20以增加整洁度。
for(i=0;i<20;i++)
{
for(j=0;j<20;j++)
{