java - 返回组成单词的字母的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();
}
}
解决方案
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. :)
推荐阅读
- swagger - 对 Swagger 2 使用任何方法
- java - 使用 Algebird 库时,如何使用 Java lambda 返回字节数组?
- sql - 尝试根据日期范围查询数据,但仅查询一个时间点
- r - 错误:尝试在 jupyter notebook 中使用 olsrr 库
- node.js - 为什么在线几个小时后出现 503 错误?节点/快递
- reactjs - 查看未找到名称 div 的配置
- c - 通过strtok将ac字符串分解成token
- android - 如何防止在 ViewPager2 中滚动时单击?
- c# - “dotnet ef 数据库更新”失败(外键约束失败)
- protractor - 断言请求 URL 是使用量角器指定的 URL