为什么在将String Array转换为int Array时会出现NumberFormatException?

问题描述 投票:1回答:4

当我在IntelliJ上运行代码时,我没有得到错误。但是,当我尝试将我的代码交给我工作的代理时,我会在两个测试用例中获得NFE。我删除了所有代码,只让下面的代码运行测试用例。在这里的某个地方必须是NumberFormatException

public class Search {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        sc.nextLine();
        int[] list = new int[n];
        String [] tokens = sc.nextLine().trim().split(" ");

        for (int i=0; i<tokens.length;i++){
            list[i]=Integer.parseInt(tokens[i]);
        }
    }
}

我阅读了有关双空格的内容并使用以下方法进行了检查:System.out.println(Arrays.asList(tokens).contains(""));输出为false,因此这不是一个选项。如你所见,我已经在使用trim()了。我很感激你的帮助。路易

Reddit:好吧,有些东西在这里很腥。我补充道

System.out.println(Arrays.asList(tokens).contains(""));
    System.out.println(Arrays.toString(tokens));

到我的代码并将其交给测试用例。虽然IntelliJ会传递false后跟一个整数数组,但测试用例输出:true []。因此,你们都是对的,我只是错误地假设我的测试用例中的输入与赋值中给出的输入I的示例类似。

Aaditi:

好的!我想到了。测试用例的输入格式与我的测试输入中的格式不同,看起来有点像这样:

10 8 8 9 12 110 111 117 186 298 321 2 8 13

我假设我包含的sc.nextLine()跳过我需要列出的整数。所以实际的问题不是额外的空格或任何东西,只是我通过使用sc.nextLine()来提升我想要的输入。答案给了我所需要的暗示,即使我认为这不是来自Andronicus。不管怎样,感谢其他人。

java numberformatexception parseint
4个回答
2
投票

如果你知道,将有一个整数作为输入而你不担心解析,为什么不使用它呢?

int input = sc.nextInt();

在您的解决方案中,您必须这样做:

Arrays.stream(sc.nextLine().trim().split(" ")).filter(s -> !s.matches("\\s")).toArray(String[]::new);
\\ or simplier
sc.nextLine().trim().split("\\s+")

2
投票

有许多可能的原因:

  1. tokens中有一个非数字 - 例如。 9 1! 3 x 3 ......
  2. 令牌被不止一个空间分开 - 例如9 3

您应该能够通过数字格式异常的文本来判断。例如,在多个空格的情况下,您将获得:

线程“main”中的异常java.lang.NumberFormatException:对于输入字符串:“”

对于非数字(例如“a”),你会得到:

线程“main”中的异常java.lang.NumberFormatException:对于输入字符串:“a”

当然,有很多可能的解决方案取决于你在遇到无效输入时想要做什么(你忽略它吗?抛出一个特殊的异常?尝试去除非数字?)

当您知道输入由空格分隔,但不知道有多少空格时,您可以使用正则表达式来定位split命令中的多个空格:

str.split("\\s+"); // splits on one or more whitespace including tabs, newlines, etc.

然后,要处理令牌列表中的非数字,您可以在for循环中添加一个检查:

for(int i = 0; i < tokens.length; i++) {
  if(tokens[i].matches("\\d+")) {
    list[i] = Integer.parseInt(tokens[i]);
  } else {
    // Handle error case for non-digit input
  }
}

1
投票

这很可能是由于数字之间有多余的空格。

例如,

9    8 7 9    1
  ^^       ^^
*Note: You have more than one spaces here.

这是分裂后阵列的外观,

tokens = {"9", "", "", "", "8", "7", "9", "", "", "", "1"}

由于额外的空间,上面将抛出NumberFormatException

你可以再次尝试trimming的内容,

int i = 0;
for (String token : tokens){
    token = token.trim();
    if (!"".equals(token)) {
        list[i++] = Integer.parseInt(token);
    }
}

0
投票

请将您的代码修改为:

public class Example {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the size of the array : ");
        int n = sc.nextInt();
        sc.nextLine();
        int[] list = new int[n];
        System.out.println("Enter a string : ");
        /** This regex will work for string having more than one space. */ 
        String trimmedToken = sc.nextLine().replaceAll("\\s+", " ");
        String[] tokens = trimmedToken.split(" ");
        for (int i = 0; i < tokens.length; i++) {
            list[i] = Integer.parseInt(tokens[i]);
            System.out.println(list[i]);
        }
        sc.close();
    }

}

控制台输入:

Enter the size of the array : 
5
Enter a string : 
1       2     3      4    5

输出:

1
2
3
4
5
© www.soinside.com 2019 - 2024. All rights reserved.