我想要添加数字,但只能在指定的领导者之间添加。例如,如果输入字母B和E,我想要输出630。我希望它从B一直添加到E,但不包括E.所以程序会添加(140 + 125 + 365),它不包括最后一个数字。另一个例子是,如果C和G被输入,它将输出125 + 365 + 250 + 160)。
System.out.println("enter location 1");
String location1=in.nextLine();
System.out.println("enter location 2");
String location2=in.nextLine();
if (location1.equalsIgnoreCase("a"))
{
sum +=450;
}
else if (location1.equalsIgnoreCase("b"))
{
sum+=140;
}
else if (location1.equalsIgnoreCase("c"))
{
sum+=125;
}
else if (location1.equalsIgnoreCase("d"))
{
sum+=125;
}
else if (location1.equalsIgnoreCase("e"))
{
sum+=365;
}
else if (location1.equalsIgnoreCase("f"))
{
sum+=160;
}
else if (location1.equalsIgnoreCase("g"))
{
sum+=380;
}
else if (location1.equalsIgnoreCase("h"))
{
sum+=235;
}
else if (location1.equalsIgnoreCase("j"))
{
sum+=320;
}
else if (location1.equalsIgnoreCase("k"))
{
sum+=0;
}
if (location2.equalsIgnoreCase("a"))
{
sum2 +=450;
}
else if (location2.equalsIgnoreCase("b"))
{
sum2+=140;
}
else if (location2.equalsIgnoreCase("c"))
{
sum2+=125;
}
else if (location2.equalsIgnoreCase("d"))
{
sum2+=365;
}
else if (location2.equalsIgnoreCase("e"))
{
sum2+=250;
}
else if (location2.equalsIgnoreCase("f"))
{
sum2+=160;
}
else if (location2.equalsIgnoreCase("g"))
{
sum2+=380;
}
else if (location2.equalsIgnoreCase("h"))
{
sum2+=235;
}
else if (location2.equalsIgnoreCase("j"))
{
sum2+=320;
}
else if (location2.equalsIgnoreCase("k"))
{
sum2+=0;
}
答案 0 :(得分:1)
if
语句仅执行条件为真的分支。如果输入“d”,则只有else if (location2.equalsIgnoreCase("d"))
为真且仅添加该数字。如果你想要所有数字“介于”两个字母之间,你可以先将这些字母视为char
s,然后从较低的字母到较高的字母进行循环,并为每个字母添加任何数字。
正如@Takendarkk所说,地图可能会有所帮助。在这里,我将使用链接的地图(保留订单)。这是一些未经测试的伪代码:
import java.util.LinkedHashMap;
import java.util.Map;
// ...
LinkedHashMap<Character, Integer> valuePerCharacter = new LinkedHashMap<>();
valuePerCharacter.put('a', 450);
valuePerCharacter.put('b', 140);
// ... and so on...
int sum = 0;
for (Map.Entry<Character, Integer> e : valuePerCharacter.entrySet()) {
if (e.getKey() >= location1 && e.getKey() < location2) {
sum += e.getValue();
}
}