首页 > 解决方案 > 返回组成单词的字母的Java程序

问题描述

我试图了解代码片段是如何在 java 中贡献程序的。所以程序应该从用户那里获取一个单词的输入,然后输出打印用户输入单词的字母表。该程序运行良好,但我需要帮助来解释 for 循环在做什么。谢谢!

    import java.util.Scanner;

public class J0307_search {
    public static void main(String[] args) {
        String str1;
        int count;
        char[] arr1=new char[40];

        Scanner s=new Scanner (System.in);
        System.out.print("input a string:");
        str1=s.nextLine();
        arr1[0]=str1.charAt(0);
        System.out.print(arr1[0]+"");


        for (int i=1; i<str1.length();i++) {
            count=0;
            for (int j=0;j<i;j++) {
                if (str1.charAt(i)==str1.charAt(j)) {
                    count++;

                }
            }
            if (count<1) {
                arr1[i]=str1.charAt(i);
                System.out.print(arr1[i]+"");
            }
        }
        System.out.print(" : only made up of these alphabets");
        s.close();
    }

}

标签: javafor-loop

解决方案


I change code and add explain.

    boolean behindExist;
    for (int i=1; i<str1.length(); i++) {//loop for all character in string
        behindExist = false;
        for (int j=0; j < i; j++) {
            //check same character is exist before now char 
            //Ex) if (i = 3), check
            //str1.charAt(3) == str1.charAt(0);
            //str1.charAt(3) == str1.charAt(1);
            //str1.charAt(3) == str1.charAt(2);
            if (str1.charAt(i)==str1.charAt(j)) {
                behindExist = true;
            }
        }

        if (!behindExist) {//if not behindExist
            arr1[i]=str1.charAt(i);//add to arr1
            System.out.print(arr1[i]+"");//and print character
        }
    }

And, this is my code.

    Scanner sc = new Scanner(System.in);
    System.out.print("input a string : ");
    String input = sc.nextLine();

    for(int charCode : input.chars().distinct().toArray()) {
        System.out.print((char)charCode);
    }
    System.out.print(" : only made up of these alphabets");
    sc.close();

Short. I love it. I hope this can be help. :)


推荐阅读