java - 如何将 "[]"的字符串转换为整数数组

标签 java string get

我有两个字符串:

String s1 = "[143, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 157, 158, 159, 162, 163, 164]";

String s2 = "[20, 35, 74, 78, 124, 125, 126, 127, 131, 132, 143, 144, 145, 146]";

我想做的就是找到这两个字符串中最小的公共(public)数。所以我首先替换“[]”符号,并将字符串中的数字提取为整数。然后用循环求最小公共(public)数。程序如下:

s1 = s1.replace("[",""); 
s1 = s1.replace("]","");
String [] band = s1.split(",");     
s2 = s2.replace("[",""); 
s2 = s2.replace("]","");
String [] hotel = s1.split(",");    
System.out.println( EarliestCommonSlot(hotel,band) );

EarliestCommonSlot() 定义如下:

public static int EarliestCommonSlot(String [] a1, String [] b1){
    int i=0,j=0;
    int common = -1;
    int [] a = new int [a1.length];
    int [] b = new int [b1.length];

    for(i = 0;i < a1.length;i++)
    {
        a[i] = Integer.parseInt( a1[i]);
        System.out.println(a1[i]);
    }
    for(i = 0;i < b1.length;i++)
    {
        b[i] = Integer.parseInt( b1[i]);
        System.out.println(b1[i]);
    }
    i = 0; j=0;
    while ( i< a.length && j < b.length){
        if ( a[i] == b[j] ){
            common = a[i]; break;
        }
        if ( a[i] < b[j] ){
            i++;
        }
        else j++;
    }
    return common;
}

但是当我运行程序时,出现以下错误:

Exception in thread "main" java.lang.NumberFormatException: For input string: " 143"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:481)
    at java.lang.Integer.parseInt(Integer.java:527)
    at ClientReserve.EarliestCommonSlot(ClientReserve.java:39)
    at ClientReserve.main(ClientReserve.java:179)

这是为什么呢?我该如何解决这个问题?

最佳答案

而不是

s1.replace("]"," "); // This replaces the bracket with a space.
                     // The number with the space will emit the error

用途:

s1.replace("]","");//This replaces the bracket with an empty string.
<小时/>

新代码:

s1 = s1.replace("[",""); 
s1 = s1.replace("]","");
String [] band = s1.split(", ");     
s2 = s2.replace("[",""); 
s2 = s2.replace("]","");
String [] hotel = s1.split(", ");    //Comma and a space. Thanks to SaviourSelf
System.out.println( EarliestCommonSlot(hotel,band) );

关于java - 如何将 "[]"的字符串转换为整数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36403745/

相关文章:

c++ - 字符串中的匹配序列

javascript - 如何在外部使用 Angular 6 subscribe() 方法的结果?

javascript - 如何使用 JQuery 从远程元素获取 img src 和文本?

java - 使用 dbUnit 模拟触发器

java - 如何使用 gradle 调试 spring 应用程序

string - 如何在 slice 中写入函数的结果

javascript - 我有一个字符串,想使用 javascript 删除其特定部分中的特殊字符

javascript - jQuery 如果不起作用?

java - Gmail 作为 JavaMail SMTP 服务器

java - 在自己的线程中运行 JPanel。