1-D arrays: store, index, and traverse · Arrays 1-D: armazenar, indexar e percorrer
Many values in one box
- An array holds many values of the same type in order.
- Until now one variable held one value. An array holds a whole list.
- For example, the test scores of a class can live in one
intarray.
Muitos valores em uma única caixa
- Um array guarda muitos valores do mesmo tipo em ordem.
- Até agora uma variável guardava um valor. Um array guarda uma lista inteira.
- Por exemplo, as notas de uma turma podem viver em um único array
int.
Make an array with values
- If you know the values, list them in curly braces
{ }. - The type is the element type plus
[], likeint[]. - Java counts how many values you gave and makes the array that size.
Criar um array com valores
- Se você souber os valores, liste-os entre chaves
{ }. - O tipo é o tipo dos elementos mais
[], comoint[]. - O Java conta quantos valores você deu e faz o array desse tamanho.
public class Main {
public static void main(String[] args) {
int[] scores = {90, 80, 70};
System.out.println(scores[0]); // 90
System.out.println(scores[2]); // 70
}
}
Index positions
- Each value has an index (its position). Indexes start at 0.
- So the first value is
scores[0], the second isscores[1], and so on. - You can also change a value:
scores[1] = 85;.
Posições de índice
- Cada valor tem um índice (sua posição). Os índices começam em 0.
- Então o primeiro valor é
scores[0], o segundo éscores[1], e assim por diante. - Você também pode alterar um valor:
scores[1] = 85;.
public class Main {
public static void main(String[] args) {
int[] scores = {90, 80, 70};
scores[1] = 85; // change the middle value
System.out.println(scores[1]); // 85
}
}
Make an empty array
- Use
new int[n]to make an array ofnvalues. - Every
intslot starts at 0 automatically. - Then you fill the slots one by one.
Criar um array vazio
- Use
new int[n]para criar um array denvalores. - Cada slot de
intcomeça em 0 automaticamente. - Depois você preenche os slots um por um.
public class Main {
public static void main(String[] args) {
int[] nums = new int[3]; // {0, 0, 0}
nums[0] = 5;
nums[1] = 6;
System.out.println(nums[0] + " " + nums[1] + " " + nums[2]); // 5 6 0
}
}
.length
array.lengthtells you how many values the array has.- Note: no parentheses — it is
scores.length, notscores.length(). - The last valid index is always
length - 1.
.length
array.lengthdiz quantos valores o array tem.- Nota: sem parênteses — é
scores.length, nãoscores.length(). - O último índice válido é sempre
length - 1.
public class Main {
public static void main(String[] args) {
int[] scores = {90, 80, 70};
System.out.println(scores.length); // 3
System.out.println(scores[scores.length - 1]); // 70 (last value)
}
}
Traverse with a for loop
- To visit every value, loop the index from
0up tolength - 1. - Use
i < array.lengthas the stop test. - Below we add up every value.
Percorrer com um laço for
- Para visitar cada valor, faça o loop do índice de
0atélength - 1. - Use
i < array.lengthcomo o teste de parada. - Abaixo somamos todos os valores.
public class Main {
public static void main(String[] args) {
int[] scores = {90, 80, 70};
int total = 0;
for (int i = 0; i < scores.length; i++) {
total = total + scores[i];
}
System.out.println(total); // 240
}
}
Enhanced for loop
- The enhanced for (or "for-each") visits each value directly.
- Read it as: "for each
int vinscores". - Use it when you only need the values, not the index.
Laço enhanced for
- O enhanced for (ou "for-each") visita cada valor diretamente.
- Leia como: "para cada
int vemscores". - Use-o quando precisar apenas dos valores, não do índice.
public class Main {
public static void main(String[] args) {
int[] scores = {90, 80, 70};
int total = 0;
for (int v : scores) {
total = total + v;
}
System.out.println(total); // 240
}
}
Common mistakes
a.lengthhas no(); valid indexes run0toa.length - 1.- Going out of range throws ArrayIndexOutOfBoundsException.
Erros comuns
a.lengthnão tem(); índices válidos vão de0aa.length - 1.- Passar do intervalo lança ArrayIndexOutOfBoundsException.
Now you try
- Some tasks print a result; others complete a method the Harness calls.
- Remember: indexes start at 0, and the last index is
length - 1. - Press Run to compile, then Check answer.
Agora você tenta
- Algumas tarefas imprimem um resultado; outras completam um método que o Harness chama.
- Lembre-se: os índices começam em 0, e o último índice é
length - 1. - Pressione Run para compilar, depois Check answer.
A 1-D array, indexed · Um array 1-D, indexado
An array stores values in order; reach one with a[i]. · Um array armazena valores em ordem; acesse um com a[i].
The array nums is already filled. Use a loop to add up all its values and print the total on one line. For {4, 8, 15, 16, 23, 42} the output is 108. · O array nums já está preenchido. Use um laço para somar todos os seus valores e imprimir o total em uma linha. Para {4, 8, 15, 16, 23, 42} a saída é 108.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Complete sum(int[] a) so it returns the sum of all values in the array. An empty array should return 0. The checker calls it with several arrays. · Complete sum(int[] a) para que ele retorne a soma de todos os valores no array. Um array vazio deve retornar 0. O verificador o chama com vários arrays.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Complete doubleAll(int[] a). It does not return anything. Instead it changes the array in place so every value becomes twice as big. {1, 2, 3} becomes {2, 4, 6}. · Complete doubleAll(int[] a). Ele não retorna nada. Em vez disso, altera o array in loco para que todo valor dobre. {1, 2, 3} torna-se {2, 4, 6}.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.