上我的第一个 Java 课程后,我陷入了愚蠢的境地。我正在做回文项目。这个逻辑看起来不错。在任何一种情况下都显示 True。我究竟做错了什么?
称呼:
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.");
}
这是整个代码: import 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);
}
}