java - 将部分字符串转换为要在 if/else 语句中使用的字符

标签 java

我在学校做作业,虽然我已经检查了所有的书面 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++;
            }
        }
    }
}

最佳答案

只需将 golsilbro 转换为 char 而不是 Strings.

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/

相关文章:

java - Decimalformat:在 JTable 中不需要用逗号替换点

java - 使用 .append(string1 + string 2) 与 .append(string1).append(string2)

java - 有没有办法以不锁定 Swing 线程的方式调用 JXTable.packAll() ?

java - Java/Tomcat 多线程(?)问题中的 RESTful 服务

java - HttpClient 无法在 Tomcat 上运行,NoSuchMethodError org/apache/http/entity/ContentType

java - Q 查询后的输出数组将一些元素设置为零

java - 如何在客户端套接字连接上设置超时?

java - hdfs + solr安装报错cannot create core collection1

java - 无法在显示按钮列表的表单上添加背景颜色或图像 - Blackberry

java - 我可以使用什么工具向 EJB 2.1 代码生成多个线程来模拟连接池负载?