DEV Community

Beatriz Maciel
Beatriz Maciel

Posted on • Edited on

3 1

HackerRank #27 | 1D Array | 🇧🇷

Neste exercício devemos declarar um Array que lê n elementos.
O número de entrada é n e, depois disso, precisamos que o input peça a quantidade de números equivalente a n.

O código começa assim:

import java.util.*;

public class Solution {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();

        // .. escreva o código aqui

        scan.close();

        for (int i = 0; i < a.length; i++) {
            System.out.println(a[i]);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

=========

Para criar um novo array que só recebe int (com o nome a, como é imprimido no for a.length) a sintaxe é a seguinte:

int[] a = new int[n]

A quantidade de inputs é relativa ao número n, portanto precisamos fazer a seguinte iteração:

for (int i = 0; i < n; i++){
    a[i] = scan.nextInt();
}
Enter fullscreen mode Exit fullscreen mode

=========

O código final fica assim, dentro da main:

        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();

        int[] a = new int[n];

        for (int i = 0; i < n; i++){
            a[i] = scan.nextInt();
        }


        scan.close();

Enter fullscreen mode Exit fullscreen mode

============

Essa publicação faz parte de uma série de exercícios resolvidos em Java no HackerRank. Acesse a série completa:

Top comments (0)

Great read:

Is it Time to go Back to the Monolith?

History repeats itself. Everything old is new again and I’ve been around long enough to see ideas discarded, rediscovered and return triumphantly to overtake the fad. In recent years SQL has made a tremendous comeback from the dead. We love relational databases all over again. I think the Monolith will have its space odyssey moment again. Microservices and serverless are trends pushed by the cloud vendors, designed to sell us more cloud computing resources.

Microservices make very little sense financially for most use cases. Yes, they can ramp down. But when they scale up, they pay the costs in dividends. The increased observability costs alone line the pockets of the “big cloud” vendors.