数组边界溢出问题??
import java.util.Scanner;
public class Transfer
{
int x;
int select;
int []yu=new int[20];
int i;
void get()
{
System.out.printf( "\t十进制转换器\n ");
System.out.printf( "1.转换成二进制数\n ");
System.out.printf( "2.转换成八进制数\n ");
System.out.printf( "3.转换成十六进制数\n ");
System.out.printf( "0.退出\n ");
System.out.println( "请输入一个十进制数据: ");
Scanner input=new Scanner(System.in);
x=input.nextInt();
System.out.println( "请选择转换方式: ");
select=input.nextInt();
}
void choose()
{
while(select!=0) //就是加了个WHILE语句,调试过程就提示说数组边界溢出,为什么呢,晕哦
{
if (select> 3||select <0)
{
System.out.println( "转换方式选择错误,请重选 ");
get();
}else
{
if (select==0) System.exit(0);
else transfer(select);
}
}
}
void transfer(int s)
{
int base=2;
switch(s)
{
case 1:base=2;break;
case 2:base=8;break;
case 3:base=16;break;
}
while(x> =base)
{
yu[i++]=x % base;
x=x/base;
}
yu[i]=x;
print();
}
void print()
{
System.out.printf( "\n转换之后的进制数为: ");
switch(select)
{
case 1:
while(i> =0)
System.out.print(yu[i--]);
break;
case 2:
while(i> =0)
System.out.print(yu[i--]);
break;
case 3:
while(i> =0)
{
if (yu[i]> 9) System.out.print((char)(yu[i--]+55));
else System.out.print(yu[i--]);
}break;
}
}
public static void main(String []args)
{
Transfer t=new Transfer();
t.get();
t.choose();
t.print();
}
}
------解决方案--------------------找个有ide的调试一下就知道了
------解决方案--------------------是JAVA吗??
System.out.printf ~!!??
------解决方案--------------------你没有初始化你的i变量就用了!!!
------解决方案--------------------yu[i] = x;应该是在这里运行错误
------解决方案--------------------import java.util.Scanner;
public class Transfer{
int x;
int select;
int []yu=new int[20];
int i;
void get(){
System.out.println( " ");
System.out.printf( "\t十进制转换器\n ");
System.out.printf( "1.转换成二进制数\n ");
System.out.printf( "2.转换成八进制数\n ");
System.out.printf( "3.转换成十六进制数\n ");
System.out.printf( "0.退出\n ");
System.out.println( "请输入一个十进制数据: ");
Scanner input=new Scanner(System.in);
x=input.nextInt();
System.out.println( "请选择转换方式: " );
select=input.nextInt();