「配列を使って実行できる興味深い例をいくつか示します。」

例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] = i + 1;
        }
    }
}
10 要素の配列に 10 から 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;
        }
    }
}
10 要素の配列に 0 から 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;
        }
    }
}
10 要素の配列に 9 から 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;
        }
    }
}
例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 University コースの一部としてのメンターによる講義の抜粋。フルコースにお申し込みください。