"Her er et par eksempler på interessante ting, du kan gøre med arrays:"
Eksempel 1. |
Fyld en matrix med 10 elementer med tal fra 1 til 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;
}
}
}
Fyld en matrix med 10 elementer med tal fra 10 til 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;
}
}
}
Fyld en matrix med 10 elementer med tal fra 0 til 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;
}
}
}
Fyld en matrix med 10 elementer med tal fra 9 til 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;
}
}
}
|
Eksempel 2. |
Læs 10 strenge fra tastaturet:
public class MainClass
{
public static void main(String[] args) throws IOException
{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String[] list = new String[10];
for (int i = 0; i < list.length; i++)
{
list[i] = reader.readLine();
}
}
}
Læs 10 tal fra tastaturet:
public class MainClass
{
public static void main(String[] args) throws IOException
{
BufferedReader reader = 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);
}
}
}
|
Eksempel 3. |
Vis et array på skærmen:
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]);
}
}
|
Eksempel 4. |
Hurtig (statisk) initialisering. Tilføj array-elementerne:
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);
}
}
|
Eksempel 5. |
Find det mindste element i en matrix:
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);
}
}
|
Et foredragsuddrag med en mentor som en del af Codegym University-kurset. Tilmeld dig hele kurset.
GO TO FULL VERSION