我应该要求用户输入一个字符串,我应该解析字符串并跟踪字母表的数量。所以如果用户输入字符串“abee” 它将输出显示为:
a: 1
b: 1
c: 0
e: 2
到目前为止,我已经能够获取字符串并解析它并将元素存储到数组中。而且我已经能够使用for循环一次打印出每个字母。现在我面临的问题是,当它打印出字母以及短语中存在多少字母时,数字不匹配。例如,如果我输入字母:“abccddee” 打印出来:
a: 1
b: 1
c: 1
c: 0
d: 0
d: 0
e: 0
e: 0
出于测试目的,我使用自己的字符串而不是使用扫描仪。
import java.util.Scanner;
public class CountLetters
{
public static void main(String[] args)
{
//create arrays
String[] upper = new String[25];
String[] lowerChar = new String[25];
int [] lowerCharNum = new int[25];
Scanner input = new Scanner(System.in);
System.out.println("Please enter a phrase");
//grab phrase from user
String phrase = "abccddee";
//create array with the size of the phrase entered from user
String[] letters = new String[phrase.length()];
System.out.println("letters length: " + letters.length);
//separate every letter in phrase and store it into array "letters"
letters = phrase.split("");
for(int i=0; i<letters.length; i++)
{
lowerChar[i] = letters[i];
switch(letters[i])
{
case "a":
lowerCharNum[0] += 1;
break;
case "b":
lowerCharNum[1] += 1;
break;
case "c":
lowerCharNum[2] += 1;
break;
case "d":
lowerCharNum[3] += 1;
break;
case "e":
lowerCharNum[4] += 1;
break;
case "f":
lowerCharNum[5] += 1;
break;
}//end of switch
System.out.println(lowerChar[i] + ": " + lowerCharNum[i]);
}
}//end of main method
}//end of class
答案 0 :(得分:4)
您可以使用java Collection
的{{1}}而不是使用简单数组。
HashMap
使用HashMap
循环进行主要工作,将检查for
中是否已存在Character
,如果是,那么我们将获得与HashMap
相关联的值,并将使用现有值加1,如果Character
不存在,那么我们会在Character
中放置Character
并存储初始计数1与相关的角色。
HashMap
你正在使用数组,你需要首先在声明时初始化这将创建一个额外的内存空间,如果没有遇到所有26个字母并且根据你在问题中提供的代码将会浪费正在分配3个数组,因此需要更多的内存,所以这个解决方案只需要 HashMap<Character, Integer> lettersCount = new HashMap<>();
String phrase = "abccddee";
int length = phrase.length();
int count = 1;
for (int i = 0; i < length; i++) {
int integer = 0;
char charAt = input.charAt(i);
if (!lettersCount.containsKey(charAt)) {
lettersCount.put(charAt, 0);
}
integer = lettersCount.get(charAt);
integer = initialCount + integer;
lettersCount.put(charAt, integer);
}
System.out.println(lettersCount);
(HashMap
将根据HashMap
中插入的键和值分配内存)和HashMap
循环只计算for
的出现次数并在程序中进一步使用它将会更加容易。
答案 1 :(得分:3)
您正在for循环中打印。您应该在该循环之外打印频率。
您使用的方法不可扩展。鉴于该短语仅包含大写和小写英文字母,您必须在开关中编写52个case语句。
更好的方法是使用ASCII编码为您的目的。你可以在以下几行中找到一些东西:
int frequency[] = new int[128];
for (int i = 0; i < phrase.length(); i++) {
frequency[(int) phrase.charAt(i)]++;
}
在此方法中,frequency
数组用于计算phrase
字符串中前128个ASCII字符的出现次数。操作(int) phrase.charAt(i)
只是将字符转换为相应的ASCII码,我们将该字符的计数器增加1.在处理结束时,frequency
数组将包含前128个ASCII字符的出现次数。给定的phrase
字符串。只需打印此频率即可获得所需的输出。
答案 2 :(得分:2)
print语句必须在 while for循环之外。
System.out.println(lowerChar[i] + ": " + lowerCharNum[i]);
更新: 你需要先解析整个字符串,然后开始打印。
import java.io.*;
import java.util.*;
class CountLetters {
public static void main(String[] args)
{
int i;
//create arrays
String[] upper = new String[25];
String[] lowerChar = new String[25];
int [] lowerCharNum = new int[25];
Scanner input = new Scanner(System.in);
System.out.println("Please enter a phrase");
//grab phrase from user
String phrase = "abccddee";
//create array with the size of the phrase entered from user
String[] letters = new String[phrase.length()];
System.out.println("letters length: " + letters.length);
//seperate every letter in phrase and store it into array "letters"
letters = phrase.split("");
for(i=0; i<letters.length; i++)
{
lowerChar[i] = letters[i];
switch(letters[i])
{
case "a":
lowerCharNum[0] += 1;
break;
case "b":
lowerCharNum[1] += 1;
break;
case "c":
lowerCharNum[2] += 1;
break;
case "d":
lowerCharNum[3] += 1;
break;
case "e":
lowerCharNum[4] += 1;
break;
case "f":
lowerCharNum[5] += 1;
break;
}//end of switch
}
for(i=0;i<5;i++)
System.out.println(lowerChar[i] + ": " + lowerCharNum[i]);
}//end of main method
}//end of class
答案 3 :(得分:1)
您使用数组的解决方案有点复杂。通过使用Map,我们可以直接将遇到的字符与它们遇到的次数相关联,从而使得非常直接地增加计数器并输出计数器而无需在不同的数组中查找索引。
@login_required
def profile_edit(request):
truck_name = Product.objects.get(user=request.user)
try:
truck_form = RegisterTruckForm(instance=truck_name)
except ObjectDoesNotExist:
truck_form = RegisterTruckForm()
if request.method == 'GET':
if truck_name is not None:
truck_form = RegisterTruckForm(instance=truck_name)
else:
truck_form = RegisterTruckForm()
context = {
'truck_form': truck_form,
'truck_name': truck_name,
}
return render(request, 'accounts/profile_edit.html', context)
elif request.method == 'POST':
if truck_name is not None:
truck_form = RegisterTruckForm(request.POST, request.FILES,instance=truck_name)
else:
truck_form = RegisterTruckForm(request.POST, request.FILES)
if truck_form.is_valid():
truck_name = truck_form.save(commit=False)
truck_name.product = Product.objects.get(user=request.user)
truck_form.save_m2m()
truck_name.save()
return HttpResponseRedirect('/accounts/profile')
return render_to_response('accounts/profile_edit.html', {'truck_form': truck_form}, context_instance=RequestContext(request))
答案 4 :(得分:0)
HashMap
-以无序方式存储键和值,并且contains only unique keys.
TreeMap
-以自然顺序和contains only unique keys.
LinkedHashMap
-按键插入和contains only unique keys.
满足此要求的适当数据结构将是Map
。如果要保持字母在字符串中出现的顺序,可以使用LinkedHashMap,如果字母顺序无关紧要,则可以使用HashMap。我在示例中使用LinkedHashMap。
public class Test {
public static void main(String[] args) {
//Taking the input from the user
System.out.println("Enter the String"); //I am entering "abccddee" for your example
Scanner sc = new Scanner(System.in);
String input = sc.next();
//LinkedhashMap preserves the order in which input was supplied
LinkedHashMap<Character, Integer> lhm = new LinkedHashMap<Character, Integer>();
for(int i=0; i<input.length(); i++){
//method get will return null if the letter is not available at the given index else it will return the count
Integer j = lhm.get(input.charAt(i));
//If the chracter was not present in the String
if(j==null)
lhm.put(input.charAt(i),1);
//If the character was present in the String
else
lhm.put(input.charAt(i),j+1);
}
for(Character c : lhm.keySet())
System.out.println(c+": "+lhm.get(c)+" ");
}
}
输出将是:
a: 1
b: 1
c: 2
d: 2
e: 2