我是HashMaps
的新手,我帮助理解了如何在地图中添加和打印整数。然而,不是得到我想要的东西,我得到一些奇怪和不同的东西,我不确定如何解决。
输出
Rick Grimes
Rick Grimes rescued Carl 100pts!
Rick Grimes rescued Carl 100pts!Rick Grimes rescued Michone 50pts!
Characters rescued: Carl, Michone Total points: 10050
您可能会注意到,总分数只是分数的组合。这就是我想要的
渴望输出
Rick Grimes
Rick Grimes rescued Carl 100pts!
Rick Grimes rescued Michone 50pts!
Characters rescued: Carl, Michone Total points: 150
您在我的输出中可能会注意到的另一个问题是line 3
重复line 2
中的第一次救援,但首先我要关注第一个问题。
这是我的代码
GameDriver.java
import java.io.*;
import java.util.*;
import java.awt.*;
public class GameDriver {
public static void main(String[] args) throws FileNotFoundException {
Hero N = new Cop();
String s;
File f = new File (args[0]);
Scanner input = new Scanner(f);
while (input.hasNext()) {
s = input.next();
if (s.equalsIgnoreCase("h")) {
System.out.println(N.getHeroName());
}
if (s.equalsIgnoreCase("r")) {
String cn = input.next();
int pts = input.nextInt();
N.newMap.put(cn, pts);
System.out.println(N.rescue());
}
if (s.equalsIgnoreCase("v")) {
System.out.println(N.view());
}
}
}
}
总结发生在这个班级
Hero.java
import java.util.*;
import java.io.*;
import java.awt.*;
public abstract class Hero extends Character
{
private String heroname1;
public Hero() {
heroname1 = "Rick Grimes"; //the default player name
}
HashMap<String, Integer> newMap = new HashMap<String, Integer>();
public Hero(String newhero) {
if (newhero.length() > 0) {
heroname1 = newhero;
} else { heroname1 = "Rick Grimes"; } //defaulted as protagonist
}
public String getHeroName() {
return heroname1; //return the name
}
public String rescue() { //class to rescue people or things
String out = "".toString();
for(String _key : newMap.keySet()) {
out += heroname1 + " rescued " + _key + " " + newMap.get(_key) +!
}
return out;
}
public String toString() { //print
return heroname1;
}
public String view() {
Set<String> names = newMap.keySet();
StringBuilder sb = new StringBuilder("Characters rescued: ");
int i = 0;
for (String name : names) {
if (i == 0) {
sb.append(name);
i++;
} else {
sb.append(", ");
sb.append(name);
}
}
String printNames = sb.toString();
Collection<Integer> points = newMap.values();
StringBuilder sp = new StringBuilder("Total points: ");
int sum = 0;
for (Integer value : points) {
sum += value;
sp.append(value);
}
String printPoints = sp.toString();
return printNames + " " + printPoints ;
}
}
我做错了什么?请询问任何澄清!的谢谢!
答案 0 :(得分:3)
您只需在此处附加文字:
StringBuilder sp = new StringBuilder("Total points: ");
int sum = 0;
for (Integer value : points) {
sum += value;
sp.append(value);//you're wrong here.
}
你应该在变量总和之后附加。
StringBuilder sp = new StringBuilder("Total points: ");
int sum = 0;
for (Integer value : points) {
sum += value;
}
sp.append(sum);
附加值也应该是&#39; sum&#39;不是&#39;值&#39;;