当/如果循环在课堂上不起作用



我正在学习java,但我的if代码无法运行。

在下面的代码中,我试图确定一个数字(变量num)是否是一个三角形数字(1,3,6,10等)。 代码应该贯穿并给出"是三角形"。 然而,它不断吐出空。

我知道这不是执行此代码的最有效方法,但我正在尝试学习如何使用类。

public class HelloWorld {
  public static void main(String[] args) {
    class NumberShape {
        int num = 45;
        int tri = 0;
        int triplus = 0;
        String triresult;
        public String triangle() {
            while (tri < num) {
                if (tri == num) {
                    triresult =  "Is a Triangle";
                    System.out.println("Is a Triangle");
                } else if (tri + (triplus + 1) > num){
                    triresult =  "Is Not a Triangle";
                } else {
                    triplus++;
                    tri = tri + triplus;
                }
            }
            return triresult;
        }
    }
    NumberShape result = new NumberShape();
    System.out.println(result.triangle());
    }
}

感谢您提供的任何帮助。

试试这个代码:

public class HelloWorld {
  public static void main(String[] args) {
            class NumberShape {
                int num = 10;//Try other numbers
                int tri = 0;
                int triplus = 0;
                int res = 0;
                String triresult =  "Is Not a Triangle";
                int[] tab= new int[num];

                public String triangle() {
                    //to calculate the triangle numbers 
                     for(int i = 0; i<num; i++){
                         res = res + i;
                         tab[i]=res;
                     }
                     //To check if num is a triangle or not
                     for(int i = 0; i<tab.length; i++){
                         System.out.println(">>  " + i + " : " + tab[i]);
                         if(tab[i]== num){
                             triresult =  num + " Is a Triangle";
                             break;//Quit if the condition is checked
                         }else{
                             triresult =  num + " Is Not a Triangle";
                         }
                     }
                    return triresult;
                }
            }
            NumberShape result = new NumberShape();
            System.out.println(result.triangle());
            }
}

希望这有帮助。

仔细执行循环。 您可能会看到

,在这种情况下
(tri < num) 

失败了,因此你掉出了循环,而

(tri == num)

(tri + (triplus + 1) > num)

两者都失败了,所以在你掉出来之前没有设置任何文本。

您可能希望在方法中仅对tri进行if测试,而不是对tri的修改,以减少自己对代码工作方式的混淆。

最新更新