Error with arrays in Java

5

Could someone tell me what's wrong with this code? The result is always the 1st number before space, but it has to be the sum of all the numbers in the array.

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
    @SuppressWarnings("resource")
    Scanner entrada = new Scanner(System.in);
    String x = entrada.next();
    String array[] = x.split (" ");
    int soma = 0;
    int resultado[] = new int[array.length];
    for (int i = 0; i < array.length; i++) {
        resultado[i] = Integer.parseInt(array[i]);
        soma = soma + resultado[i];
    }
    System.out.println (soma);
  }
}
    
asked by anonymous 05.08.2015 / 01:09

2 answers

4

Change this:

String x = entrada.next();

so

String x = entrada.nextLine();

Your code is not working, because next () returns the next full token. In this case, the 1st number before space. The nextLine () returns all characters up to the line break character.

More detailed explanation

A full token, returned by next () , is a token that meets the delimitation pattern specified in the Scanner. Since no pattern was specified, then the space between the numbers becomes a delimiter.

So when you type 1 2 3 and use next () , it returns character 1, because the space after the number 1 served as a delimiter.

Already in the nextLine case a line pattern is used. See the nextLine () function taken from the source code of the Scanner class.

public String nextLine() {
    if (hasNextPattern == linePattern())
        return getCachedResult();
    clearCaches();

    String result = findWithinHorizon(linePattern, 0);
    if (result == null)
        throw new NoSuchElementException("No line found");
    MatchResult mr = this.match();
    String lineSep = mr.group(1);
    if (lineSep != null)
        result = result.substring(0, result.length() - lineSep.length());
    if (result == null)
        throw new NoSuchElementException();
    else
        return result;
}
    
05.08.2015 / 01:20
2

What is happening is that entrada.next(); returns the next word, but in the context of that application it would be entrada.nextLine();

nextLine takes everything typed.

    
05.08.2015 / 01:18