小编典典

由于数据类型而导致循环在计算之前退出

java

我的程序规格如下。1.所有四个数字都不同。2.千位数字是十位数的三倍。3.数字是奇数。4.数字的总和是27。我遗漏了整个程序的一些代码。它具有干净的编译器,但运行时会自动终止。我认为问题出在数据类型的转换中。

int randomNumber = rand.nextInt(9000) + 1000;
String randomString;
boolean found = true;

while (found)
{

// converting to string to find position of digits and value        
randomString = String.valueOf(randomNumber);

// converting to char to transfer back to in while knowing the position of the digits 
char position0a = randomString.charAt(0);
char position1a = randomString.charAt(1);
char position2a = randomString.charAt(2);
char position3a = randomString.charAt(3);

// coverted back to int
int position0 = Character.getNumericValue(position0a);
int position1 = Character.getNumericValue(position1a);
int position2 = Character.getNumericValue(position2a);
int position3 = Character.getNumericValue(position3a);

int sumCheck = position0a + position1a + position2a + position3a;
int digit30Check = 3 * position2;

//checking addition to 27
String sumCheck27 = "27";
String sumCheck28 = String.valueOf(sumCheck);

// checking all digits are different
if (position0 != position1 && position0 != position2 && position0 != position3  &&

position1 != position2 && position1 != position3 && position2 != position3) 
{
if (position3 != digit30Check) // check if the digit in the thousands place 3 * tens
{
    if (sumCheck27.equals(sumCheck28)) // check if the sum is 27
    {
        if (position0 != 1 && position0 != 3 
&& position0 != 5 && position0 != 7 &&      
position0 != 9 && position1 != 1 && position1 != 3 
&& position1 != 5 && position1 != 7 && 
position1 != 9 && position2 != 2 && position2 != 3 
&& position2 != 5 && position2 != 7 && 
position2 != 9 && position3 != 3 && position3 != 3 && 
position3 != 5 && position3 != 7 && position3 != 9)
        { 
// checks for odd digits
         found = false;
         System.out.println(randomNumber);

        }
        else 
        randomNumber = rand.nextInt(9000) + 1000;
    }
    else 
    randomNumber = rand.nextInt(9000) + 1000;               
}
else 
randomNumber = rand.nextInt(9000) + 1000; 
}
else 
 randomNumber = rand.nextInt(9000) + 1000;

 // end while
 }

阅读 205

收藏
2020-11-30

共1个答案

小编典典

boolean found = false;

while (found)

仅此一项就确保了while循环将永远不会进入,因为它found是false。while循环中的任何内容都没有任何区别,因为它将永远不会执行。

你可能想写

while (!found)

除了此错误外,您的情况也过于复杂。这是您可以简化它们的方法:

if ((position0 == (3 * position2)) && // note that position0 is the "thousands place", not position3
    ((position0+position1+position2+position3) == 27) && // sum of digits
    (position3 % 2 == 1) && // odd number
    (position0 != position1 && position0 != position2 && position0 != position3  &&
     position1 != position2 && position1 != position3 && position2 != position3)) { // different digits
    found = true;
}
2020-11-30