返回组成单词的字母表的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();

    }


}


开心每一天1111
浏览 123回答 3
3回答

MYYA

我更改代码并添加说明。&nbsp; &nbsp; boolean behindExist;&nbsp; &nbsp; for (int i=1; i<str1.length(); i++) {//loop for all character in string&nbsp; &nbsp; &nbsp; &nbsp; behindExist = false;&nbsp; &nbsp; &nbsp; &nbsp; for (int j=0; j < i; j++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //check same character is exist before now char&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //Ex) if (i = 3), check&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //str1.charAt(3) == str1.charAt(0);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //str1.charAt(3) == str1.charAt(1);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //str1.charAt(3) == str1.charAt(2);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (str1.charAt(i)==str1.charAt(j)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; behindExist = true;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if (!behindExist) {//if not behindExist&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; arr1[i]=str1.charAt(i);//add to arr1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print(arr1[i]+"");//and print character&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }而且,这是我的代码。&nbsp; &nbsp; Scanner sc = new Scanner(System.in);&nbsp; &nbsp; System.out.print("input a string : ");&nbsp; &nbsp; String input = sc.nextLine();&nbsp; &nbsp; for(int charCode : input.chars().distinct().toArray()) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.print((char)charCode);&nbsp; &nbsp; }&nbsp; &nbsp; System.out.print(" : only made up of these alphabets");&nbsp; &nbsp; sc.close();短的。我喜欢它。我希望这能有所帮助。:)

天涯尽头无女友

我们可以使用像这样简单的东西吗?该集合将包含构成单词的唯一字符。char[] charArr = str1.toCharArray();Set<Character> charSet = new HashSet();for(char c: charArr){&nbsp; &nbsp; charSet.add(c);}

慕姐8265434

为什么要把问题复杂化。尝试在 java 中使用集合的功能。是这样的:-Set<Character>&nbsp;set&nbsp;=&nbsp;new&nbsp;HashSet(Arrays.asList(str1.toCharArray()));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java