Pregunta

I'm getting an error when I try to include '[' and ']' in my collection if split items. I've tried a few different variations like '\\[' for example but its still not working. It seems to have a problem with my parseInt with whatever I try. It works fine with just the comma ex: 1,12,12,13 but when I try to add and use [] ex: [1,12,12,13] I run into problems. Thanks!

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);
}
}
¿Fue útil?

Solución 2

The easy way is to strip out all non-digits:

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

Otros consejos

Before splitting string you could use replaceAll like below

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

you should first remove [ and ] from line and then split it:

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

try a simple replace on the input String

text = scan.nextLine().replace ("[").replace ("]");
String[] numbers = text.split(",");
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top