JavaJava · Chapterبەش 9 · Lectureوانە 9.1
Arrays in One and Two Dimensionsڕیزەکەکان لە یەک و دوو ڕەهەنددا
Java arrays: many values of one type under one name, with a fixed length. Create them with { } or new (and their default values), read and change elements by index from 0, loop with for and for-each, the ArrayIndexOutOfBoundsException and NullPointerException, printing with Arrays.toString, two names for one array and real copies, == versus Arrays.equals, sort and fill, arrays in methods (removing an element into a new, shorter array, and five more practice methods) and String[] args, and two-dimensional arrays with nested loops.
Java: چەندین یەک جۆر لە ژێر یەک ناودا، بە درێژییەکی جێگیر. دروستکردنیان بە { } یان new (و )، خوێندنەوە و گۆڕینی بە لە 0ـەوە، سووڕانەوە بە for و ، ArrayIndexOutOfBoundsException و NullPointerException، چاپکردن بە Arrays.toString، دوو ناو بۆ یەک و کۆپیی ڕاستەقینە، == بەرامبەر Arrays.equals، sort و fill، لە (لابردنی بۆ نوێی کورتتر لەگەڵ پێنج تری ڕاهێنان) و String[] args و بە .
What you will learnچی فێر دەبیت
- Create arrays with { } and with new, and know their default values.
- Read, change and loop over elements by index, and avoid the index and null errors.
- Explain why an array variable holds a reference, and copy and compare arrays correctly.
- Use Arrays.toString, sort, fill, equals and copyOf, and pass arrays to and from methods.
- Write methods that build new arrays: remove an element, merge, rotate, add two arrays and drop duplicates.
- Store a table in a two-dimensional array and process it with nested loops.
- بە { } و بە new دروست بکەیت و بزانیت.
- بە بخوێنیتەوە، بگۆڕیت و بەسەریاندا بسووڕێیتەوە و خۆت لە هەڵەکانی و null بپارێزیت.
- ڕوون بکەیتەوە بۆچی هەڵدەگرێت و بە دروستی کۆپی و بەراورد بکەیت.
- Arrays.toString، sort، fill، equals و copyOf بەکار بهێنیت و بنێریت بۆ و لێیانەوە وەربگریت.
- بنووسیت کە نوێ دروست دەکەن: لابردنی ، یەکخستن، سووڕاندن، کۆکردنەوەی دوو و لابردنی دووپاتەکان.
- خشتەیەک لە هەڵبگریت و بە کاری لەسەر بکەیت.
Many values, one nameچەندین نرخ، یەک ناو
Five students sat a Java test. With what you know so far, five marks need five variables, and every calculation must name each one:
پێنج قوتابی تاقیکردنەوەیەکی Javaـیان کرد. بەوەی تا ئێستا دەیزانیت، پێنج نمرە پێنج پێویستن و هەموو ژمێرکارییەک دەبێت ناوی یەک بە یەکیان بهێنێت:
public class FiveMarks {
public static void main(String[] args) {
int mark1 = 90, mark2 = 75, mark3 = 88, mark4 = 62, mark5 = 95;
int total = mark1 + mark2 + mark3 + mark4 + mark5;
System.out.println("Total: " + total);
}
}$ java FiveMarks Total: 410
For a class of 40 that is hopeless. An keeps many values of one type under one name, in numbered places. Each value is an , and its place number is its :
بۆ پۆلێکی 40 کەسی ئەمە ناکرێت. چەندین یەک جۆر لە ژێر یەک ناودا هەڵدەگرێت، لە شوێنی ژمارەداردا. هەر و ژمارەی شوێنەکەی :
Creating an array and reading an elementدروستکردنی ڕیزەکێک و خوێندنەوەی دانەیەک
int[] marks declares a variable whose type is array of int (the brackets belong to the type). Values in braces, {90, 75, 88, 62, 95}, create the array and fill it. marks[2] reads the element at index 2:
int[] marks دەناسێنێت کە جۆرەکەی intـە (کەوانە چوارگۆشەکان بەشێکن لە جۆرەکە). لە ناو کەوانەدا، {90, 75, 88, 62, 95}، دروست دەکەن و پڕی دەکەنەوە. marks[2] 2 دەخوێنێتەوە:
public class Marks {
public static void main(String[] args) {
int[] marks = {90, 75, 88, 62, 95};
System.out.println("First mark: " + marks[0]);
System.out.println("Third mark: " + marks[2]);
System.out.println("Last mark: " + marks[4]);
System.out.println("How many: " + marks.length);
}
}$ java Marks First mark: 90 Third mark: 88 Last mark: 95 How many: 5
length - 1نمرەی سێیەم 2ـی هەیە؛ دوایین length - 1ـەCêITJava counts from 0, like Python and C (Indexes in notation); MATLAB counts from 1 (Reaching one element). int marks[] also compiles, a leftover from C, but Java programmers write int[] marks.
Java لە 0ـەوە دەژمێرێت، وەک Python و C (ئیندێکسەکان لە نیشانەکاندا)؛ MATLAB لە 1ـەوە دەژمێرێت (گەیشتن بە یەک دانە). int marks[]ـیش کۆمپایل دەبێت، پاشماوەیەکی Cـیە، بەڵام بەرنامەسازانی Java دەنووسن int[] marks.
Changing an element; the lengthگۆڕینی دانەیەک؛ درێژی
An element is used like a variable: assign to it with =, or read it in a calculation. cities.length gives the number of elements, so the last index is cities.length - 1:
وەک بەکار دێت: بە = تێ بخە، یان لە ژمێرکارییەکدا بیخوێنەوە. cities.length ژمارەی دەدات، بۆیە دوایین cities.length - 1ـە:
public class ChangeMark {
public static void main(String[] args) {
int[] marks = {90, 75, 88, 62, 95};
marks[1] = 80; // Shilan's paper was marked again
marks[3] = marks[3] + 5; // a bonus of 5 for the fourth student
System.out.println(marks[1] + " " + marks[3]);
String[] cities = {"Hawler", "Duhok", "Halabja"};
cities[2] = "Zakho";
System.out.println(cities[0] + ", " + cities[1] + ", " + cities[2]);
System.out.println(cities.length + " cities, last index " + (cities.length - 1));
}
}$ java ChangeMark 80 67 Hawler, Duhok, Zakho 3 cities, last index 2
length is a field of the array, written without brackets. A String uses the method length() with brackets (length). Mixing them up gives cannot find symbol:
length خانەیەکی و بەبێ کەوانە دەنووسرێت. String length() بە کەوانەوە بەکار دەهێنێت (length). تێکەڵکردنیان دەدات cannot find symbol:
$ javac LengthCall.java
LengthCall.java:5: error: cannot find symbol
System.out.println(marks.length());
^
symbol: method length()
location: variable marks of type int[]
LengthCall.java:6: error: cannot find symbol
System.out.println(name.length);
^
symbol: variable length
location: variable name of type String
2 errorsVisiting every element with forسەردانی هەموو دانەیەک بە for
A counting for loop (The for loop) visits the indexes 0, 1, 2 … one after another. With i < marks.length as the condition it works for an array of any length:
ژماردن (خولی for) 0، 1، 2 … یەک لە دوای یەک سەردان دەکات. بە i < marks.length وەک بۆ بە هەر درێژییەک کار دەکات:
public class SumMarks {
public static void main(String[] args) {
int[] marks = {90, 75, 88, 62, 95};
int sum = 0;
for (int i = 0; i < marks.length; i++) {
sum += marks[i];
System.out.println("i = " + i + " mark = " + marks[i] + " sum = " + sum);
}
double average = (double) sum / marks.length;
System.out.println("Average: " + average);
}
}$ java SumMarks i = 0 mark = 90 sum = 90 i = 1 mark = 75 sum = 165 i = 2 mark = 88 sum = 253 i = 3 mark = 62 sum = 315 i = 4 mark = 95 sum = 410 Average: 82.0
![An animation. The code int sum = 0; for (int i = 0; i < marks.length; i++) { sum += marks[i]; } next to the array 90, 75, 88, 62, 95. A pointer i moves from box 0 to box 4; the visited boxes turn blue, and the variable sum grows 90, 165, 253, 315, 410. In the last frame i is 5, the test 5 < 5 is false and the loop ends: average = 410 / 5 = 82.0.](/_astro/java-arrays-array-loop.en.B74KQt8c.gif)
![An animation. The code int sum = 0; for (int i = 0; i < marks.length; i++) { sum += marks[i]; } next to the array 90, 75, 88, 62, 95. A pointer i moves from box 0 to box 4; the visited boxes turn blue, and the variable sum grows 90, 165, 253, 315, 410. In the last frame i is 5, the test 5 < 5 is false and the loop ends: average = 410 / 5 = 82.0.](/_astro/java-arrays-array-loop.ckb.aMtSnXU_.gif)
i walks from 0 to length - 1 while sum collects the marksi لە 0ـەوە تا length - 1 دەڕوات و sum نمرەکان کۆ دەکاتەوەCêITThe cast (double) sum makes the division exact (Where the cast goes). Use <, not <=: with <= the loop also asks for index 5 and the program stops (Off by one).
کاستی (double) sum دابەشکردنەکە ورد دەکات (کاست لە کوێ دادەنرێت). < بەکار بهێنە، نەک <=: بە <= داوای 5ـیش دەکات و دەوەستێت (یەکێک زیاتر یان کەمتر).
The for-each loopخولی foreach
When you need every element but not its index, the is shorter (A first look). Read for (int mark : marks) as "for each int mark in marks":
کاتێک پێویستت بە هەموو هەیە بەڵام نەک بە ، کورترە (یەکەم سەیرکردن). for (int mark : marks) وا بخوێنەوە: «بۆ هەر int markـێک لە ناو marks»:
public class ForEachMarks {
public static void main(String[] args) {
int[] marks = {90, 75, 88, 62, 95};
int sum = 0;
for (int mark : marks) {
sum += mark;
}
System.out.println("Sum: " + sum);
String[] names = {"Aram", "Shilan", "Karwan"};
for (String name : names) {
System.out.println("Hello, " + name);
}
}
}$ java ForEachMarks Sum: 410 Hello, Aram Hello, Shilan Hello, Karwan
The loop variable gets a copy of each element, so changing it changes nothing in the array. This program shows both loops:
کۆپییەکی هەر وەردەگرێت، بۆیە گۆڕینی هیچ شتێک لە ناگۆڕێت. ئەم هەردوو نیشان دەدات:
import java.util.Arrays;
public class ForEachCopy {
public static void main(String[] args) {
int[] marks = {90, 75, 88};
for (int mark : marks) {
mark = mark + 5; // changes only the copy in mark
}
System.out.println(Arrays.toString(marks));
for (int i = 0; i < marks.length; i++) {
marks[i] = marks[i] + 5; // changes the array itself
}
System.out.println(Arrays.toString(marks));
}
}$ java ForEachCopy [90, 75, 88] [95, 80, 93]
new: an array of a given lengthnew: ڕیزەکێک بە درێژییەکی دیاریکراو
When the values come later (from the keyboard, a file, a calculation), create the array with new and a length: int[] counts = new int[5];. Java fills every place with a at once:
کاتێک دواتر دێن (لە ، ، ژمێرکارییەک)، بە new و درێژییەک دروست بکە: int[] counts = new int[5];. Java یەکسەر هەموو شوێنێک بە پڕ دەکاتەوە:
import java.util.Arrays;
public class Defaults {
public static void main(String[] args) {
int[] counts = new int[5];
double[] prices = new double[3];
boolean[] answers = new boolean[3];
String[] names = new String[3];
System.out.println(Arrays.toString(counts));
System.out.println(Arrays.toString(prices));
System.out.println(Arrays.toString(answers));
System.out.println(Arrays.toString(names));
char[] letters = new char[2];
System.out.println((int) letters[0]);
}
}$ java Defaults [0, 0, 0, 0, 0] [0.0, 0.0, 0.0] [false, false, false] [null, null, null] 0
A char starts as '\u0000', the character with code 0, which prints as nothing, so the program prints its number. The length is fixed when the array is made: it can be a variable (new int[n]), but it never changes afterwards. A new object starts with the same default values (Default values of an object).
char بە '\u0000' دەست پێ دەکات، ئەو کۆدەکەی 0ـە و هیچ چاپ ناکات، بۆیە ژمارەکەی چاپ دەکات. درێژی لە کاتی دروستکردنی جێگیر دەبێت: دەتوانێت بێت (new int[n])، بەڵام دواتر هەرگیز ناگۆڕێت. نوێش بە هەمان دەست پێ دەکات (نرخە بنەڕەتییەکانی ئۆبجێکتێک).
new: an array of a given lengthnew: ڕیزەکێک بە درێژییەکی دیاریکراو
An empty slot: nullشوێنی چۆڵ: null
In a String[] the default is null: an empty slot with no String in it yet. Printing it shows null, but calling a method on it stops the program with a NullPointerException:
لە String[]ـدا nullـە: شوێنی چۆڵ، هێشتا هیچ Stringـێکی تێدا نییە. چاپکردنی null نیشان دەدات، بەڵام بانگکردنی لەسەری بە NullPointerException دەوەستێنێت:
public class Names {
public static void main(String[] args) {
String[] names = new String[3];
names[0] = "Aram";
names[1] = "Shilan";
for (int i = 0; i < names.length; i++) {
System.out.println(i + ": " + names[i]);
}
System.out.println(names[2].length());
}
}$ java Names 0: Aram 1: Shilan 2: null Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "<local1>[2]" is null at Names.main(Names.java:9)
Since Java 15 (JEP 358) the message names the empty place. <local1> means local variable number 1 (here names), because plain javac does not store variable names in the class file. Compiled with javac -g, the same run says because "names[2]" is null. Fill every element before you use it, or check if (names[i] != null).
لە Java 15ـەوە (JEP 358) پەیامەکە ناوی شوێنە چۆڵەکە دەبات. <local1> واتە ژمارە 1 (لێرەدا names)، چونکە javacـی ئاسایی ناوی لە فایلی classـدا هەڵناگرێت. ئەگەر بە javac -g کۆمپایل بکرێت، هەمان جێبەجێکردن دەڵێت because "names[2]" is null. هەموو پێش بەکارهێنانی پڕ بکەرەوە، یان if (names[i] != null) بپشکنە.
Outside the array: ArrayIndexOutOfBoundsExceptionدەرەوەی ڕیزەکەکە: ArrayIndexOutOfBoundsException
Every index is checked while the program runs. An index below 0 or at length or above stops the program with an that names the index and the length (Reading a stack trace):
هەموو لە کاتی کارکردنی دەپشکنرێت. لە خوار 0 یان لە length و سەرووتر بە دەوەستێنێت کە ناوی و درێژییەکە دەبات (خوێندنەوەی stack trace):
public class Bounds {
public static void main(String[] args) {
int[] marks = {90, 75, 88, 62, 95};
System.out.println(marks[4]);
System.out.println(marks[5]);
}
}$ java Bounds 95 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5 at Bounds.main(Bounds.java:5)
Java has no negative indexes: marks[-1] is not the last element, as in Python, but the same exception. The most common cause is <= in a loop header; this loop prints all three marks, then asks for index 3:
Java نییە: marks[-1] وەک Python دوایین نییە، بەڵکو هەمان . باوترین هۆکار <=ـە لە سەرەی ؛ ئەم هەر سێ نمرەکە چاپ دەکات، پاشان داوای 3 دەکات:
public class OffByOne {
public static void main(String[] args) {
int[] marks = {90, 75, 88};
for (int i = 0; i <= marks.length; i++) {
System.out.println(marks[i]);
}
}
}$ java OffByOne 90 75 88 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3 at OffByOne.main(OffByOne.java:5)
Printing an array: Arrays.toStringچاپکردنی ڕیزەکێک: Arrays.toString
System.out.println(marks) does not print the marks. It prints the type and a code for the object: [I means array of int, [Ljava.lang.String; array of String, and the part after @ is a number in hexadecimal. Arrays.toString from java.util prints the elements:
System.out.println(marks) نمرەکان چاپ ناکات. جۆرەکە و کۆدێک بۆ چاپ دەکات: [I واتە int، [Ljava.lang.String; String و بەشی دوای @ ژمارەیەکە بە . Arrays.toString لە java.utilـەوە چاپ دەکات:
import java.util.Arrays;
public class PrintArray {
public static void main(String[] args) {
int[] marks = {90, 75, 88, 62, 95};
String[] names = {"Aram", "Shilan"};
System.out.println(marks);
System.out.println(names);
System.out.println(Arrays.toString(marks));
System.out.println(Arrays.toString(names));
}
}$ java PrintArray [I@7344699f [Ljava.lang.String;@6b95977 [90, 75, 88, 62, 95] [Aram, Shilan]
Two names, one arrayدوو ناو، یەک ڕیزەک
An array is an object, and an array variable holds a to it, not the elements themselves (arrays are ). So int[] b = a; copies the reference: a and b are two names for one array, and a change through b is seen through a:
و بۆی هەڵدەگرێت، نەک خودی ( ). بۆیە int[] b = a; کۆپی دەکات: a و b دوو ناون بۆ یەک و گۆڕانکاری لە ڕێگەی bـەوە لە aـشەوە دەبینرێت:
import java.util.Arrays;
public class SharedArray {
public static void main(String[] args) {
int[] a = {10, 20, 30};
int[] b = a; // b is a second name for the same array
b[0] = 99;
System.out.println("a: " + Arrays.toString(a));
System.out.println("b: " + Arrays.toString(b));
System.out.println("a == b: " + (a == b));
}
}$ java SharedArray a: [99, 20, 30] b: [99, 20, 30] a == b: true
![An animation in five steps. 1: int[] a = {10, 20, 30}; the variable a points at an array of three ints. 2: int[] b = a; a second arrow from b points at the same array: two names, one array. 3: b[0] = 99; the first box becomes 99, so a[0] is 99 too. 4: int[] c = Arrays.copyOf(a, a.length); a new array 99, 20, 30 appears, with c pointing at it. 5: c[0] = 5; only the copy changes: c is 5, 20, 30 and a is still 99, 20, 30.](/_astro/java-arrays-copy-trap.en.BFj_rKgl.gif)
![An animation in five steps. 1: int[] a = {10, 20, 30}; the variable a points at an array of three ints. 2: int[] b = a; a second arrow from b points at the same array: two names, one array. 3: b[0] = 99; the first box becomes 99, so a[0] is 99 too. 4: int[] c = Arrays.copyOf(a, a.length); a new array 99, 20, 30 appears, with c pointing at it. 5: c[0] = 5; only the copy changes: c is 5, 20, 30 and a is still 99, 20, 30.](/_astro/java-arrays-copy-trap.ckb.DFRxH-t7.gif)
The same happens with Python lists (Two names, one list). It is not a bug: passing one big array around without copying it is fast. Just make a real copy when you need two separate arrays. Every object works this way (Two variables, one object).
هەمان شت لەگەڵ Python ڕوو دەدات (دوو ناو، یەک لیست). ئەمە نییە: گواستنەوەی گەورە بەبێ کۆپیکردن خێرایە. تەنیا کاتێک کۆپییەکی ڕاستەقینە دروست بکە کە پێویستت بە دوو جیا هەیە. هەموو بەم شێوەیە کار دەکات (دوو گۆڕاو، یەک ئۆبجێکت).
Two names, one arrayدوو ناو، یەک ڕیزەک
A real copy: Arrays.copyOfکۆپییەکی ڕاستەقینە: Arrays.copyOf
Arrays.copyOf(a, length) makes a new array with the elements of a. With a bigger length the new places get default values; with a smaller one the copy is cut. (a.clone() or a loop also copy.)
Arrays.copyOf(a, length) نوێ بە a دروست دەکات. بە درێژییەکی گەورەتر شوێنە نوێیەکان وەردەگرن؛ بە درێژییەکی بچووکتر کۆپییەکە دەبڕدرێت. (a.clone() یان کۆپی دەکەن.)
import java.util.Arrays;
public class CopyArray {
public static void main(String[] args) {
int[] a = {10, 20, 30};
int[] c = Arrays.copyOf(a, a.length); // a new array with the same values
c[0] = 5;
System.out.println("a: " + Arrays.toString(a));
System.out.println("c: " + Arrays.toString(c));
System.out.println("a == c: " + (a == c));
int[] longer = Arrays.copyOf(a, 5); // two more places, filled with 0
int[] shorter = Arrays.copyOf(a, 2); // only the first two
System.out.println("longer: " + Arrays.toString(longer));
System.out.println("shorter: " + Arrays.toString(shorter));
}
}$ java CopyArray a: [10, 20, 30] c: [5, 20, 30] a == c: false longer: [10, 20, 30, 0, 0] shorter: [10, 20]
This is also the only way to "grow" an array: copy it into a longer one and keep the new one in the same variable. When this happens often, use an ArrayList, which grows by itself:
ئەمە تاکە ڕێگەشە بۆ «گەورەکردنی» : کۆپیی بکە بۆ یەکێکی درێژتر و نوێیەکە لە هەمان هەڵبگرە. کاتێک ئەمە زۆر ڕوو دەدات، ArrayList بەکار بهێنە کە خۆی گەورە دەبێت:
import java.util.Arrays;
public class AddMark {
public static void main(String[] args) {
int[] marks = {90, 75, 88, 62, 95};
marks = Arrays.copyOf(marks, marks.length + 1); // a new, longer array
marks[marks.length - 1] = 70; // the new mark goes in the last place
System.out.println(Arrays.toString(marks) + " length " + marks.length);
}
}$ java AddMark [90, 75, 88, 62, 95, 70] length 6
Two names, one arrayدوو ناو، یەک ڕیزەک
Comparing arrays: == or Arrays.equalsبەراوردکردنی ڕیزەکەکان: == یان Arrays.equals
== asks whether two variables refer to the same array. Two different arrays with equal elements are not ==. Arrays.equals compares the length and every element:
== دەپرسێت ئایا دوو ئاماژە بە هەمان دەکەن. دوو جیاواز بە یەکسان == نین. Arrays.equals درێژی و هەموو بەراورد دەکات:
import java.util.Arrays;
public class CompareArrays {
public static void main(String[] args) {
int[] x = {1, 2, 3};
int[] y = {1, 2, 3};
System.out.println("x == y: " + (x == y));
System.out.println("x.equals(y): " + x.equals(y));
System.out.println("Arrays.equals(x, y): " + Arrays.equals(x, y));
}
}$ java CompareArrays x == y: false x.equals(y): false Arrays.equals(x, y): true
It is the same trap as comparing strings with == (Comparing strings): for objects, use a method that compares the contents.
هەمان تەڵەی بەراوردکردنی بە ==ـە (بەراوردکردنی زنجیرەنووسەکان): بۆ ، بەکار بهێنە کە ناوەڕۆک بەراورد بکات.
The Arrays class: sort, fill, toStringکلاسی Arrays: sort، fill، toString
The class Arrays in java.util holds ready-made static methods for arrays (The Java API). Arrays.sort puts the elements in order, Arrays.fill gives every element the same value:
Arrays لە java.utilـدا ئامادەی بۆ هەیە (APIـی Java). Arrays.sort ڕیز دەکات و Arrays.fill هەمان دەداتە هەموو :
import java.util.Arrays;
public class ArraysTools {
public static void main(String[] args) {
int[] marks = {90, 75, 88, 62, 95};
Arrays.sort(marks);
System.out.println(Arrays.toString(marks));
String[] names = {"Shilan", "Aram", "Karwan", "Dilan"};
Arrays.sort(names);
System.out.println(Arrays.toString(names));
int[] seats = new int[6];
Arrays.fill(seats, -1); // -1 = an empty seat
System.out.println(Arrays.toString(seats));
}
}$ java ArraysTools [62, 75, 88, 90, 95] [Aram, Dilan, Karwan, Shilan] [-1, -1, -1, -1, -1, -1]
sort changes the array itself and returns nothing. Words are sorted by their character codes, so capitals come first: {"shilan", "Aram", "karwan", "Dilan"} becomes [Aram, Dilan, karwan, shilan]. How sorting works inside, and sorting in other orders, comes in Sorting and searching and Sorting algorithms.
sort خودی دەگۆڕێت و هیچ ناگەڕێنێتەوە. وشەکان بەپێی کۆدی ڕیز دەکرێن، بۆیە پیتی گەورە یەکەم دێت: {"shilan", "Aram", "karwan", "Dilan"} دەبێتە [Aram, Dilan, karwan, shilan]. لە ناوەوە چۆن کار دەکات و بە ڕیزی تر لە ڕیزکردن و گەڕان و ئەلگۆریزمەکانی ڕیزکردنـدا دێن.
A program: marks from the keyboardبەرنامەیەک: نمرە لە کیبۆردەوە
Now a complete program: read five marks into an array, then use it three times: for the average, the best mark and the number of students above the average. Without the array the third loop would be impossible, because the marks would be gone (Scanner):
ئێستا تەواو: پێنج نمرە بخوێنەوە بۆ ناو ، پاشان سێ جار بەکاری بهێنە: بۆ ناوەند، باشترین نمرە و ژمارەی ئەو قوتابیانەی لە سەرووی ناوەندن. بەبێ سێیەم مەحاڵ دەبوو، چونکە نمرەکان نەمابوون (Scanner):
import java.util.Scanner;
public class ReadMarks {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] marks = new int[5];
for (int i = 0; i < marks.length; i++) {
System.out.print("Mark of student " + (i + 1) + ": ");
marks[i] = input.nextInt();
}
int sum = 0;
int best = marks[0];
for (int mark : marks) {
sum += mark;
if (mark > best) {
best = mark;
}
}
double average = (double) sum / marks.length;
System.out.println("Average: " + average);
System.out.println("Best mark: " + best);
int above = 0;
for (int mark : marks) {
if (mark > average) {
above++;
}
}
System.out.println(above + " students are above the average.");
}
}$ java ReadMarks Mark of student 1: 90 Mark of student 2: 75 Mark of student 3: 88 Mark of student 4: 62 Mark of student 5: 95 Average: 82.0 Best mark: 95 3 students are above the average.
best starts as the first mark, not as 0: with all marks negative (say, temperatures in winter) a start of 0 would be wrong. The same pattern with an index finds where the best value is (see the exercises).
best بە نمرەی یەکەم دەست پێ دەکات، نەک بە 0: ئەگەر هەموو بن (بۆ نموونە پلەی گەرمی لە زستاندا) دەستپێکردن بە 0 هەڵە دەبێت. هەمان شێواز بە دەدۆزێتەوە باشترین لە کوێیە (ڕاهێنانەکان ببینە).
Arrays and methodsڕیزەکەکان و میتۆدەکان
A method can take an array as a (int[] numbers) and can return one (return type int[]) (Methods). Because the method gets the reference, it can change the caller's array; an int parameter is only a copy (pass by value):
دەتوانێت وەک وەربگرێت (int[] numbers) و دەتوانێت یەکێک بگەڕێنێتەوە ( int[]) (میتۆدەکان). چونکە وەردەگرێت، دەتوانێت بانگکەر بگۆڕێت؛ int تەنیا کۆپییەکە (ناردن بە نرخ):
import java.util.Arrays;
public class ArrayMethods {
static double average(int[] numbers) {
int sum = 0;
for (int n : numbers) {
sum += n;
}
return (double) sum / numbers.length;
}
static void addBonus(int[] numbers, int bonus) {
for (int i = 0; i < numbers.length; i++) {
numbers[i] += bonus; // changes the caller's array
}
}
static void addBonusToOne(int mark, int bonus) {
mark += bonus; // changes only the copy in mark
}
static int[] squares(int n) {
int[] result = new int[n];
for (int i = 0; i < n; i++) {
result[i] = (i + 1) * (i + 1);
}
return result;
}
public static void main(String[] args) {
int[] marks = {90, 75, 88};
System.out.println("Average: " + average(marks));
addBonus(marks, 2);
System.out.println("After addBonus: " + Arrays.toString(marks));
addBonusToOne(marks[0], 50);
System.out.println("After addBonusToOne: " + Arrays.toString(marks));
System.out.println("squares(5): " + Arrays.toString(squares(5)));
}
}$ java ArrayMethods Average: 84.33333333333333 After addBonus: [92, 77, 90] After addBonusToOne: [92, 77, 90] squares(5): [1, 4, 9, 16, 25]
Arrays and methodsڕیزەکەکان و میتۆدەکان
Removing an element: a new, shorter arrayلابردنی دانەیەک: ڕیزەکێکی نوێی کورتتر
An array cannot shrink either. To "remove" the element at an index, a method makes a new array one place shorter and copies the others into it: the elements before the index keep their places, and each element after it moves one place to the left. The method returns the new array:
بچووکیش نابێتەوە. بۆ «لابردنی» ئەو لە ، نوێ دروست دەکات کە یەک شوێن کورتترە و ئەوانی تری تێدا کۆپی دەکات: پێش لە شوێنی خۆیان دەمێننەوە و هەر دوای ئەو یەک شوێن بەرەو چەپ دەچێت. نوێ دەگەڕێنێتەوە:
import java.util.Arrays;
public class RemoveElement {
static int[] removeAt(int[] array, int index) {
if (index < 0 || index >= array.length) {
throw new IndexOutOfBoundsException("Index " + index + " is not in the array");
}
int[] result = new int[array.length - 1]; // one place shorter
for (int i = 0; i < index; i++) { // before the index: the same place
result[i] = array[i];
}
for (int i = index + 1; i < array.length; i++) { // after it: one place to the left
result[i - 1] = array[i];
}
return result;
}
public static void main(String[] args) {
int[] numbers = {3, 8, 5, 2, 10};
int[] shorter = removeAt(numbers, 2);
System.out.println("Before: " + Arrays.toString(numbers));
System.out.println("After removing index 2: " + Arrays.toString(shorter));
removeAt(numbers, 7);
}
}$ java RemoveElement Before: [3, 8, 5, 2, 10] After removing index 2: [3, 8, 2, 10] Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 7 is not in the array at RemoveElement.removeAt(RemoveElement.java:6) at RemoveElement.main(RemoveElement.java:23)
The if at the top refuses an index outside the array: throw stops the method with an exception, as Java itself does for numbers[7] (throw comes later). The original array does not change. An ArrayList does all of this for you with remove(index).
ifـەکەی سەرەوە دەرەوەی ڕەت دەکاتەوە: throw بە ڕادەگرێت، هەروەک خودی Java بۆ numbers[7] دەیکات (throw دواتر دێت). سەرەکی ناگۆڕێت. ArrayList هەموو ئەمە بە remove(index) بۆت دەکات.
Arrays and methodsڕیزەکەکان و میتۆدەکان
String[] args: the array in mainString[] args: ڕیزەکەکە لە mainـدا
Now you can read the header public static void main(String[] args): main receives an array of strings. It holds the words typed after the class name in the terminal:
ئێستا دەتوانیت سەرەی public static void main(String[] args) بخوێنیتەوە: main وەردەگرێت. ئەو وشانەی تێدایە کە لە لە دوای ناوی نووسراون:
public class Greet {
public static void main(String[] args) {
System.out.println("args.length = " + args.length);
for (String name : args) {
System.out.println("Hello, " + name + "!");
}
}
}$ java Greet Aram Shilan args.length = 2 Hello, Aram! Hello, Shilan! $ java Greet args.length = 0
Two-dimensional arrays: rows and columnsڕیزەکە دووڕەهەندەکان: ڕیز و ستوون
A timetable, a seating plan or a table of marks has rows and columns. A stores such a table. The type has two pairs of brackets, the values are given row by row, and an element is reached with two indexes, row first, then column:
خشتەی وانەکان، نەخشەی دانیشتن یان خشتەی نمرەکان و هەیە. خشتەیەکی لەو جۆرە هەڵدەگرێت. جۆرەکەی دوو جووت کەوانەی چوارگۆشەی هەیە، بە دەدرێن و بە دوو دەگەیتە : یەکەم ، پاشان :
public class Timetable {
public static void main(String[] args) {
String[][] timetable = {
{"Maths", "Java", "English"}, // row 0: Saturday
{"Physics", "Maths", "Java"}, // row 1: Sunday
{"English", "Kurdish", "Java"} // row 2: Monday
};
System.out.println(timetable[1][2]); // Sunday, third lesson
System.out.println(timetable[2][0]); // Monday, first lesson
timetable[0][2] = "Sport"; // Saturday's third lesson changes
System.out.println(timetable[0][2]);
System.out.println("Rows: " + timetable.length);
System.out.println("Columns in row 0: " + timetable[0].length);
}
}$ java Timetable Java English Sport Rows: 3 Columns in row 0: 3
This is the order of maths, where the entry of a is in row i and column j (Matrix entries). Python keeps tables as lists of lists (Two-dimensional lists) and MATLAB has matrices built in (Matrices).
ئەمە ڕیزبەندیی بیرکارییە، کە تێیدا دانەی ـی لە i و jـدایە (دانەکانی ماتریکس). Python خشتەکان وەک لە هەڵدەگرێت (لیستە دووڕەهەندەکان) و MATLAB لە خۆیدا هەیە (ماتریکسەکان).
Two-dimensional arrays: rows and columnsڕیزەکە دووڕەهەندەکان: ڕیز و ستوون
Nested loops over a tableخولە ناوەکییەکان بەسەر خشتەیەکدا
To visit every element, put one loop inside another (Nested loops): the outer loop picks a row, the inner loop walks along it. timetable[row].length is the length of that row:
بۆ سەردانی هەموو ، بخەرە ناو یەکێکی ترەوە (خولە ناوەکییەکان): دەرەوە هەڵدەبژێرێت، ناوەوە بە درێژاییدا دەڕوات. timetable[row].length درێژیی ئەو :
public class PrintTimetable {
public static void main(String[] args) {
String[] days = {"Sat", "Sun", "Mon"};
String[][] timetable = {
{"Maths", "Java", "English"},
{"Physics", "Maths", "Java"},
{"English", "Kurdish", "Java"}
};
for (int row = 0; row < timetable.length; row++) {
System.out.print(days[row] + ": ");
for (int col = 0; col < timetable[row].length; col++) {
System.out.printf("%-9s", timetable[row][col]);
}
System.out.println();
}
}
}$ java PrintTimetable Sat: Maths Java English Sun: Physics Maths Java Mon: English Kurdish Java


%-9s pads each word to 9 places so the columns line up (Width and flags). For sums per row, reset the total at the start of each row:
%-9s هەر وشەیەک بۆ 9 شوێن پڕ دەکاتەوە تا ڕێک بن (پانی و ئاڵاکان). بۆ کۆی هەر ، کۆکە لە سەرەتای هەر سفر بکەرەوە:
import java.util.Arrays;
public class MarkTable {
public static void main(String[] args) {
int[][] marks = {
{90, 75, 88}, // Aram: Maths, Java, English
{62, 95, 70}, // Shilan
{80, 85, 91} // Karwan
};
String[] students = {"Aram", "Shilan", "Karwan"};
for (int row = 0; row < marks.length; row++) {
int total = 0;
for (int col = 0; col < marks[row].length; col++) {
total += marks[row][col];
}
System.out.println(students[row] + ": total " + total);
}
for (int[] row : marks) { // for-each: each row is an int[]
System.out.println(Arrays.toString(row));
}
}
}$ java MarkTable Aram: total 253 Shilan: total 227 Karwan: total 256 [90, 75, 88] [62, 95, 70] [80, 85, 91]
Two-dimensional arrays: rows and columnsڕیزەکە دووڕەهەندەکان: ڕیز و ستوون
A 2-D array is an array of arraysڕیزەکی دووڕەهەند ڕیزەکێکە لە ڕیزەکەکان
Java has no real tables. new int[3][4] makes an array of 3 elements, and each element is itself an int[4] row, all 0. So seats[0] is a whole row, seats.length counts rows and Arrays.toString(seats) prints three array codes; Arrays.deepToString prints the numbers:
Java خشتەی ڕاستەقینەی نییە. new int[3][4] 3 دروست دەکات و هەر خۆی int[4]ـە، هەمووی 0. بۆیە seats[0] تەواوە، seats.length دەژمێرێت و Arrays.toString(seats) سێ کۆدی چاپ دەکات؛ Arrays.deepToString ژمارەکان چاپ دەکات:
import java.util.Arrays;
public class Seats {
public static void main(String[] args) {
int[][] seats = new int[3][4]; // 3 rows, 4 seats in each row, all 0
seats[0][1] = 1; // 1 = taken
seats[2][3] = 1;
System.out.println(Arrays.deepToString(seats));
System.out.println(Arrays.toString(seats));
System.out.println(Arrays.toString(seats[0]));
}
}$ java Seats [[0, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 1]] [[I@6b95977, [I@7e9e5f8a, [I@8bcc55f] [0, 1, 0, 0]
Common mistakesهەڵە باوەکان
| You wroteنووسیت | javac or the run saysjavac یان جێبەجێکردن دەڵێت | Fixچارەسەر |
|---|---|---|
marks[5] | (length 5) ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5(درێژی 5) ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5 | The last index is length - 1.دوایین length - 1ـە. |
i <= marks.length | the same exception after the last elementهەمان دوای دوایین | Use i < marks.length.i < marks.length بەکار بهێنە. |
marks.length() | cannot find symbol symbol: method length() | Arrays: length; strings: length().: length؛ : length(). |
System.out.println(marks); | [I@7344699f[I@7344699f | Arrays.toString(marks).Arrays.toString(marks). |
a == b | false for two arrays with equal elementsfalse بۆ دوو بە یەکسان | Arrays.equals(a, b).Arrays.equals(a, b). |
int[] b = a; | changes through b appear in aگۆڕانکاری لە ڕێگەی bـەوە لە aـدا دەردەکەوێت | Copy: Arrays.copyOf(a, a.length).کۆپی: Arrays.copyOf(a, a.length). |
names[2].length() | (nothing stored) NullPointerException(هیچ هەڵنەگیراوە) NullPointerException | Fill the element first, or check != null.سەرەتا پڕ بکەرەوە، یان != null بپشکنە. |
new int[3]{1, 2, 3} | array creation with both dimension expression and initialization is illegal | new int[] {1, 2, 3} or {1, 2, 3}.new int[] {1, 2, 3} یان {1, 2, 3}. |
b = {1, 2}; | illegal start of expression | Braces alone only in the declaration; else b = new int[] {1, 2};.کەوانە بە تەنیا تەنیا لە ناساندندا؛ ئەگینا b = new int[] {1, 2};. |
for (int m : marks) m = 0; | no message, but the array does not changeهیچ پەیامێک نییە، بەڵام ناگۆڕێت | Change elements through the index. لە ڕێگەی بگۆڕە. |
The real javac messages for the two wrong ways of creating an array:
پەیامە ڕاستەقینەکانی javac بۆ دوو ڕێگە هەڵەکەی دروستکردنی :
$ javac InitErrors.java
InitErrors.java:3: error: array creation with both dimension expression and initialization is illegal
int[] a = new int[3]{1, 2, 3};
^
InitErrors.java:5: error: illegal start of expression
b = {1, 2};
^
InitErrors.java:5: error: not a statement
b = {1, 2};
^
InitErrors.java:5: error: ';' expected
b = {1, 2};
^
4 errorsPracticeڕاهێنان
Reverse int[] numbers = {3, 8, 1, 9, 4}; in place (no second array), then print it.
int[] numbers = {3, 8, 1, 9, 4}; لە شوێنی خۆیدا پێچەوانە بکەرەوە (بەبێ دووەم)، پاشان چاپی بکە.
Hintئاماژە
Use a temp variable, and numbers.length - 1 - i for the partner from the end.
temp بەکار بهێنە و numbers.length - 1 - i بۆ هاوبەشەکە لە کۆتاییەوە.
Show answerوەڵامەکە پیشان بدە
import java.util.Arrays;
public class Reverse {
public static void main(String[] args) {
int[] numbers = {3, 8, 1, 9, 4};
for (int i = 0; i < numbers.length / 2; i++) {
int j = numbers.length - 1 - i; // the partner from the other end
int temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
}
System.out.println(Arrays.toString(numbers));
}
}$ java Reverse [4, 9, 1, 8, 3]
Count the marks of 50 or more in {90, 45, 88, 30, 62, 49, 75}.
نمرەکانی 50 و سەرووتر لە {90, 45, 88, 30, 62, 49, 75}ـدا بژمێرە.
Show answerوەڵامەکە پیشان بدە
public class Passed {
public static void main(String[] args) {
int[] marks = {90, 45, 88, 30, 62, 49, 75};
int passed = 0;
for (int mark : marks) {
if (mark >= 50) {
passed++;
}
}
System.out.println(passed + " of " + marks.length + " passed");
}
}$ java Passed 4 of 7 passed
Find the index of "Karwan" in {"Aram", "Shilan", "Karwan", "Dilan"}; print -1 if the name is not there.
"Karwan" لە {"Aram", "Shilan", "Karwan", "Dilan"}ـدا بدۆزەرەوە؛ ئەگەر ناوەکە نەبوو -1 چاپ بکە.
Show answerوەڵامەکە پیشان بدە
public class FindName {
public static void main(String[] args) {
String[] names = {"Aram", "Shilan", "Karwan", "Dilan"};
String wanted = "Karwan";
int position = -1; // -1 = not found yet
for (int i = 0; i < names.length; i++) {
if (names[i].equals(wanted)) {
position = i;
break;
}
}
System.out.println(wanted + " is at index " + position);
}
}$ java FindName Karwan is at index 2
Compare strings with equals, and stop at the first match with break (Search and stop). This is a .
بە equals بەراورد بکە و بە break لە یەکەم یەکگرتنەوەدا بوەستە (گەڕان و وەستان). ئەمە .
int[] steps = {4200, 8100, 6500, 9900, 7300}; holds the steps of five days. Print on which day (1 to 5) the most steps were walked.
int[] steps = {4200, 8100, 6500, 9900, 7300}; هەنگاوەکانی پێنج ڕۆژ هەڵدەگرێت. چاپ بکە لە کام ڕۆژدا (1 تا 5) زۆرترین هەنگاو نراوە.
Show answerوەڵامەکە پیشان بدە
public class MaxIndex {
public static void main(String[] args) {
int[] steps = {4200, 8100, 6500, 9900, 7300};
int best = 0;
for (int i = 1; i < steps.length; i++) {
if (steps[i] > steps[best]) {
best = i;
}
}
System.out.println("Most steps on day " + (best + 1) + ": " + steps[best]);
}
}$ java MaxIndex Most steps on day 4: 9900
Keep the index of the best value, not the value: the day number is best + 1.
باشترین هەڵبگرە، نەک خودی : ژمارەی ڕۆژەکە best + 1ـە.
Two arrays side by side: days with the seven day names and temps with the seven temperatures 18.5, 21.0, 19.5, 23.0, 25.5, 24.0 and 20.5. Print the average and the name of the hottest day.
دوو لە تەنیشت یەک: days بە ناوی حەوت ڕۆژەکە و temps بە حەوت پلەی گەرمیی 18.5، 21.0، 19.5، 23.0، 25.5، 24.0 و 20.5. ناوەند و ناوی گەرمترین ڕۆژ چاپ بکە.
Show answerوەڵامەکە پیشان بدە
public class WeekTemps {
public static void main(String[] args) {
String[] days = {"Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
double[] temps = {18.5, 21.0, 19.5, 23.0, 25.5, 24.0, 20.5}; // Hawler, one week in October
double sum = 0;
int hottest = 0; // the index of the hottest day so far
for (int i = 0; i < temps.length; i++) {
sum += temps[i];
if (temps[i] > temps[hottest]) {
hottest = i;
}
}
System.out.printf("Average: %.1f degrees%n", sum / temps.length);
System.out.println("Hottest: " + days[hottest] + ", " + temps[hottest] + " degrees");
}
}$ java WeekTemps Average: 21.7 degrees Hottest: Wednesday, 25.5 degrees
The same index connects the two arrays: days[hottest] belongs to temps[hottest].
هەمان هەردوو پێکەوە دەبەستێتەوە: days[hottest] هی temps[hottest]ـە.
int[][] marks has a row per student and a column per subject (Maths, Java, English). Print the average of each subject.
int[][] marks بۆ هەر قوتابییەک و بۆ هەر بابەتێک هەیە (Maths، Java، English). ناوەندی هەر بابەتێک چاپ بکە.
Show answerوەڵامەکە پیشان بدە
public class ColumnAverages {
public static void main(String[] args) {
int[][] marks = {
{90, 75, 88},
{62, 95, 70},
{80, 85, 91}
};
String[] subjects = {"Maths", "Java", "English"};
for (int col = 0; col < marks[0].length; col++) {
int sum = 0;
for (int row = 0; row < marks.length; row++) {
sum += marks[row][col];
}
System.out.printf("%s average: %.1f%n", subjects[col], (double) sum / marks.length);
}
}
}$ java ColumnAverages Maths average: 77.3 Java average: 85.0 English average: 83.0
Here the outer loop walks the columns and the inner loop the rows, because each sum runs down one column.
لێرەدا دەرەوە بەسەر و ناوەوە بەسەر دەڕوات، چونکە هەر کۆیەک بە درێژایی یەک دەڕوات.
More practice: methods that work on arraysڕاهێنانی زیاتر: ئەو میتۆدانەی کار لەسەر ڕیزەک دەکەن
Write each task as one method, like removeAt in Removing an element. Call it from main and print the result with Arrays.toString. The picture shows what each method should give back:
هەر ئەرکێک وەک یەک بنووسە، وەک removeAt لە لابردنی دانەیەک. لە mainـەوە بانگی بکە و ئەنجامەکە بە Arrays.toString چاپ بکە. وێنەکە نیشان دەدات هەر دەبێت چی بگەڕێنێتەوە:
Write static boolean isPalindrome(char[] letters): true when the letters read the same from both ends. Test it with {'r', 'a', 'd', 'a', 'r'} and {'j', 'a', 'v', 'a'}.
static boolean isPalindrome(char[] letters) بنووسە: true کاتێک لە هەردوو سەرەوە وەک یەک دەخوێنرێنەوە. بە {'r', 'a', 'd', 'a', 'r'} و {'j', 'a', 'v', 'a'} تاقیی بکەرەوە.
Hintئاماژە
Compare letters[i] with its partner letters[letters.length - 1 - i] and stop at the middle, as in Reverse an array.
letters[i] لەگەڵ هاوبەشەکەی letters[letters.length - 1 - i] بەراورد بکە و لە ناوەڕاستدا بوەستە، وەک لە پێچەوانەکردنەوەی .
Show answerوەڵامەکە پیشان بدە
public class Palindrome {
static boolean isPalindrome(char[] letters) {
for (int i = 0; i < letters.length / 2; i++) {
if (letters[i] != letters[letters.length - 1 - i]) {
return false; // the first pair that differs decides
}
}
return true;
}
public static void main(String[] args) {
char[] radar = {'r', 'a', 'd', 'a', 'r'};
char[] javaWord = {'j', 'a', 'v', 'a'};
System.out.println("radar: " + isPalindrome(radar));
System.out.println("java: " + isPalindrome(javaWord));
}
}$ java Palindrome radar: true java: false
One pair that differs is enough to return false; only when every pair matches is it true. For a word in a String, see the strings practice.
یەک جووتی جیاواز بەسە بۆ گەڕاندنەوەی false؛ تەنیا کاتێک هەموو جووتەکان وەک یەک بن trueـە. بۆ وشەیەک لە Stringـێکدا، ڕاهێنانەکانی زنجیرەنووسەکان ببینە.
Write static int[] merge(int[] first, int[] second): one new array with all the elements of first, then all of second, in their order. {1, 3, 5} and {2, 4} give [1, 3, 5, 2, 4].
static int[] merge(int[] first, int[] second) بنووسە: یەک نوێ بە هەموو first و پاشان هەموو ئەوانەی second، بە ڕیزبەندیی خۆیان. {1, 3, 5} و {2, 4} دەدەن [1, 3, 5, 2, 4].
Hintئاماژە
The new length is first.length + second.length.
درێژیی نوێ first.length + second.lengthـە.
Show answerوەڵامەکە پیشان بدە
import java.util.Arrays;
public class Merge {
static int[] merge(int[] first, int[] second) {
int[] result = new int[first.length + second.length];
for (int i = 0; i < first.length; i++) {
result[i] = first[i];
}
for (int i = 0; i < second.length; i++) {
result[first.length + i] = second[i]; // continue after the first array
}
return result;
}
public static void main(String[] args) {
int[] odd = {1, 3, 5};
int[] even = {2, 4};
System.out.println(Arrays.toString(merge(odd, even)));
}
}$ java Merge [1, 3, 5, 2, 4]
The elements of second go on where first stops, at index first.length + i.
second لەو شوێنەوە بەردەوام دەبن کە first تێیدا دەوەستێت، لە first.length + i.
Write static int[] rotateRight(int[] a, int k) (k is 0 or more): every element moves k places to the right, and the ones that fall off the end come back at the start. {1, 2, 3, 4, 5} with k = 2 gives [4, 5, 1, 2, 3].
static int[] rotateRight(int[] a, int k) بنووسە (k 0 یان زیاترە): هەر k شوێن بەرەو ڕاست دەچێت و ئەوانەی لە کۆتاییەوە دەکەونە دەرەوە لە سەرەتاوە دەگەڕێنەوە. {1, 2, 3, 4, 5} بە k = 2 دەدات [4, 5, 1, 2, 3].
Hintئاماژە
Element a[i] goes to index (i + k) % a.length (the remainder operator).
a[i] دەچێتە (i + k) % a.length (پاشماوە).
Show answerوەڵامەکە پیشان بدە
import java.util.Arrays;
public class Rotate {
static int[] rotateRight(int[] a, int k) {
int[] result = new int[a.length];
for (int i = 0; i < a.length; i++) {
result[(i + k) % a.length] = a[i]; // past the end? % brings it back to the start
}
return result;
}
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
System.out.println("k = 2: " + Arrays.toString(rotateRight(numbers, 2)));
System.out.println("k = 7: " + Arrays.toString(rotateRight(numbers, 7)));
System.out.println("k = 5: " + Arrays.toString(rotateRight(numbers, 5)));
}
}$ java Rotate k = 2: [4, 5, 1, 2, 3] k = 7: [4, 5, 1, 2, 3] k = 5: [1, 2, 3, 4, 5]
% also handles a k larger than the length: 7 places on 5 elements is the same as 2, and 5 places bring every element back home.
% ئەو kـەش چارەسەر دەکات کە لە درێژییەکە گەورەترە: 7 شوێن لەسەر 5 وەک 2 شوێن وایە و 5 شوێن هەموو دەگەڕێنێتەوە شوێنی خۆیان.
Write static int[] addArrays(int[] a, int[] b) for two arrays of the same length: element i of the result is a[i] + b[i]. {1, 2, 3} and {10, 20, 30} give [11, 22, 33].
static int[] addArrays(int[] a, int[] b) بۆ دوو بە هەمان درێژی بنووسە: iـی ئەنجامەکە a[i] + b[i]ـە. {1, 2, 3} و {10, 20, 30} دەدەن [11, 22, 33].
Show answerوەڵامەکە پیشان بدە
import java.util.Arrays;
public class AddArrays {
static int[] addArrays(int[] a, int[] b) {
int[] sums = new int[a.length];
for (int i = 0; i < a.length; i++) {
sums[i] = a[i] + b[i]; // the same index in both arrays
}
return sums;
}
public static void main(String[] args) {
int[] first = {1, 2, 3};
int[] second = {10, 20, 30};
System.out.println(Arrays.toString(addArrays(first, second)));
}
}$ java AddArrays [11, 22, 33]
One index walks both arrays at once. If the lengths may differ, check them first and throw an exception, as removeAt does for a wrong index.
یەک هاوکات بەسەر هەردوو دەڕوات. ئەگەر درێژییەکان لەوانەیە جیاواز بن، سەرەتا بیانپشکنە و فڕێ بدە، وەک ئەوەی removeAt بۆ هەڵە دەیکات.
Write static int[] withoutDuplicates(int[] a): a new array with each value once, in the order it first appears. {3, 1, 3, 2, 1} gives [3, 1, 2].
static int[] withoutDuplicates(int[] a) بنووسە: نوێ کە هەر تەنیا یەک جاری تێدایە، بەو ڕیزبەندییەی یەکەم جار دەردەکەوێت. {3, 1, 3, 2, 1} دەدات [3, 1, 2].
Hintئاماژە
Keep the values in a second array and count how many you kept. Before keeping a value, look for it among the kept ones; at the end, cut the array with Arrays.copyOf(kept, count).
لە دووەمدا هەڵبگرە و بژمێرە چەندت هەڵگرتووە. پێش هەڵگرتنی هەر ، لە ناو هەڵگیراوەکاندا بەدوایدا بگەڕێ؛ لە کۆتاییدا بە Arrays.copyOf(kept, count) کورت بکەرەوە.
Show answerوەڵامەکە پیشان بدە
import java.util.Arrays;
public class NoDuplicates {
static int[] withoutDuplicates(int[] a) {
int[] kept = new int[a.length]; // room for the worst case: no duplicates at all
int count = 0; // how many places of kept are used
for (int value : a) {
boolean seen = false;
for (int j = 0; j < count; j++) {
if (kept[j] == value) {
seen = true;
break;
}
}
if (!seen) {
kept[count] = value;
count++;
}
}
return Arrays.copyOf(kept, count); // cut off the unused places
}
public static void main(String[] args) {
int[] numbers = {3, 1, 3, 2, 1};
System.out.println(Arrays.toString(withoutDuplicates(numbers)));
}
}$ java NoDuplicates [3, 1, 2]
Later, a LinkedHashSet does the same in one line (Removing duplicates).
دواتر LinkedHashSet هەمان کار لە یەک دێڕدا دەکات (لابردنی دووپاتەکان).
Summaryکورتە
- An array holds a fixed number of values of one type:
int[] a = {…}ornew int[n](filled with default values: 0, false, null). - Indexes run from 0 to
a.length - 1; anything else throws ArrayIndexOutOfBoundsException.lengthhas no brackets. - Loop with
for (int i = 0; i < a.length; i++)to use indexes; with for-each to read the elements (it gives copies). - An array variable holds a reference:
b = ashares the array;Arrays.copyOfcopies;Arrays.equalscompares. - To remove an element, copy the others into a new array one place shorter (or use an ArrayList).
java.util.Arrays:toString,sort,fill,equals,copyOf. Methods can take and return arrays;maingetsString[] args.- A 2-D array
t[row][col]is an array of row arrays, visited with nested loops.
- ژمارەیەکی جێگیر لە یەک جۆر هەڵدەگرێت:
int[] a = {…}یانnew int[n](پڕ لە : 0، false، null). - لە 0ـەوە تا
a.length - 1دەڕۆن؛ هەر شتێکی تر ArrayIndexOutOfBoundsException فڕێ دەدات.lengthکەوانەی نییە. - بۆ بە
for (int i = 0; i < a.length; i++)بسووڕێوە؛ بۆ خوێندنەوەی بە (کۆپی دەدات). - هەڵدەگرێت:
b = aهاوبەش دەکات؛Arrays.copyOfکۆپی دەکات؛Arrays.equalsبەراورد دەکات. - بۆ لابردنی ، ئەوانی تر کۆپی بکە بۆ نوێ کە یەک شوێن کورتترە (یان ArrayList بەکار بهێنە).
java.util.Arrays:toString،sort،fill،equals،copyOf. دەتوانن وەربگرن و بیگەڕێننەوە؛mainString[] argsوەردەگرێت.-
t[row][col]لە (هەریەکەیان ) و بە سەردان دەکرێت.
Why does System.out.println(a) print something like [I@7344699f?بۆچی System.out.println(a) شتێکی وەک [I@7344699f چاپ دەکات؟
Because a is a reference to an array object; use Arrays.toString(a) to see the elements.
چونکە a بۆ ؛ بۆ بینینی Arrays.toString(a) بەکار بهێنە.
How do you add a sixth element to an array of five?چۆن دانەیەکی شەشەم زیاد دەکەیت بۆ ڕیزەکێکی پێنجی؟
You cannot: copy it into a longer array with Arrays.copyOf(a, 6), or use an ArrayList.
ناتوانیت: بە Arrays.copyOf(a, 6) کۆپیی بکە بۆ درێژتر، یان ArrayList بەکار بهێنە.
What is the default value of a String[] element?نرخی بنەڕەتیی دانەیەکی String[] چییە؟
null: an empty slot. Calling a method on it throws NullPointerException.
null: شوێنی چۆڵ. بانگکردنی لەسەری NullPointerException فڕێ دەدات.
Lesson complete!وانەکە تەواو بوو!
Well done. Review the key terms, then go on to the next lesson.دەستخۆش. سەیرێکی زاراوە سەرەکییەکان بکەرەوە، پاشان بڕۆ بۆ وانەی داهاتوو.
Key termsزاراوە سەرەکییەکان
ArrayList and Wrapper ClassesArrayList و کلاسە پێچەرەوەکان
Related lecturesوانە پەیوەندیدارەکان
- ArrayList and Wrapper ClassesArrayList و کلاسە پێچەرەوەکان
- Methods, Parameters and Return Valuesمیتۆدەکان، پارامیتەرەکان و نرخە گەڕاوەکان
- Method Overloading and Scopeفرەپێناسەکردنی میتۆد و مەودا
- Strings and String Methodsزنجیرەنووسەکان و میتۆدەکانی String
- Packages, import and the Java APIپاکێجەکان، import و APIـی Java
- Lists: Creating and Indexingلیستەکان: دروستکردن و ئیندێکسەکان
- Lists, References, Copies and Functionsلیستەکان، ئاماژەکان، کۆپی و کردارەکان
- Two-Dimensional Listsلیستە دووڕەهەندەکان
- Python Next to JavaPython لە تەنیشت Javaـەوە
- Indexing, the Colon, Adding and Deleting Elementsئیندێکسەکان، دوو خاڵ، زیادکردن و سڕینەوەی توخمەکان
- Vectors and Matrices: Arrows, Bold Letters, Aᵀ, A⁻¹ and detئاڕاستەبڕەکان و ماتریکسەکان: تیر، پیتی تۆخ، Aᵀ، A⁻¹ و det
References and further readingسەرچاوەکان و خوێندنەوەی زیاتر
- W3Schools: Java Arrays
- W3Schools: Java Arrays Loop
- W3Schools: Java Arrays, real-life examples
- W3Schools: Java Multidimensional Arrays
- W3Schools: Java Arrays class methods
- The Java Tutorials: Arrays
- Java Language Specification (Java SE 17), chapter 10: Arrays
- Java Language Specification (Java SE 17), §4.12.5 Initial Values of Variables
- Java SE 17 API: java.util.Arrays
- Sedgewick and Wayne, Introduction to Programming in Java, 1.4 Arrays
This lecture is a first edition. The Kurdish text and terminology are waiting for review by Kurdish IT teachers.ئەم وانەیە چاپی یەکەمە. دەقە کوردییەکە و زاراوەکانی چاوەڕێی پێداچوونەوەی مامۆستایانی کوردی بواری IT ن.