例如,假设我有以下String
String S = "5,a\n" +
"6,b\n" +
"9,a";格式总是相同的-一个数字,然后逗号,然后一个字符,然后行结束字符。
用于循环字符串中的每一行
for(String a : S.split("\\n")){}我想学习最高数量的字符,当按字符分组时。例如,只有一个"b",所以值是6;而"a“有两行,所以它的值是5+9= 14。因为这里的最大值是14,所以我想找出"a”和14,并将它们保存在变量中。
发布于 2016-05-24 01:09:58
您可以这样做:
public static void main (String[] args) throws java.lang.Exception
{
String S = "5,a\n" +
"6,b\n" +
"9,a";
String[] lines = S.split("\\n");
Map<String, Integer> map = new HashMap<String, Integer>();
for( String t : lines )
{
String[] e = t.split(",");
Integer digit = Integer.parseInt(e[0]);
String c = e[1];
if ( map.get(c) != null )
{
Integer val = map.get(c);
val += digit;
map.put( c, val );
}
else
{
map.put( c, digit );
}
}
int max = 0;
String maxKey = null;
for ( String k : map.keySet() )
{
if ( map.get(k) > max )
{
max = map.get(k);
maxKey = k;
}
}
System.out.println("The maximum key is : " + maxKey );
System.out.println("The maximum value is : " + max );
}产出如下:
The maximum key is : a
The maximum value is : 14发布于 2016-05-24 01:09:01
使用HashMap来存储每一对,并以字母作为密钥。如果条目不存在,则put第一个数字。如果存在,则get条目并添加数字,然后put求和。
import java.util.HashMap;
import java.util.Map;
public class ParseTest {
public static void main(String[] args) {
String S = "5,a\n" + "6,b\n" + "9,a";
String maxKey = null;
int maxVal = 0;
Map<String, Integer> sums = new HashMap<>();
for (String a : S.split("\\n")) {
String[] split = a.split(",");
int value = Integer.parseInt(split[0]);
String key = split[1];
if (sums.containsKey(key)) {
sums.put(key, sums.get(key) + value);
} else {
sums.put(key, value);
}
if (sums.get(key) > maxVal) {
maxVal = sums.get(key);
maxKey = key;
}
}
System.out.println("Max key: " + maxKey + ", Sum: " + maxVal);
}
}发布于 2016-05-24 01:40:28
在完成我的回答后,我发现很多类似的答案都被张贴了出来:)。总之,我的解决方案是:
public static void main(String[] args) {
String S = "5,a\n6,b\n9,a";
Map<String, Integer> map = new HashMap<String, Integer>();
String highestAmountChar = "";
int highestAmount = 0;
for (String str : S.split("\\n")) {
String[] amountChar = str.split(",");
if (map.get(amountChar[1]) == null) {
map.put(amountChar[1], Integer.parseInt(amountChar[0]));
} else {
map.put(amountChar[1], map.get(amountChar[1]) + Integer.parseInt(amountChar[0]));
}
if (highestAmount < map.get(amountChar[1])) {
highestAmount = map.get(amountChar[1]);
highestAmountChar = amountChar[1];
}
}
System.out.println("The character " + highestAmountChar + " has highest amount " + highestAmount);
}https://stackoverflow.com/questions/37402787
复制相似问题