【问题标题】:Splitting between [ , and ]在 [ 和 ] 之间分割
【发布时间】:2014-04-28 05:08:48
【问题描述】:

如果拆分项目,当我尝试在我的集合中包含“[”和“]”时出现错误。例如,我尝试了一些不同的变体,例如 '\\[',但它仍然无法正常工作。无论我尝试什么,我的 parseInt 似乎都有问题。仅使用逗号 ex: 1,12,12,13 就可以正常工作,但是当我尝试添加和使用 [] ex: [1,12,12,13] 时,我遇到了问题。 谢谢!

import java.io.IOException;
import java.util.Scanner;


public class lineStats {
public static void main(String[] args) throws IOException {
String text;
    Scanner scan = new Scanner(System.in);
    text = scan.nextLine();
    String[] numbers = text.split(",");
        int[] answer = new int[numbers.length];
        int num = 0;
for (int i = 0; i < numbers.length; i++){
    answer[i] = Integer.parseInt(numbers[i]);
                }
for(int k=0;k<numbers.length;k++){
    if(answer[k]>10){
    num=num+1;  
    }
}
System.out.println(num);
}
}

【问题讨论】:

  • 您的描述和代码似乎矛盾。请告诉我们您的输入是什么,您想要的输出是什么。

标签: java arrays string split int


【解决方案1】:

在拆分字符串之前,您可以使用如下所示的 replaceAll

text = text.replaceAll("(\[|\])", "");

【讨论】:

    【解决方案2】:

    最简单的方法是去掉所有非数字:

    answer[i] = Integer.parseInt(numbers[i].replaceAll("\\D", ""));
    

    【讨论】:

      【解决方案3】:

      您应该首先从行中删除[],然后将其拆分:

      text = scan.nextLine();
      text = text.replaceAll("\\[|\\]","");
      ...
      

      【讨论】:

        【解决方案4】:

        尝试对输入字符串进行简单替换

        text = scan.nextLine().replace ("[").replace ("]");
        String[] numbers = text.split(",");
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-08-06
          • 2021-12-31
          • 2018-09-10
          • 1970-01-01
          • 2015-08-18
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多