Using Java 8+, you can generate the array with the squares on a single line. Assuming your array is the numeros
variable, then you can do this:
int[] quadrados = IntStream.of(numeros).map(x -> x * x).toArray();
To read the 20 numbers, you can also do with two lines:
Scanner entrada = new Scanner(System.in);
int[] numeros = IntStream.generate(entrada::nextInt).limit(20).toArray();
To display the array, you can do in a row too:
System.out.println(Arrays.toString(quadrados));
Here is the resulting complete code. Note that it is very simple, it only needs 5 lines between {
and }
of method main
:
import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.IntStream;
class Teste {
public static void main(String[] args) {
Scanner entrada = new Scanner(System.in);
int[] numeros = IntStream.generate(entrada::nextInt).limit(20).toArray();
int[] quadrados = IntStream.of(numeros).map(x -> x * x).toArray();
System.out.println(Arrays.toString(numeros));
System.out.println(Arrays.toString(quadrados));
}
}
Given this entry:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
This output is produced:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400]
See here working on ideone.
Ah, Math.sqrt(...)
is for calculating the square root. To calculate the square, the simplest way is to multiply each element by itself as in the code above. Note that the code for creating the array with the squares works regardless of the size of the original array.
If you want a message to appear to ask for the number, you can do something like this:
int[] numeros = IntStream.generate(() -> {
System.out.println("Digite um número: ");
return entrada.nextInt();
}).limit(20).toArray();