[英]I'm having trouble with a loop, my error involving &&
我的指導是編寫一個代碼(用Java),該代碼查找介於1,000到9,999(任意4位數字)之間的代碼,並符合以下四個條件:
到目前為止,這就是我所擁有的。 我在//loop
部分下遇到錯誤:
C4PP10.java:27: error: bad operand types for binary operator '&&'"
是出現的錯誤。
在我的腦海中, &&
只是表示“和”,我是否使用不當?
這是我對Java類作業BTW的介紹。
public class C4PP10
{
public static void main(String[] args)
{
//variables
int first=1;
int second=0;
int third=0;
int fourth=0;
int total = first * 1000 + second * 100 + third * 10 + fourth;
boolean fourDifferentDigits = false;
boolean thousandsPlaceX3TensPlace = false;
boolean odd = false;
boolean sum = false;
boolean correctAddress = false;
//loop
while (correctAddress = false)
{
fourth = fourth + 1;
if (fourth == 10)
{
fourth = 0 && third = third + 1;
}//end if
if (third == 10)
{
third = 0 && second = second + 1;
}//end if
if (second == 10)
{
second = 0 && first = first + 1;
total = first * 1000 + second * 100 + third * 10 + fourth;
}//end if
}//end loop
//testing
if ( first != second && first !=third && first !=fourth && second !=third && second !=fourth && third != fourth )
{
fourDifferentDigits = true;
}//end if
if (first == third*3)
{
thousandsPlaceX3TensPlace = true;
}//end if
if (fourth%2 != 0)
{
odd = true;
}//end if
if ( first + second + third + fourth == 27 )
{
sum = true;
}//end if
if (fourDifferentDigits=true && thousandsPlaceX3TensPlace=true && odd=true && sum=true)
{
correctAddress = true;
}//end if
if (correctAddress = true)
{
System.out.println("The Riddler plans to strike " + total + " Pennsylvania Avenue!");
}
}//end main
}//end class
這么多格式錯誤,請確保比較時使用==
而不是=
來表示布爾語句,並確保使用縮進以提高可讀性。 僅在邏輯語句中使用&&
,而不是在語句中添加。 您還可以在開始時使用逗號( ,
)定義多個變量,而不必每次都鍵入int
。
public class C4PP10
{
public static void main(String[] args)
{
//variables
int first = 1, second = 0, third = 0, fourth = 0;
int total = first * 1000 + second * 100 + third * 10 + fourth;
boolean fourDifferentDigits = false, thousandsPlaceX3TensPlace = false;
boolean odd = false, sum = false, correctAddress = false;
while (correctAddress == false) // or while (!(correctAddress))
{
fourth = fourth + 1;
if (fourth == 10)
{
fourth = 0;
third = third + 1;
}
if (third == 10)
{
third = 0
second = second + 1;
}
if (second == 10)
{
second = 0
first = first + 1;
total = first * 1000 + second * 100 + third * 10 + fourth;
}
}
if (first != second && first != third && first != fourth && second !=third && second !=fourth && third != fourth)
{
fourDifferentDigits = true;
}
if (first == third * 3)
{
thousandsPlaceX3TensPlace = true;
}
if (fourth % 2 != 0)
{
odd = true;
}
if (first + second + third + fourth == 27)
{
sum = true;
}
if (fourDifferentDigits == true && thousandsPlaceX3TensPlace == true && odd == true && sum == true)
{
correctAddress = true;
}
if (correctAddress == true)
{
System.out.println("The Riddler plans to strike " + total + " Pennsylvania Avenue!");
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.