Maison  >  Article  >  Java  >  Parcours d'apprentissage Java

Parcours d'apprentissage Java

Susan Sarandon
Susan Sarandonoriginal
2024-10-19 18:20:02332parcourir

Java Learning Journey

J'ai récemment appris Java grâce aux pratiques de [https://exercism.org/tracks/java/exercises]. Ma progression actuelle est de 13 sur un total de 148 pratiques. J'aimerais partager ce que j'ai appris.

Cet article présente ma compréhension de .split(), .trim(), .isDigit(), .isLetter(), Comparable, des exceptions Java définies par l'utilisateur et de l'interface.

1) .split()

Définition : La méthode .split() divise String en un tableau basé sur le séparateur [1].

Syntaxe :

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

Paramètre :

  • regex : (champ obligatoire) modèle de séparateur
  • limite : (champ facultatif) longueur maximale du tableau renvoyé

Exemple :

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");
    }

}

Sortie :

12.50 + 23.45 + 395.67 = 431.62

2) .trim()

Définition : La méthode .trim() supprime les espaces aux deux extrémités d'une chaîne [2].

Syntaxe :

public String trim()

Paramètre :

  • aucun paramètre

Exemple :

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

Sortie :

   You can do it!   
You can do it!

3) .isDigit()

Définition : La méthode .isDigit() détermine si un caractère est un chiffre ou non [3].

Syntaxe :

public static boolean isDigit(char ch)

Paramètre :

  • ch : (champ obligatoire) la valeur du caractère à tester

Exemple :

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");
            }
        }

    }
}

Sortie :

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

4) .isLetter()

Définition : La méthode .isLetter() détermine si un caractère est une lettre ou non [4].

Syntaxe :

public static boolean isLetter(char ch)

Paramètre :

  • ch : (champ obligatoire) la valeur du caractère à tester

Exemple :

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);
        }
    }
}

Sortie :

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) Comparable

Définition : Le Comparable L'interface est utilisée pour définir un ordre naturel pour une collection d'objets, et elle doit être implémentée dans la classe des objets comparés [5]. Le paramètre de type T représente le type d'objets pouvant être comparés.

Exemple :

// 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));
    }
}

Sortie :

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) Exceptions Java définies par l'utilisateur

Définition : l'exception Java définie par l'utilisateur est une exception personnalisée qu'un développeur crée pour gérer des conditions d'erreur spécifiques [6].

Exemple :

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");
    }

}

Sortie :

12.50 + 23.45 + 395.67 = 431.62

7) Interfaces

Les interfaces en Java permettent aux utilisateurs d'invoquer la même méthode dans différentes classes, chacune implémentant sa propre logique [7]. Dans l'exemple ci-dessous, la méthode calculatePrice() est appelée dans différentes classes, telles que Fruit et DiscountFruit, chaque classe appliquant sa propre logique de calcul unique.

Exemple :

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)

Sortie :

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");
            }
        }

    }
}

Référence

[1] JavaRush, méthode split en java : diviser une chaîne en parties, 8 août 2023

[2] W3Schools, méthode Java String trim()

[3] GeeksforGeeks, Méthode Character isDigit() en Java avec exemples, 17 mai 2020

[4] tutorielspoint, Java - Méthode Character isLetter()

[5] DigitalOcean, exemple comparable et comparateur en Java, 4 août 2022

[6] Shiksha, Comprendre les exceptions définies par l'utilisateur en Java, 25 avril 2024

[7] Scientech Easy, Utilisation de l'interface en Java avec exemple, 9 juillet 2024

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Article précédent:Blocs d'essai imbriquésArticle suivant:Aucun