即使我不关心nextLine()
方法,这些代码行也会产生问题。我仍然无法弄明白为什么。我已经检查了我的代码的其他部分,我想出了这个部分,我怀疑。
int value;
int capacity;
int choice;
int testValue;
int index;
ArrayList<IntBag> bags = new ArrayList<IntBag>();
choice = 0;
testValue = 0;
Scanner scan = new Scanner( System.in );
while( choice != 9 )
{
value = 0;
index = 0;
System.out.println( "\n*********\n1.Create a new empty collection"
+ " with a specified maximum capacity\n2.Read a set "
+ "of positive values into the collection\n3.Print the"
+ " collection of values.\n4.Add a value to the collection"
+ " of values at a specified locaiton\n5.Remove the value at"
+ " a specified location from the collection of values\n6.Read "
+ "a single test value.\n7.Compute the set of locations of the "
+ "test value within the collection\n8.Print the set of locations."
+ "\n9.Quit the program.");
System.out.print( "\nChoice: " );
choice = scan.nextInt();
if( choice == 1 )
{
System.out.print( "\nPlease enter the capacity: " );
capacity = scan.nextInt();
if( capacity > 0 )
{
bags.add( new IntBag( capacity ) );
System.out.println( "\nCollection has successfully created!" );
}
else
System.out.println( "\nInvalid capacity!");
}
if( !bags.isEmpty() )
{
if( choice == 2 )
{
int input;
System.out.print( "\nPlease enter the value you want to assign(use 0 to finish): " );
for( int i = 0; i < bags.get(0).size(); i++ )
{
input = scan.nextInt();
if( input != 0 )
{
System.out.println( i + ": " );
bags.get(0).add( input );
}
else
break;
}
它实际上应该寻找0以外的任何输入(0终止它),但是,即使没有接近这一点,这个问题也开始发生。
注意:bags只是一个ArrayList
对象,它具有我编写的类的泛型类型。它基本上代表了一个整数数组,我认为它并不构成这个问题的任何内容。
编辑:它跳过for循环中的最后一个input = scan.nextInt();
行。
谢谢!
答案 0 :(得分:2)
您在每个号码后按回车键。因此,当您键入数字后跟返回键时,扫描程序将数字视为一个输入,同时作为另一个输入输入,因此跳过下一个整数。
您应该在一行中输入所有数字,然后按Enter或更好地使用nextLine
方法,然后将该字符串转换为整数。