Java不会为此运行循环

时间:2019-11-05 18:43:48

标签: java for-loop fractions

这就是重要的代码完整性

       int dom = Integer.parseInt(Domin.getText());
       double fraction = Integer.parseInt(Numer.getText())/Integer.parseInt(Domin.getText());
       String currentlow = "";
       System.out.println("TEST");


       for (int i = 0; i >= dom;i++){ //ok the problem wasn't that it was > dom instead of >= dom
           System.out.println("dummy"); //this doesn't print and it would print every time if it was running the for loop.
           if((num % i == 0)&&(dom % i == 0)){ //this just = checks to see that there's no remainder (like 5/5)
               System.out.println("true"); //this for some reason never triggers even though i'm testing with 5/25
               if ((num/i)/(dom/i) == fraction){ //this is a dummy check to make sure it doesn't round improperly
                   currentlow = String.valueOf(num/i) + "/" + String.valueOf(i); //this sets the value but isn't the problem since the console never says "true"
                    System.out.println(currentlow); //nother dummy check
               }
           }
       }

根据需要编辑注释,但是基本上for循环应该使它除以除主导符之外的所有数字,但是它甚至不会打开for循环(它不会打印“ dummy” “或” true“,它应该在我的测试中将其打印24次时)不能弄清楚为什么

2 个答案:

答案 0 :(得分:1)

您的for循环条件看起来不对。您的开始条件为i = 0,但结束条件为i >= dom。如果dom是任何大于0的整数,则for循环将永远不会执行,因为我不能同时为0和大于或等于大于0的数字。我想你的意思是说i <= dom?< / p>

答案 1 :(得分:0)

您在这里有一些缺陷。首先,正如其他人指出的那样,这是错误的:

for (int i = 0; i >= dom;i++)

只有dom0的情况下,这才真正起作用(在这种情况下,它将只运行一次)。如果dom大于0,则i将永远不会大于或等于它。另一方面,如果dom为负,则i总是大于 ,因为您每次迭代都在进行i++

第二,您做的划分不正确。结果如下:

double x = Integer.parseInt("3") / Integer.parseInt("4");
System.out.print(x); // Prints 0.0

实际上是0.0,因为它正在执行整数除法。但是,结果是:

double x = (double)Integer.parseInt("3") / Integer.parseInt("4");
System.out.print(x); // Prints 0.75

是预期的0.75

您可以在代码中的多个位置进行此操作。