【问题标题】:Read integer array through white space with using limit in java在java中使用limit通过空格读取整数数组
【发布时间】:2014-11-27 09:16:21
【问题描述】:

我的要求是:

输入的第一行包含一个整数 n(其中 n>=3)表示数组的大小。在下一行中,将有 n 个整数,由空格分隔,对应于数组中的 n 个元素。为此,我使用了以下代码:

Scanner length = new Scanner(System.in);
         System.out.println("Please Enter Length of Aarry:");
         int n=length.nextInt();
         int[] numbers = new int[n];


        Scanner sc = new Scanner(System.in);



        System.out.println("Enter the elements seperated by spaces: ");
        String input = sc.nextLine();
        StringTokenizer strToken = new StringTokenizer(input);
        int count = strToken.countTokens();
        //Reads in the numbers to the array
        System.out.println("Count: " + n);
        int[] arr = new int[n];

        for(int x = 0;x < n;x++){
            arr[x] = Integer.parseInt((String)strToken.nextElement());
            System.out.println("values are: " + arr[x]);

        }

但问题是:上面的代码将正确读取所有用空格输入的整数,但我也想指定输入值的限制。请帮助我如何实现这一点。

【问题讨论】:

  • 不清楚你想要什么。如果用户输入的数字(令牌)过多,您想向用户显示错误信息吗?
  • @StijnGeukens 我认为 OP 想在阅读 n 数字后停止阅读输入。
  • @johny 我认为他现在已经这样做了,但是如果 n > count 会失败
  • @StijnGeukens 我们现在可以输入比n 更多的数字,但数组arr 中只有n 个值。但我认为 OP 想阻止我们输入比n 更多的号码。
  • @johnny 如果用户输入的数字少于 n,它将抛出 NoSuchElementException

标签: java arrays string java.util.scanner


【解决方案1】:

有几种方法可以解决您的“问题”:

  • 最简单:根本不询问数组的长度 => 长度 = #tokens
  • 验证:if (n != count) System.err.println("Invalid input...")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-29
    • 1970-01-01
    • 2014-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-26
    相关资源
    最近更新 更多