【问题标题】:Splitting a String of a large negative number and putting it into a LinkedList拆分大负数的字符串并将其放入 LinkedList
【发布时间】:2014-06-21 18:50:10
【问题描述】:

这是我的方法,但是当我尝试为负数运行它时,我得到一个 NumberFormatException 输入“-”。

public newObj(String s)
{
    list = new LinkedList<Integer>();
    String[] splitted = s.split("\\d");

    int[] ints = new int[splitted.length];

    for (int i = 0; i < splitted.length - 1; i++) {
        ints[i] = Integer.parseInt(splitted[i]);
    }

    for (int j = 0; j < ints.length - 1; j++) {
        list.add(ints[j]);
    }

}

我的输入字符串只是一个数字,如“-123456”或“12345”。正数工作,但我不能让负数工作。

对于我的否定输入字符串,我希望我的列表类似于 [-1,-2,-3,-4,-5,-6]。

【问题讨论】:

  • (per Ren8888) "你的输入字符串是什么?"

标签: java string parsing integer


【解决方案1】:

它会用数字模式分割数字,所以如果你有-123

例如:

String str = "-123";
System.out.println(Arrays.toString(str.split("\\d")));

输出

[-]

- 无法解析为int

来自 cmets:

对于像-123456 这样的输入,op 希望将其设为正数

你可以这样做

Math.abs(Integer.parseInt(inputString))

让它解析负数,然后你可以使用Math.abs()得到它的绝对值

与 cmets 相距甚远

op 想要分割每个数字并应用符号,你可以做类似的事情

    String str = "-123";
    int numbers[] = null;
    int characterIndex = 0;
    boolean isNegative = false;

    if (str.trim().startsWith("-")) {
        characterIndex = 1;
        isNegative = true;
        numbers = new int[str.length() - 1];
    } else {
        numbers = new int[str.length()];

    }

    for (int numIndex = 0; characterIndex < str.length(); characterIndex++, numIndex++) {
        numbers[numIndex] = Integer.parseInt(str.substring(characterIndex, characterIndex + 1));
        if (isNegative) {
            numbers[numIndex] = -1 * numbers[numIndex];
        }

    }
    System.out.println(Arrays.toString(numbers));

注意:错误处理留给你

【讨论】:

  • 当我将它添加到列表时,我是否可以跳过“-”,然后在添加到列表时将每个数字乘以 -1?
  • 你的输入字符串样本是什么样的?
  • 样本将是“-123456”,但我还必须处理像“123456”这样的正数
  • 对不起,我不是说我想把它转换成正数。我的意思是输入字符串可以是正数或负数。截至目前,我的代码适用于正数,但我无法让它适用于负数。我想我有一个解决我的问题的方法,但我只是不知道一种方法来解析一个负数的字符串并将其拆分为单独的负整数。
  • 你可以用同样的方法简单地解析负数,例如Integer.parseInt("-123")会返回int-123
猜你喜欢
  • 1970-01-01
  • 2020-09-06
  • 2015-01-07
  • 2020-08-26
  • 2023-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-23
相关资源
最近更新 更多