如何从我的 switch case java 程序中得到总和?

How to get the sum out of my switch case java program?

这是我们的作业。我们必须使用 while 将 unicode 转换为十进制值。 我正在为输入使用 switch case,因此很容易划分每个输入,但我现在无法计算所有值的总和。

public class Exercise { 

    public static void main (String[] args) throws Exception
    {
        int uni = 0, code = 0, dec=0, sum=0;
        System.out.println("Please write a Unicode of the form \uxxxx");

        while ((uni = System.in.read()) != '\n') {
            code++;

            if (uni!='\' && code == 1) {
                System.out.println("You did not write \ correctly");   
                break;
            }

            if (uni!='u'&&code == 2) {
                System.out.println("You did not write u correctly");
                return;
            }

            if(code >=3 && code <=6)
            {
                if(uni >= '0' && uni <= '9'|| uni >= 'a'&&uni<='f')
                {
                    switch (code) {
                    case 3:
                        dec=uni*4096;
                        break;
                    case 4: 
                        dec=uni*256;
                        break;
                    case 5:
                        dec=uni*16;
                        break;
                    case 6:        
                        dec=uni*1;
                        break;
                    default:
                        Sytem.out.println("Too much values!");
                        break;
                }
            sum=sum+dec;
            }
            else
            {
                System.out.println("Wrong!!!");
                return;
            }           
         }          
     }        
    System.out.println(sum);
    }
}

一如既往,我们将不胜感激! :)

只要声明一个int变量(可能叫"sum")

int sum = 0;

在循环之外,每次计算新的 dec 时,将其添加到总和值。

sum = sum + dec;

然后在函数的最后,return或者打印sum的值。

sum = sum + dec; 必须 进入 while 循环,在 case 语句的末尾。这是您刚刚通过循环在 运行 上设置 dec 值的点。如果你将它留在 while 循环之外,那么你只会在 while 循环退出后将 dec 添加到它一次,而不是将每个值都添加到它。

您需要将字符 uni 转换为其数值 (0-15) 并使用它。

int digit = 0;
if ('0' <= uni && uni <= '9') {
    digit = uni - '0';
} else ('a' <= uni && uni <= 'f') {
    ... // 10-15
} else ('A' <= uni && uni <= 'F') {
    ...
}