import java.util.*;
public class Practice_7_4
{
public static void main(String[] args)
{
int counter = 0;
String statement;
int length;
char space = ' ';
String word = "";
char letter;
char check;
int count = 0;
Scanner input = new Scanner(System.in);
System.out.print("Enter a string: ");
statement = input.nextLine();
length = statement.length();
System.out.print("Entered String: " + statement);
while(counter <= length-1)
{
letter = statement.charAt(counter);
for(int charcount = 0; charcount <= length-1; charcount++)
{
check = statement.charAt(charcount);
if(letter != ' ' && charcount < length-1)
{
if(Character.toLowerCase(letter) == Character.toLowerCase(check))
{
count+=1;
}
}
}
if(letter != ' ')
System.out.printf("\nletter %c:\t %d", letter, count);
counter += 1 ;
count = 0;
}
}
}
Output of "I am tired" in the program:
letter i: 2
letter a: 1
letter m: 1
letter t: 1
letter i: 2
letter r: 1
letter e: 1
letter d: 0
我的问题是如何删除重复的字母&#39; i&#39;从被打印两次,我如何让我的代码计算最后一个字符而不是产生0?这是我唯一的问题,但它说添加更多细节,所以我要打字,直到我达到最低金额。
答案 0 :(得分:0)
您可以将Collection用于此目的。
public static void main(String[] args) {
int occurrence = 0;
String arr="I am tired";
List<Character> nos =new ArrayList<>();
for(int i=0;i<arr.length();i++){
nos.add(Character.toLowerCase(arr.charAt(i)));
}
Set<Character> uniqueNos = new HashSet<>(nos);
for(char temp:uniqueNos) {
for(char tempList:nos) {
if(String.valueOf(temp).equalsIgnoreCase(String.valueOf(tempList))) {
occurrence++;
}
}
if(temp!=' ')
System.out.println(temp+ " Appears "+occurrence +" times");
occurrence = 0;
}
}
首先,我们创建一个Character to String的Arraylist。然后将每个字符存储到列表中。
然后从list.hashset创建一个hashset,只包含唯一数据。
然后从hashset中选择一个char并与list all项进行比较,如果匹配则再增加计数器。
答案 1 :(得分:0)
以下程序可以完成这项工作。
import java.util.*;
public class Practice_7_4 {
public static void main(String[] args) {
int counter = 0;
String statement;
int length;
char space = ' ';
String word = "";
char letter;
char check;
int count = 0;
Scanner input = new Scanner(System.in);
System.out.print("Enter a string: ");
statement = input.nextLine();
char c[] = statement.toCharArray();
length = statement.length();
System.out.print("Entered String: " + statement);
while (counter <= length - 1) {
letter = c[counter];
for (int charcount = 0; charcount <= length - 1; charcount++) {
check = c[charcount];
if (letter != ' ' && charcount <= length - 1) {
if (Character.toLowerCase(letter) == Character.toLowerCase(check)) {
//System.out.println(true);
count += 1;
c[charcount]=' ';
}
}
}//System.out.println(Arrays.asList(c).toString());
if (letter != ' ')
System.out.printf("\nletter %c:\t %d", letter, count);
counter += 1;
count = 0;
}
System.out.println("hello"+statement);
}
}
我做了很少的改变:
制作字符串的字符数组,以便能够用空格替换已经看过的字符。
在找到的每个地方用空格('')替换正在搜索的字符,从而增加计数。