Java报错问题Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 13
代码如下:publicclassCardGame{publicstaticvoidmain(String[]args){//生成扑克牌inti,j;inta=0,b=0;...
代码如下:
public class CardGame
{
public static void main(String[] args)
{
//生成扑克牌
int i,j;
int a=0,b=0;
String[] card = new String[54];
String[] suit = new String[]{"黑桃","红心","梅花","方块"};
String[] size = new String[]{"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
System.out.println("最初的扑克:");
for(i=0; i<4; i++)
{
for(j=0; j<13; j++)
{
card[j] = suit[a] + size[b];
System.out.print(card[j]);
b++;//为什么加了这句就报错
}
System.out.println();
a++;
}
}
}
最后输出结果:
最初的扑克:
黑桃A黑桃2黑桃3黑桃4黑桃5黑桃6黑桃7黑桃8黑桃9黑桃10黑桃J黑桃Q黑桃K
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 13
at xyt.CardGame.main(CardGame.java:23)
为什么只显示了第一行 后面就报错了 展开
public class CardGame
{
public static void main(String[] args)
{
//生成扑克牌
int i,j;
int a=0,b=0;
String[] card = new String[54];
String[] suit = new String[]{"黑桃","红心","梅花","方块"};
String[] size = new String[]{"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
System.out.println("最初的扑克:");
for(i=0; i<4; i++)
{
for(j=0; j<13; j++)
{
card[j] = suit[a] + size[b];
System.out.print(card[j]);
b++;//为什么加了这句就报错
}
System.out.println();
a++;
}
}
}
最后输出结果:
最初的扑克:
黑桃A黑桃2黑桃3黑桃4黑桃5黑桃6黑桃7黑桃8黑桃9黑桃10黑桃J黑桃Q黑桃K
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 13
at xyt.CardGame.main(CardGame.java:23)
为什么只显示了第一行 后面就报错了 展开
3个回答
展开全部
public class CardGame {
public static void main(String[] args) {
int i, j;
int m =0;
String[] card = new String[54];
String[] suit = new String[] { "黑桃", "红心", "梅花", "方块" };
String[] size = new String[] { "A", "2", "3", "4", "5", "6", "7", "8",
"9", "10", "J", "Q", "K" };
String[] yn = new String[] {"大王,小王"};
System.out.println("最初的扑克:");
for (i = 0; i < suit.length; i++) {
for (j = 0; j < size.length; j++) {
card[j] = suit[i] + size[j];
if(j == size.length-1){
System.out.print(card[j]);
}else{
System.out.print(card[j]+",");
}
}
m++;
System.out.println("");
if(m == suit.length){
for(int a = 0;a < yn.length;a++){
System.out.println(yn[a]);
}
}
}
}
}
不是太明白你定义 a和b的含义,如果for循环中存在了i++的话,就没有必要在定义其他变量了,再其次不要在程序中写入定值,这样不利于后期的维护和修改,一旦出现问题就很难找到原因
展开全部
b在外层循环中没有初始化,这样第一次循环结束后,b的值为13,在数组size中取值时就会报越界错误了,在外层循环中,设定b=0的初始值就行了
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
public class CardGame
{
public static void main(String[] args)
{
//生成扑克牌
int index = 0;
String[] card = new String[54];
String[] suit = new String[]{"黑桃","红心","梅花","方块"};
String[] size = new String[]{"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
System.out.println("最初的扑克:");
for(int i=0; i<4; i++)
{
for(int j=0; j<13; j++)
{
card[index] = suit[i] + size[j];
index++;
}
}
card[52] = "小王";
card[53] = "大王";
System.out.println(Arrays.toString(card));
}
}
改的不多,你看看
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询