System.out.println("请输入访问元素,以空格隔开");如果我用逗号隔开元素可以执行吗?

代码如下:

private static int[] input() {
        System.out.println("请输入有多少个访问元素:");
        Scanner s = new Scanner(System.in);
        int num = s.nextInt();
        System.out.println("请输入访问元素,以空格隔开");
        int[] arr = new int[num]; // 用来保存输入的页面数据
        for (int i = 0; i < num; i++) {
            arr[i] = s.nextInt();
        }
        return arr;
    }

要求以空格隔开,那么假如我用逗号隔开元素,是否依旧可以运行呢?为什么?谢谢!

不可以,因为用的是nextInt,传入的必须是int类型,如果用其他的是可以的


  public int nextInt(int paramInt)
  {
    if ((this.typeCache != null) && ((this.typeCache instanceof Integer)) && (this.radix == paramInt))
    {
      int i = ((Integer)this.typeCache).intValue();
      useTypeCache();
      return i;
    }
    setRadix(paramInt);
    clearCaches();
    try
    {
      String str = next(integerPattern());
      if (this.matcher.group(this.SIMPLE_GROUP_INDEX) == null) {
        str = processIntegerToken(str);
      }
      return Integer.parseInt(str, paramInt);
    }
    catch (NumberFormatException localNumberFormatException)
    {
      this.position = this.matcher.start();
      throw new InputMismatchException(localNumberFormatException.getMessage());
    }
  }

不可以,会报错,自己可以试一下,具体原因不清楚,应该是java定义的吧,空格可以当作分割。

会报返回数据类型错误,可以点进去看看System类和Scanner类的源码就知道啥原因了