"Hier zijn een paar voorbeelden van interessante dingen die u kunt doen met arrays:"
Voorbeeld 1.
Vul een array van 10 elementen met getallen van 1 tot 10:
public class MainClass
{
public static void main(String[] args)
{
int[] numbers = new int[10];
for (int i = 0; i < numbers.length; i++)
{
numbers[i] = i + 1;
}
}
}
Vul een array van 10 elementen met getallen van 10 tot 1:
public class MainClass
{
public static void main(String[] args)
{
int[] numbers = new int[10];
for (int i = 0; i < numbers.length; i++)
{
numbers[i] = 10 - i;
}
}
}
Vul een array van 10 elementen met getallen van 0 tot 9:
public class MainClass
{
public static void main(String[] args)
{
int[] numbers = new int[10];
for (int i = 0; i < numbers.length; i++)
{
numbers[i] = i;
}
}
}
Vul een array van 10 elementen met getallen van 9 tot 0:
public class MainClass
{
public static void main(String[] args)
{
int[] numbers = new int[10];
for (int i = 0; i < numbers.length; i++)
{
numbers[i] = 9 - i;
}
}
}
Voorbeeld 2.
Lees 10 snaren van het toetsenbord:
public class MainClass
{
public static void main(String[] args) throws IOException
{
BufferedReaderreader = new BufferedReader(new InputStreamReader(System.in));
String[] list = new String[10];
for (int i = 0; i < list.length; i++)
{
list[i] = reader.readLine();
}
}
}
Lees 10 cijfers van het toetsenbord:
public class MainClass
{
public static void main(String[] args) throws IOException
{
BufferedReaderreader = new BufferedReader(new InputStreamReader(System.in));
int[] list = new int[10];
for (int i = 0; i < list.length; i++)
{
String s = reader.readLine();
list[i] = Integer.parseInt(s);
}
}
}
Voorbeeld 3.
Toon een array op het scherm:
public class MainClass
{
public static void main(String[] args) throws IOException
{
int[] list = new int[10];
// Fill the array
for (int i = 0; i < list.length; i++)
list[i] = i;
// Display the contents of the array
for (int i = 0; i < list.length; i++)
System.out.println(list[i]);
}
}
Voorbeeld 4.
Snelle (statische) initialisatie. Tel de array-elementen op:
public class MainClass
{
public static void main(String[] args) throws IOException
{
// Static initialization
int[] list = {5, 6, 7, 8, 1, 2, 5, -7, -9, 2, 0};
// Calculate the sum
int sum = 0;
for (int i = 0; i < list.length; i++)
sum += list[i];
System.out.println("Sum is " + sum);
}
}
Voorbeeld 5.
Zoek het kleinste element in een array:
public class MainClass
{
public static void main(String[] args) throws IOException
{
int[] list = {5, 6, 7, 8, 1, 2, 5, -7, -9, 2, 0};
int min = list[0];
for (int i = 1; i < list.length; i++)
{
if (list[i] < min)
min = list[i];
}
System.out.println ("Min is " + min);
}
}
GO TO FULL VERSION