復古趣味屋の備忘録

いろいろ開発備忘録

音痴でも分かるJavaの基礎

配列のお話

▶個数指定生成
int[] numbers = new int[10];
型名[] 変数名 = new 型名[個数]

▶配列の要素指定
int[] numbers = {1, 3, 2, 4};
型名[] 変数名 = {要素1,要素2};

アクセス方法

numbers[0]

System.out.println(numbers[0]);
的な

for文のお話

for(int i = 1; i <= 10;){}
Cと一緒です。安心してくれ。
str.lengthで配列の長さを取ってきてくれます。

拡張for文

配列の要素すべてで

int[] numbers = {10, 20, 30};
for(int number : numbers){
 System.out.println(number);
}

配列numbersの要素を1つずつnumberに代入しながら繰り返し実行、全ての要素を取り出したら繰り返しを終了する

参考リンク

while文のお話

boolean flag = true;
while(flag){  
}
// 永久的に繰り返す

条件文を満たしている時(trueの時)は実行を繰り返す

do-whileのお話

boolean flag = true;

do{
}while(flag)

確実に一回以上は実行される繰り返し文 繰り返し判定が前のwhile文、for文に対し、do-while文は繰り返し判定が後ろ。

break;
強制的に繰り返しを終了させる
continue;
次の繰り返しに強制移動させる  参考リンク

switchのお話

switch(i){
case 1:

今日書いたコード

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    static void question1(){
        String[] str = {"tokai ","robo","p!"};
        System.out.println(str[0] + str[1] + str[2]);
    }
    
    static void question2(){
        String[] str = {"tokai ","robo","p!"};
        for(int i = 0; i <= 2; i++){
            System.out.println(str[i]);
        }
    }
    
    static void question3(){
        String[] str = {"tokai ","robo","p!"};
        for(String stri : str){
            System.out.println(stri);
        }
    }
    
    static void question4(){
        int i = 0;
        while(i <= 10){
            System.out.println(i);
            i++;
        }
    }
    
    static void question5(){
        int i = 10;
        switch(i){
            case 0: System.out.println("sunny");
            break;
            case 1: System.out.println("cloudy");
            break;
            case 2: System.out.println("rainy");
            break;
         default: System.out.println("other");
            break;
        }
    }
    
    public static void main (String[] args) throws java.lang.Exception
    {
        question5();
    }
}