我试图理解代码片段是如何贡献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();
}
}
最佳答案
我更改代码并添加解释。
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
}
}
而且,这是我的代码。
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();
简短。我喜欢它。我希望这能有所帮助。 :)
关于返回单词组成字母的 Java 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57230917/