weixin_45125091 2019-12-19 14:20 采纳率: 0%
浏览 676
已采纳

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;
    }

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

  • 写回答

3条回答 默认 最新

  • zxf-nobug 2019-12-19 15:59
    关注

    不可以,因为用的是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());
        }
      }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?