使用while循环时如何解决此错误消息?

时间:2019-10-02 18:41:20

标签: java

我有一个练习,必须编写一种方法来计算时钟的分针和时针之间的角度。分钟参数为0-60,小时参数为0-24。我想我已经解决了,但是我是Java新手,语法错误(我认为)有问题

public class W1_E3 {
    public static int timeToAngle(int hours, int minutes){
       while (hours > 12) {
           hours = hours - 12;
        } else {
           minute_val = hours * 5;
           return minute_val * 6;
       }
    }
    public static void main(String[]args){
        System.out.println(timeToAngle(3, 0));
    }
}

当我去编译时,我得到以下信息:

.Exception in thread "main" java.lang.Error: Unresolved compilation problems: Syntax error on token "else", delete this token minute_val cannot be resolved to a variable minute_val cannot be resolved to a variable at W1_E3.timeToAngle(W1_E3.java:5) at W1_E3.main(W1_E3.java:11)

4 个答案:

答案 0 :(得分:0)

您从未实例化minute_val-将minute_val更改为minutes

此外,您在else之前缺少if。

答案 1 :(得分:0)

while循环没有else语句。您是说,而不是一段时间吗?

答案 2 :(得分:0)

只要给定条件为真,C#中的while循环语句就会重复执行目标语句。

您不能在while上使用else,需要if才能使用else

正确的代码(缺少变量的声明):

public class W1_E3 {
    public static int timeToAngle(int hours, int minutes){
       if (hours > 12) {
           hours = hours - 12;
        } else {
           minute_val = hours * 5;
           return minute_val * 6;
       }
    }
    public static void main(String[]args){
        System.out.println(timeToAngle(3, 0));
    }
}

C#循环:https://www.tutorialspoint.com/csharp/csharp_loops.htm

C#if / else:https://www.tutorialspoint.com/csharp/csharp_decision_making.htm

答案 3 :(得分:0)

您似乎想要在while循环中进行重复的数学运算,然后再执行其他操作。在else循环中包含while是无效的。

下面的代码示例似乎符合您的预期逻辑–对hours进行数学运算,直到hours > 12不再成立,然后分别执行其他一些数学运算并返回值。只需将事情分开,这样就可以在while循环完成后执行第二组操作。

public static int timeToAngle(int hours, int minutes) {
    while (hours > 12) {
        hours = hours - 12;
    }

    int minute_val = hours * 5;
    return minute_val * 6;
}