循环不会重复我想要的方式

循环不会重复我想要的方式

本文介绍了"为"循环不会重复我想要的方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得的从用户3曲棍球运动员的名字和球衣号码。然后,我从我的叫HockeyPlayer与我有数据创建的类使对象。然后,我把它放入数组。第二迭代不起作用。请帮忙!谢谢你在前进。

 的ArrayList< HockeyPlayer>阵列=新的ArrayList< HockeyPlayer>();// for循环输入名称
的for(int i = 0;我3;;我++)
{
    System.out.print(+ I +玩家的输入名称:);
    startName = keyboard.nextLine();
    System.out.print(输入球衣号球员的+ I +:);
    playNum = keyboard.nextInt();    //使对象,并添加到阵列
    HockeyPlayer P =新HockeyPlayer(startName,playNum);
    array.add(P);
}
keyboard.close();


解决方案

这里的问题是,在你的循环的每一个迭代中,您对 nextLine()通话,然后调用 nextInt(),但你拨打电话到后nextInt(),换行字符有没有被读出。基本上,如果输入的是一样的东西。

首先玩家姓名
1
第二个玩家名称
2

那么,你的循环的第一次迭代之后,扫描刚刚看完了 1 ,但其后不要换行权。因此,在第二次迭代中, nextLine()涉及换行后 1 ,但的那个换行符。然后, nextInt()通话将力图把 INT ,并抛出了 InputMismatchException时

它周围的打算常见的方法是要么把另一个 nextLine()拨打呼叫之后nextInt()(并扔掉这个额外的换行符),或只是读与数量都在同一个呼叫一旦行 nextLine(),并解析出 INT 使用的Integer.parseInt()

I am trying to get the name and jersey number of 3 hockey players from the user. I then make an object from my created class called HockeyPlayer with the data I have. I then put it into the array. The second iteration does not work. Please help! Thank you in advance.

ArrayList<HockeyPlayer> array = new ArrayList<HockeyPlayer>();

//For loop to input names
for(int i=0; i < 3; i++)
{
    System.out.print("Enter name of Player " + i +":");
    startName = keyboard.nextLine();
    System.out.print("Enter jersey number of Player " + i +":");
    playNum = keyboard.nextInt();

    //Make objects and add to array
    HockeyPlayer p = new HockeyPlayer(startName, playNum);
    array.add(p);
}
keyboard.close();
解决方案

The problem here is that in every iteration of your loop, you make a call to nextLine(), then a call to nextInt(), but after you make the call to nextInt(), the newline character has not been read. Basically, if the input is something like

First Player Name
1
Second Player Name
2

then, after the first iteration of your loop, the Scanner has just finished reading in the 1, but not the newline right after it. Hence, in the second iteration, the nextLine() deals with the newline after 1, but only that newline. Then, the nextInt() call will try to turn Second into an int, and throws the InputMismatchException.

Common ways of going around it are to either put another nextLine() call right after the call to nextInt() (and just throw away this extra newline), or to just read in the line with the number all at once with a call to nextLine(), and parse out the int using Integer.parseInt().

这篇关于&QUOT;为&QUOT;循环不会重复我想要的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 17:05