我在学校做作业,虽然我已经检查了所有的书面 Material ,但我终其一生都不知道如何做。我们应该输入像“0123 B”这样的字符串,字符串末尾的 B 应该代表青铜,然后将++ 添加到青铜整数。然后打印奖牌数。
我的问题是,我试图从字符串(B、S 或 G)中取出最后一个字符,然后添加到该字符串中,但事实是,它是一个字符串,而不是一个字符。所以我不能使用 medal.charAt(5)。
下面是我的代码:
已编辑,代码即解决方案
import java.util.Scanner;
public class CountMedals {
public static void main(String[] args) {
int bronze = 0;
int silver = 0;
int gold = 0;
int totalMedals = 0;
int incorrectMedals = 0;
char gol = 'G';
char sil = 'S';
char bro = 'B';
String medal = " ";
Scanner in = new Scanner(System.in);
System.out.println("Please enter the event number followed by the first letter of the medal type." +
" (I.E. \"0111" + " B\"). Type exit once completed");
while (!medal.equals("")) {
medal = in.nextLine();
if (medal.charAt(medal.length() - 1) == bro)
{
bronze++;
totalMedals++;
}
else if (medal.charAt(medal.length() - 1) == sil)
{
silver++;
totalMedals++;
}
else if (medal.charAt(medal.length() - 1) == gol)
{
gold++;
totalMedals++;
}
else if (medal.equals("exit"))
{
System.out.println("Gold medals: " + gold);
System.out.println("Silver medals: " + silver);
System.out.println("Bronze medals: " + bronze);
System.out.println("Total medals: " + totalMedals);
System.out.println(incorrectMedals + " incorrect medal(s) entered.");
}
else{
incorrectMedals++;
}
}
}
}
最佳答案
只需将 gol
、sil
和 bro
转换为 char
而不是 String
s.
char gol = 'G';
char sil = 'S';
char bro = 'B';
更改后,您应该可以使用
medal.charAt(5) == gol
没问题。
编辑
为了让它更通用,你可以使用
medal.charAt(medal.length() - 1) == gol
这将始终提取最后一个字符,从而避免输入少于 5 个索引的错误。
关于java - 将部分字符串转换为要在 if/else 语句中使用的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39906629/