【问题标题】:Count entered numbers which are separated by space计算以空格分隔的输入数字
【发布时间】:2012-11-26 20:39:01
【问题描述】:

我不知道如何处理以下问题。

我有一个输入供用户输入,他们可以输入各种数字,这些数字用空格分隔,例如(20 30 89 ..) 我需要计算输入了多少个数字(在这种情况下输入了 3 个数字) 我该怎么做?

我假设这背后的逻辑类似于计算空格数并将其加 1(其前面没有空格的初始数字),但我不确定如何通过代码执行此操作。 最好检查是否在第一个数字之前输入了空格,如果是,则不要将 + 1 添加到最终计数中,还要检查诸如双空格、三空格等内容并将它们计为一个空格。最后看看最后是不是没有空格(所以没有加起来)。

这是我目前得到的(用户输入):

package temperature;

import java.util.*;

/**
 * @author --
 */
public class Histogram {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        // Input for grades
        Scanner input = new Scanner(System.in);
        System.out.println("Enter temperatures below (separated by spaces e.g. 20 30 89 ..)");
        int temperature = input.nextInt();
    }
}

【问题讨论】:

  • 您可以将数字添加到数组或列表中并检查列表的大小。或者在读取新的 int 时简单地增加一个计数器。

标签: java string count split java.util.scanner


【解决方案1】:
  • 只需使用Scanner#nextLine() 方法阅读整行。
  • 在一个或多个spaces 上拆分读取行 - 使用+ 量词 那
  • 然后得到得到的array的长度。

这是一个例子:-

if (scanner.hasNextLine()) {
    int totalNumbers = scanner.nextLine().split("[ ]+").length;
}

【讨论】:

    【解决方案2】:

    如果只计算空格,则最终可能会以数字形式出现任何垃圾数据。我的建议是阅读所有输入,直到你到达一个空格字符。然后尝试将其转换为整数(或双精度),如果转换失败,对无效输入进行错误处理,否则增加计数器。

    一个例子是这样的:

    // Sample input used.
        String input = "23 54 343 75.6 something 22.34 34 whatever 12";
        // Each number will be temporarily stored in this variable.
        Double numberInput;
        // Counter used to keep track of the valid number inputs.
        int counter = 0;
        // The index directly after the number ends.
        int endIndex = 0;
        // Now we simply loop through the string.
        for (int beginIndex = 0; beginIndex < input.length(); beginIndex = endIndex + 1) {
            // Get the index of the next space character.
            endIndex = input.indexOf(" ", beginIndex);
            // If there are no more spaces, set the endIndex to the end of the string.
            if (endIndex == -1) {
                endIndex = input.length();
            }
            // Take out only the current number from the input.
            String numberString = input.substring(beginIndex, endIndex);
            try {
                // If the number can be converted to a Double, increase the counter.
                numberInput = Double.parseDouble(numberString);
                counter++;
            } catch (java.lang.NumberFormatException nfe) {
                // Some error handling.
                System.err.println("Invallid input: " + numberString);
            }
        }
        System.out.println("Total valid numbers entered: " + counter);
    

    输出:

    Invalid input: something
    Total valid numbers entered: 7
    Invalid input: whatever
    

    编辑:抱歉,我打开了答案窗口,没有看到其他回复。拆分功能应该做得很好:)

    【讨论】:

      【解决方案3】:

      可以按空格分割,统计元素个数:

          System.out.println("20".split (" ").length);
          System.out.println("20 30".split (" ").length);
      

      这将分别打印 1 和 2。

      这是一个fiddle

      【讨论】:

      • 我做了 System.out.println(grades.split(" ").length);我收到错误消息:无法取消引用 int
      【解决方案4】:

      这是我的解决方案。它比使用 Split 方法的解决方案要长一点,但它只会在结果中包含数值。所以对于以下输入:

      12 32 234 555 24 sdf 4354 dsf34r34 rfedfg 4353
      

      该函数将在数组中返回以下值:

      12
      32
      234
      555
      24
      4354
      4353
      

      函数如下:

      private static String[] getWholeNumbers(String input) {
          ArrayList<String> output = new ArrayList<String>();
      
          Pattern pattern = Pattern.compile("\\b\\d+\\b");
          Matcher matcher = pattern.matcher(input);
          while (matcher.find()) {
              output.add(matcher.group());
          }
          return output.toArray(new String[output.size()]);
      }
      

      如果您只需要计数,也可以轻松更改该功能。

      【讨论】:

        【解决方案5】:

        如果您可以将输入作为字符串然后从字符串中检索数字会更好。

        Scanner input=new Scanner(System.in);
        String st=input.nextLine();
        String[] split=st.split(" ");
        ArrayList<Integer> temp=new ArrayList<>();
        String regex="^[0-9]+$";
             for(int i=0;i<split.length;i++)
             {
                 if(split[i].matches(regex)) temp.add(Integer.parseInt(split[i]));
             }
        

        现在你得到了所有温度为ArrayList&lt;Integer&gt;

        【讨论】:

          猜你喜欢
          • 2016-03-12
          • 2012-10-17
          • 2017-07-12
          • 1970-01-01
          • 2015-08-17
          • 2021-06-12
          • 1970-01-01
          • 1970-01-01
          • 2014-12-05
          相关资源
          最近更新 更多