以我的第一個Java類,我堅持愚蠢。我正在做迴文項目。這個邏輯看起來不錯。無論哪種情況都顯示爲True。我究竟做錯了什麼?Java作業。布爾邏輯的問題
呼叫:
boolean result = check(input);
或在該方法本身:
public static void display(boolean result, String palindrome)
{
if (result = true)
{
JOptionPane.showMessageDialog(null, palindrome
+ " is a palindrome.");
} else
JOptionPane.showMessageDialog(null, palindrome
+ " is not a palindrome.");
}
這裏是整個代碼: 進口javax.swing.JOptionPane中;
public class Palindrome
{
public static void main(String args[])
{
// declare variables
// call methods
String input = retrieveInput();
boolean result = check(input);
display(result = false, input);
finish();
}
// Accepts and validates input
public static String retrieveInput()
{
// declare variables
int length;
String palindrome = null;
boolean done = false;
while (!done)
{
try
{
// user input
palindrome = JOptionPane.showInputDialog(null,
"Please enter a 5 digit integer:");
length = palindrome.length();
// data validation
if (length != 5)
{
throw new NumberFormatException();
} else
done = true;
}
catch (NumberFormatException e)
{
JOptionPane.showMessageDialog(null,
"Error. Please enter a 5 digit integer", "Error",
JOptionPane.INFORMATION_MESSAGE);
}
}
return palindrome;
}
public static Boolean check(String palindrome)
{
// determine if palindrome
int left = 0;
int right = palindrome.length() - 1;
while (left < right)
{
if (palindrome.charAt(left) != palindrome.charAt(right))
return false;
left++;
right--;
}
return true;
}
// The output method displays commission and sales
public static void display(boolean result, String palindrome)
{
if (result = true)
{
JOptionPane.showMessageDialog(null, palindrome
+ " is a palindrome.");
} else
JOptionPane.showMessageDialog(null, palindrome
+ " is not a palindrome.");
}
// finish() method exits program
public static void finish()
{
System.exit(0);
}
}
「請輸入5位數的整數」 你的意思是像12345? 整數只是一個數字。我相信你的意思是一個5個字的單詞? –
'if(result = true)'不能用Java編譯。你確定你發佈了真實的代碼嗎? –
Daniel Bo,是的,這條指令絕對要求整數,完全像12345(或12321爲有效迴文 – user2802785