“這裡有一些您可以用數組做的有趣事情的例子:”
示例 1。 |
用 1 到 10 的數字填充 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;
}
}
}
用 10 到 1 的數字填充 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] = 10 - i;
}
}
}
用 0 到 9 的數字填充一個 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;
}
}
}
用 9 到 0 的數字填充一個 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] = 9 - i;
}
}
}
|
示例 2。 |
從鍵盤讀取 10 個字符串:
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();
}
}
}
從鍵盤讀取 10 個數字:
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);
}
}
}
|
示例 3。 |
在屏幕上顯示一個數組:
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]);
}
}
|
例 4。 |
快速(靜態)初始化。添加數組元素:
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);
}
}
|
示例 5。 |
查找數組中的最小元素:
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);
}
}
|
作為 Codegym 大學課程一部分的導師授課片段。報名參加完整課程。
GO TO FULL VERSION