【问题标题】:for loop runs once without accepting any input for array [duplicate]for循环运行一次而不接受数组的任何输入[重复]
【发布时间】:2022-12-04 07:49:03
【问题描述】:

此代码中的 for 循环在不接受输入的情况下运行一次。没有 do-while 循环和用户输入 shopList 数组长度,它运行没有问题。

import java.util.Arrays;
import java.util.Scanner;

/**
 *
 * @author cristian
 */
public class ShoppingList {

    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.println("How many items in this list?");
        
        boolean okay;
        do{
            if (sc.hasNextDouble()) {
            okay = true;
            }else{
            okay = false;
            String word = sc.next(); //this may be the problem here
            System.err.print( word + " is not a number\nTry again: ");
            }
        }while (!okay);
        int l = sc.nextInt();              //the problem appeared the first time when I added this input
        String[] shopList = new String[l]; //to give the length of this array
        System.out.println("What do you want to buy?");
        for (int x = 0 ; x < shopList.length; x++) { //this loop runs once without accepting input
            System.out.print("Item: ");
            String item = sc.nextLine();
            if (item.equals("esc")) {
                break;
            }else{
                shopList[x] = item;
                //System.out.println(x);
            }
        }
        System.out.println(Arrays.toString(shopList));
    }
}

当我将“l”变量添加到数组长度以接受来自用户的输入时,问题首先出现。然后我将其注释掉并添加了一个 do-while 循环以确保长度的输入是一个数字,这又带来了另一个问题。

发生的情况是,当两者都没有被注释掉或者如果只注释掉 do-while 循环时,在我输入数组长度后,它打印出“Item:Item:”,它接受一个少的项目,最后它输出第一项就像我刚刚按下回车一样,没有写任何东西。 如果我只注释掉数组长度的输入,程序会在运行循环之前等待输入,并将其用于第一项。

我认为对于 do-while 循环,问题是“String word = sc.next();”但我不确定。至于数组长度输入,我不知道。有人可以帮忙吗?

【问题讨论】:

    标签: java arrays loops user-input


    【解决方案1】:

    看起来问题出在 for 循环中的 nextLine() 方法上。当您调用 nextInt() 读取数组长度时,它只读取整数值并将换行符留在输入缓冲区中。当 for 循环开始并调用 nextLine() 时,它会读取这个换行符并且循环继续而不等待用户输入。

    要解决此问题,您可以在调用 nextInt() 之后添加对 nextLine() 方法的调用,以消耗输入缓冲区中剩余的换行符。例如:

    int l = sc.nextInt();
    sc.nextLine(); // consume remaining newline character
    String[] shopList = new String[l];
    
    

    或者,您可以更改 for 循环以使用 nextInt() 方法而不是 nextLine() 来从用户读取项目索引。这也将消耗输入缓冲区中的换行符。例如:

    for (int x = 0 ; x < shopList.length; x++) {
        System.out.print("Item: ");
        int itemIndex = sc.nextInt();
        if (itemIndex == "esc") {
            break;
        } else {
            shopList[x] = itemIndex;
            //System.out.println(x);
        }
    }
    

    希望这可以帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多