【问题标题】:getting an input by scanner and creating an array only using for loop not通过扫描仪获取输入并仅使用 for 循环创建数组
【发布时间】:2023-03-19 13:21:01
【问题描述】:
private static int[] arr;
public static void inputarrays() {
    Scanner scan = new Scanner(System.in);

    System.out.println("length of an array");

    int x = scan.nextInt();
    arr = new int[x];

    System.out.println("values of an array");
    for(int n = 0; n < x; x++) {
        arr[n] = scan.nextInt();
    }
}

我查找了如何编写代码来获取用户输入并创建这样的数组: Java - Creating an array from user input

看起来我的代码与链接上的代码相同,这意味着它应该可以正常工作。但是,当我输入数组的值时,扫描仪永远不会关闭。我试过scan.close(),但没有用。另外,我不能对这个使用 try&exception。

【问题讨论】:

  • 将 x++ 改为 n++
  • 我改了,但扫描仪还是没有停止
  • 在每个scan.nextInt();之后添加这一行:scan.nextLine();
  • 感谢您的编辑,下次我会按照格式进行
  • 如果我在方法内部创建一个新数组而不是在数据字段中声明它,它仍然不起作用?

标签: java arrays


【解决方案1】:

这个方法行得通,试试看:

private static int[] arr;
public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    System.out.println("length of an array");
    int x = scan.nextInt();
    scan.nextLine();
    arr = new int[x];
    System.out.println("values of an array");
    for(int n=0; n<x; n++){
        arr[n]=scan.nextInt();
        scan.nextLine();
    }
}
  1. x++ 更改为n++,因为n 是循环的索引
  2. 在每次调用 scan.nextInt() 后添加 scan.nextLine();,以便完全使用每个输入行。

【讨论】:

  • 我必须在数据字段中声明 arr 所以我把它放在方法之外。如果我保持这种方式,它会保持那个错误吗?
  • nextLine()s 在这里是多余的。
  • arr is 在第一行的问题中声明。
  • @Ivar 我是这么认为的,但是 2 次中有 1 次我在没有 nextLine() 的情况下运行代码;在 InteliJ 中,循环不会停止。
  • @Ivar 当您将输入与 nextLine() 和 nextInt() 混合时,肯定会出现问题。在只使用 nextInt() 的情况下,我也从来没有遇到过问题。但它可能会发生,只是为了安全起见......
【解决方案2】:

您在循环中使用了n,因此您必须使用n++ 而不是x++

private static int[] arr;
public static void inputarrays() {
    Scanner scan = new Scanner(System.in);

    System.out.println("length of an array");

    int x = scan.nextInt();
    arr = new int[x];
    System.out.println("values of an array");
    for(int n = 0; n < x; n++) {
        arr[n] = scan.nextInt();
    }
}

它应该以这种方式工作。

【讨论】:

  • 这个答案在其他答案中没有任何内容。
猜你喜欢
  • 1970-01-01
  • 2015-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多