ホームページ  >  記事  >  Java  >  Java学習の旅

Java学習の旅

Susan Sarandon
Susan Sarandonオリジナル
2024-10-19 18:20:02333ブラウズ

Java Learning Journey

私は最近、[https://exercism.org/tracks/java/exercises] の演習を通じて Java を学びました。現在の進捗状況は、合計148回の練習のうち13回です。私が学んだことを共有したいと思います。

この投稿では、.split()、.trim()、.isDigit()、.isLetter()、Comparable、ユーザー定義 Java 例外、およびインターフェイスについての私の理解を紹介します。

1) .split()

定義: .split() メソッドは、区切り文字 [1] に基づいて String を配列​​に分割します。

構文:

public String[] split(String regex, int limit)

パラメータ:

  • 正規表現: (必須フィールド) 区切り文字のパターン
  • limit: (オプションのフィールド) 返される配列の最大長

:

public class Main{

    public void getProductPrice(String products){
        double totalPrice = 0.0;
        StringBuilder priceDetails = new StringBuilder();

        String[] singleProduct = products.split("; ");

        for(int i = 0; i < singleProduct.length; i++){
            String[] productInfo = singleProduct[i].split(", ");
            totalPrice += Double.parseDouble(productInfo[2]);

            priceDetails.append(productInfo[2]);
            if(i < singleProduct.length - 1){
                priceDetails.append(" + ");
            }
        }

        System.out.println(priceDetails + " = " + totalPrice);
    }

    public static void main(String arg[]){
        Main obj = new Main();
        obj.getProductPrice("1, dragonfruit, 12.50; 2, guava, 23.45; 3, avocado, 395.67");
    }

}

出力:

12.50 + 23.45 + 395.67 = 431.62

2) .trim()

定義: .trim() メソッドは文字列 [2] の両端から空白を削除します。

構文:

public String trim()

パラメータ:

  • パラメータなし

:

public class Main{
    public static void main(String args[]){
        String str = "   You can do it!   ";
        System.out.println(str);
        System.out.println(str.trim());
    }
}

出力:

   You can do it!   
You can do it!

3) .isDigit()

定義: .isDigit() メソッドは、文字が数字であるかどうかを決定します [3]。

構文:

public static boolean isDigit(char ch)

パラメータ:

  • ch: (必須フィールド) テストする文字値

:

public class Main{

    // return true when the given parameter has a digit
    public boolean searchDigit(String str){
        for(int i = 0; i < str.length(); i++){
            // charAt() method returns the character at the specified index in a string
            if(Character.isDigit(str.charAt(i))){
                return true;
            }
        }
        return false;
    }

    // print digit index and value
    public void digitInfo(String str){
        for(int i = 0; i < str.length(); i++){
            if(Character.isDigit(str.charAt(i))){
                System.out.println("Digit: " + str.charAt(i) + " found at index " + i);
            }
        }
    }

    public static void main(String args[]){
        Main obj = new Main();
        String[] strList = {"RT7J", "1EOW", "WBJK"};

        for(String str : strList){
            if(obj.searchDigit(str)){
                obj.digitInfo(str);
            }else{
                System.out.println("No digit");
            }
        }

    }
}

出力:

Digit: 7 found at index 2
Digit: 1 found at index 0
No digit

4) .isLetter()

定義: .isLetter() メソッドは、文字が文字であるかどうかを決定します [4].

構文:

public static boolean isLetter(char ch)

パラメータ:

  • ch: (必須フィールド) テストする文字値

:

public class Main{

    // check whether phoneNum has letter
    public void searchLetter(String phoneNum){
        boolean hasLetter = false;

        for(int i = 0; i < phoneNum.length(); i++){
            if(Character.isLetter(phoneNum.charAt(i))){
                hasLetter = true;
                // return letter value and index
                System.out.println(phoneNum + " has letter '" + phoneNum.charAt(i) + "' at index " + i);
            }
        }

        // phone number is valid when no letter
        if(!hasLetter){
            System.out.println(phoneNum + " is valid");
        }

        System.out.println();
    }

    public static void main(String args[]){
        Main obj = new Main();
        String[] phoneNum = {"A0178967547", "0126H54786K5", "0165643484"};

        for(String item: phoneNum){
            obj.searchLetter(item);
        }
    }
}

出力:

A0178967547 has letter 'A' at index 0

0126H54786K5 has letter 'H' at index 4
0126H54786K5 has letter 'K' at index 10

0165643484 is valid

5) 同等の

定義: 比較対象インターフェースは、オブジェクトのコレクションの自然な順序付けを定義するために使用され、比較されるオブジェクトのクラスに実装される必要があります [5]。型パラメーター T は、比較できるオブジェクトの型を表します。

:

// file: Employee.java
public class Employee implements Comparable<Employee>{
    private String email;
    private String name;
    private int age;

    public Employee(String email, String name, int age){
        this.email = email;
        this.name = name;
        this.age = age;
    }

    // The Comparable interface has a method called compareTo(T obj). 
    // This method helps decide how to order objects, so they can be sorted in a list
    @Override
    public int compareTo(Employee emp){
        // compare age: 
        // return this.age - emp.age;
        // (this.age - emp.age) = negative value means this.age before emp.age; 
        // (this.age - emp.age) = positive means this.age after emp.age

        // compare email:
        return this.email.compareTo(emp.email);
    }

    @Override
    public String toString(){
        return "[email=" + this.email + ", name=" + this.name + ", age=" + this.age +"]";
    }
}
// file: Main.java
import java.util.Arrays;

public class Main {
    public static void main(String args[]){
        Employee[] empInfo = new Employee[3];
        empInfo[0] = new Employee("joseph@gmail.com", "Joseph", 27);
        empInfo[1] = new Employee("alicia@gmail.com", "Alicia", 30);
        empInfo[2] = new Employee("john@gmail.com", "John", 24);

        Arrays.sort(empInfo);
        System.out.println("After sorting:\n" + Arrays.toString(empInfo));
    }
}

出力:

After sorting:
[[email=alicia@gmail.com, name=Alicia, age=30], [email=john@gmail.com, name=John, age=24], [email=joseph@gmail.com, name=Joseph, age=27]]

6) ユーザー定義の Java 例外

定義: ユーザー定義の Java 例外は、特定のエラー条件を処理するために開発者が作成するカスタム例外です [6]。

:

public String[] split(String regex, int limit)
public class Main{

    public void getProductPrice(String products){
        double totalPrice = 0.0;
        StringBuilder priceDetails = new StringBuilder();

        String[] singleProduct = products.split("; ");

        for(int i = 0; i < singleProduct.length; i++){
            String[] productInfo = singleProduct[i].split(", ");
            totalPrice += Double.parseDouble(productInfo[2]);

            priceDetails.append(productInfo[2]);
            if(i < singleProduct.length - 1){
                priceDetails.append(" + ");
            }
        }

        System.out.println(priceDetails + " = " + totalPrice);
    }

    public static void main(String arg[]){
        Main obj = new Main();
        obj.getProductPrice("1, dragonfruit, 12.50; 2, guava, 23.45; 3, avocado, 395.67");
    }

}

出力:

12.50 + 23.45 + 395.67 = 431.62

7) インターフェース

Java のインターフェイスを使用すると、ユーザーはさまざまなクラスにわたって同じメソッドを呼び出すことができ、それぞれが独自のロジックを実装します [7]。以下の例では、メソッド CalculatePrice() が Fruit やDiscountFruit などの異なるクラスで呼び出され、各クラスが独自の計算ロジックを適用します。

:

public String trim()
public class Main{
    public static void main(String args[]){
        String str = "   You can do it!   ";
        System.out.println(str);
        System.out.println(str.trim());
    }
}
   You can do it!   
You can do it!
public static boolean isDigit(char ch)

出力:

public class Main{

    // return true when the given parameter has a digit
    public boolean searchDigit(String str){
        for(int i = 0; i < str.length(); i++){
            // charAt() method returns the character at the specified index in a string
            if(Character.isDigit(str.charAt(i))){
                return true;
            }
        }
        return false;
    }

    // print digit index and value
    public void digitInfo(String str){
        for(int i = 0; i < str.length(); i++){
            if(Character.isDigit(str.charAt(i))){
                System.out.println("Digit: " + str.charAt(i) + " found at index " + i);
            }
        }
    }

    public static void main(String args[]){
        Main obj = new Main();
        String[] strList = {"RT7J", "1EOW", "WBJK"};

        for(String str : strList){
            if(obj.searchDigit(str)){
                obj.digitInfo(str);
            }else{
                System.out.println("No digit");
            }
        }

    }
}

参照

[1] JavaRush、Java の分割メソッド: 文字列を部分に分割、2023 年 8 月 8 日

[2] W3Schools、Java String Trim() メソッド

[3] GeeksforGeeks、Java の Character isDigit() メソッドと例、2020 年 5 月 17 日

[4] チュートリアルポイント、Java - Character isLetter() メソッド

[5] DigitalOcean、Java での Comparable と Comparator の例、2022 年 8 月 4 日

[6] Shiksha、Java のユーザー定義例外について、2024 年 4 月 25 日

[7] Scientech Easy、Java でのインターフェイスの使用例、2024 年 7 月 9 日

以上がJava学習の旅の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。