0

I'm splitting a string of numbers separated by spaces like this :

Integer.valueOf(input.split(" ")[i]);

But if the user inputs 1 2 3 4 5, 2 3 4 5 (there's a space in front of the two) is what comes out. Why is this?
I've tried adding a space to the front of the string with input = " " + input but it just turns out two spaces in front of the 2.

scan.next();
String input = scan.nextLine();
System.out.println(input);
System.out.println(Integer.valueOf(
        input.split(" ")[0]));
for(int i = 0; i < input.length() - 1; i++) {
        nums[i] = Integer.valueOf(
              input.split(" ")[i]);
}
IHazABone
  • 525
  • 2
  • 6
  • 20
  • Please share your whole code. How do you output the integers? – MinecraftShamrock Feb 16 '15 at 20:22
  • And what is the range of your `i`? – RealSkeptic Feb 16 '15 at 20:23
  • 2
    I bet there's a line above that says `for (int i = 1; i < 5; i++)`. – aioobe Feb 16 '15 at 20:24
  • The range of i is how many numbers the user chooses to input. length + 1 or -1 don't work either. To output it, I'm doing `System.out.println(Integer.valueOf(input.split(" ")[i]));`, but when I use a for loop to assign each element to an element of the array, I get a NumberFormatException on "", where the first number should be. – IHazABone Feb 16 '15 at 20:29
  • And gods no I'm not declaring `i` as 1 – IHazABone Feb 16 '15 at 20:30
  • Not sure how it's a duplicate of that. That's just removing whitespaces. I need to get each number separated by the spaces and add them to an array. – IHazABone Feb 16 '15 at 20:33
  • If you want spaces and numbers in your array, then technically its not a number anymore but a string. – WonderWorld Feb 16 '15 at 20:36
  • Yeah, I trim them in a line after what I posted. Could have put it in the loop, I guess. Doesn't make a difference to my problem. – IHazABone Feb 16 '15 at 20:41
  • Since split uses a regular expression can you use [^0-9] to split on everything that is not a number? – NathanOliver Feb 16 '15 at 20:46
  • 2
    What is the `scan.next()` at the beginning of the code for? What is the actual input? – RealSkeptic Feb 16 '15 at 20:55
  • I don't believe this code will run. Are you sure that you are not getting an `ArrayIndexOutOfBoundsException` because `input.length` is going to be more than size of `input.split( " " )`. Also... why are you calling `.split` each time... `.split` is relatively expansive... so you should call it once and assign a variable to it... `Array[ String ] splitted = input.split( " " )` and use this `splitted` in rest of code. – sarveshseri Feb 16 '15 at 21:15
  • And @RealSkeptic is right... that `scan.next()` is the culprit... but this code will not run. – sarveshseri Feb 16 '15 at 21:25
  • I'll try what Sarvesh has suggested, but no, it wouldn't run. I had overlooked that because it still crashes assigning the first element. `scan.next()` is because I use `scan.nextInt()` frequently beforehand and going right from that to `scan.nextLine()` without clearing the scanner returns a blank String. I'll try with the regex that Nathan has suggested as well. – IHazABone Feb 17 '15 at 03:36
  • Also, why the downvote? It's helpful if you explain with a comment, as at the moment I'm disabled from asking questions and that's annoying. – IHazABone Feb 17 '15 at 03:37

2 Answers2

-2

I am assuming you are asking the user to input a sequence of numbers in a single line. So you might get 1 , 2 3 , 52 as the inputted value as a string. You want to store the numbers into an int array. A way to do this is take the string and remove all characters that have nothing to do with the numbers, in this case it are spaces and komma's. There would be a problem if someone enters a 1 , 4 59, but i am ignoring that scenario because it has nothing to do with the question.

String line = scanner.nextLine(); // line = "1 , 2 3 ,  45"

Remove the komma's first:

String result = line.replaceAll("," , " "); // replaces all komma's with a space.

Now you have a string with no komma's To avoid double digit numbers to be converted into 2 single digits, you can use a StringTokenizer.

 StringTokenizer st = new StringTokenizer("this is a test");
     while (st.hasMoreTokens()) {
         System.out.println(st.nextToken());
     }

prints out:

this

is

a

test

We can use this to remove the whitespaces between the numbers in our string or actually only use the values that are read as tokens.

        StringTokenizer resultLine = new StringTokenizer(result);
        int[] numbers = new int[resultLine.countTokens()];
        for (int i = 0; resultLine.hasMoreTokens(); i++) {
            numbers[i] = Integer.parseInt((String) resultLine.nextElement());
        }
        for (int j = 0; j < numbers.length; j++) {
            System.out.print(numbers[j] + " ");
        }
        System.out.println();
    }

Which finally gets us the result we want, an array of integers.

    Scanner s = new Scanner(System.in);
    while (s.hasNext()) {
    String line = s.nextLine();
    String result = line.replaceAll(",", " ");
    StringTokenizer resultLine = new StringTokenizer(result);
    int[] numbers = new int[resultLine.countTokens()];
    for (int i = 0; resultLine.hasMoreTokens(); i++) {
        numbers[i] = Integer.parseInt((String) resultLine.nextElement());
    }
    for (int j = 0; j < numbers.length; j++) {
        System.out.print(numbers[j] + " ");
    }
    System.out.println();
}

Input was: 1 , 2 3 , 52

Output is: 1 2 3 52 // int[] numbers = {1,2,3,52};

I hope this is of some use to you.

WonderWorld
  • 956
  • 1
  • 8
  • 18
  • `String result = input.replaceAll("\\s+",","); String testResult[] = result.split(",");` will be better. – sarveshseri Feb 16 '15 at 21:24
  • why check for the `","`? – WonderWorld Feb 16 '15 at 21:26
  • 1
    Please elaborate, don't just post code without context or explanation. In particular here, what's the point in removing all whitespace? Why not just do `input.split("\\s+")`? Your solution limits valid inputs to single digits. – dimo414 Feb 16 '15 at 21:27
  • Well... lets take the case where the input was `1 34 55 66 76`... Do you get it now? – sarveshseri Feb 16 '15 at 21:27
  • Hmm you are right, didnt look at double digit cases. – WonderWorld Feb 16 '15 at 21:28
  • 1
    Again, why call `replaceAll()` at all? `String.split()` takes a regex, you can simply pass `"\\s+"` straight to it. – dimo414 Feb 16 '15 at 21:30
  • @dimo414 i changed the post and implemented Sarvesh his solution. – WonderWorld Feb 16 '15 at 21:30
  • And the question remains: why do you replace something here? – Tom Feb 16 '15 at 21:35
  • I didn't downvote, but replacing the whitespace is overkill when it exists as a proper standalone delimiter. I'd eliminate that entirely. – Drew Kennedy Feb 16 '15 at 21:38
  • @Tom Because the OP says there is a space in front of the 2, which can't be there if he wants an array of integers. – WonderWorld Feb 16 '15 at 21:38
  • @DrewKennedy you are right. I am not that familiar with all the functions that are available to `Scanner` – WonderWorld Feb 16 '15 at 21:42
  • 1
    @Xbit What do you think is the difference between `result.split(",");` and `input.split("\\s+");`? And keep in mind that OP is `Scanner` incorrectly, so the whitespace(s) in front of *2* are not there, after fixing that problem. – Tom Feb 16 '15 at 21:51
  • @Tom that depends on the input you get, if there isn't a `","` where there should be or if there is a whitespace where it shouldn't be then the program will not run. – WonderWorld Feb 16 '15 at 21:57
  • Thats why i agree with Drew and use the `useDilimiter()` function of the scanner to catch all possible inputs between the actual numbers. – WonderWorld Feb 16 '15 at 22:08
  • Same problem and error. NumberFormatException on "". Issue is the scanner, then. – IHazABone Feb 17 '15 at 03:41
-2

When asking "Why doesn't this work the way I expect?" and similar questions, it's always very helpful to provide an MVCE so we can replicate what you're seeing.

Assuming scan is a Scanner and you're not doing additional input processing before the lines you pasted, the unused called to scan.next(), which advances the scanner past the first token of input, is what's muddling your input. Try commenting out that line and input should contain the whole line of text.

Community
  • 1
  • 1
dimo414
  • 47,227
  • 18
  • 148
  • 244
  • I hadn't realized that it did that. Thanks. Problem is, beforehand I use a much of scan.nextInt(), and converting it all to nextLine would be quite a lot of effort. Is there any way of making it work? – IHazABone Feb 16 '15 at 21:59
  • 1
    If you post an SSCCE that we can run, we can try to replicate your problem and offer solutions. Going off of a code snippet that doesn't compile (posted in your question) and "I use a much of scan.nextInt()" there's little advice to give. – dimo414 Feb 16 '15 at 22:02
  • @dimo414 Then why are you breaking my balls over something that you in the first place find an insufficient post? – WonderWorld Feb 16 '15 at 22:05
  • @Xbit sorry what? All I did was try to clarify why you were calling `String.replaceAll()` since it didn't seem relevant. What am I "breaking your balls" over? – dimo414 Feb 16 '15 at 22:10
  • Nevermind, i'm being stupid again. :) I overlooked the scanner part. I mean if you let the scanner read the line of input, you will get a string returned. My example works with that string, but you can solve this way easier with Scanner functions. – WonderWorld Feb 16 '15 at 22:15
  • 1
    Downvoters, I'm always open to feedback. Personally, this is better than a -2-worthy answer, but if you disagree, please let me know why. – dimo414 Feb 17 '15 at 00:34
  • Probably those guys who downvoted didnt even post a comment. – WonderWorld Feb 17 '15 at 10:15