Error with Java arrays

Asked

Viewed 90 times

5

Could someone tell me what’s wrong with this code? The result is always the first number before the space, but has to be the sum of all 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);
  }
}
  • Always 1? No! I just took a test and gave 2. Always give the first number of the sequence.

2 answers

4


Change this:

String x = entrada.next();

therefore

String x = entrada.nextLine();

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

More detailed explanation

A complete token, returned by next(), is a token that meets the delimiting pattern specified in the Scanner. Since no pattern has been specified, then the space between the numbers remains a delimiter.

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

Already in the case at nextLine a line pattern is used. See 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;
}
  • 1

    +1 - Very good explanation, congratulations!

2

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

nextLine takes everything that was typed.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.