跳过没有任何 nextLine 的 nextInt - Java

Skipping nextInt without any nextLine - Java

即使我不关心那个 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 对象,它具有我编写的 class 的通用类型。它基本上表示一个整数数组,我认为它不构成任何有关此问题的内容。

编辑:它跳过 for 循环中的最后 input = scan.nextInt(); 行。

谢谢!

您在每个数字后按 return 键。因此,当您键入数字后跟 return 键时,扫描仪将数字视为一个输入,而将输入视为另一个输入,因此会跳过下一个整数。

您应该在一行中输入所有数字,然后按回车键,或者最好使用 nextLine 方法,然后将该字符串转换为整数。