我试图检查输入的字符串是否是回文
如果它显示一些积极的东西 如果不是......一些负面的(无效的)
我目前两次得到的答案都无效(无论输入什么) 我不太确定 for 循环或 boolean 语句是否有问题。
//ACTION FROM BUTTON PERFORMED HERE
private void ButtonActionPerformed(ActionEvent evt) {
//creating variables
String myString = textField1.getText();
int stringLength = myString.length();
char arrayOne[] = new char[stringLength];
char arrayTwo[] = new char[stringLength];
boolean palindrome = false;
//for loop to setup ARRAY ONE
for(int i = 0; i < stringLength-1; i++){
arrayOne[i] = myString.charAt(i);
}
//for loop to setup ARRAY TWO
for(int i = stringLength-1; stringLength-1 > i; i--){
arrayTwo[i] = myString.charAt(i);
}
//for loop checking if array indexes are equivalent in value (char)
for(int i = 0; i < stringLength-1; i++){
if(arrayOne[i] != arrayTwo[i]){
palindrome = false;
}
else{
palindrome = true;
}
}
//assigning text to the text boxes based on boolean palindrome
if(palindrome == true){
textField2.setText("Valid");
}
if(palindrome ==false){
textField2.setText("Invalid");
}
}
}
我认为我的评论很体面
最佳答案
改变
for(int i = stringLength-1; stringLength-1 > i; i--)
至
for(int i = 0; i < stringLength-1; i++)
并改变
for(int i = stringLength-1; i-1 > 0; i--)
至
for(int i = stringLength-1; i-1 >= 0; i--)
编辑:
那是一场调试盛宴!
这是一个工作代码:
String myString = textField1.getText();
int stringLength = myString.length();
char arrayOne[] = new char[stringLength];
char arrayTwo[] = new char[stringLength];
boolean palindrome = true;
//for loop to setup ARRAY ONE
for(int i = 0; i <= stringLength-1; i++){
arrayOne[i] = myString.charAt(i);
}
//for loop to setup ARRAY TWO
for(int i = stringLength-1, pos = 0; i >= 0; i--, pos++){
arrayTwo[pos] = myString.charAt(i);
}
//for loop checking if array indexes are equivalent in value (char)
for(int i = 0; i <= stringLength-1; i++){
if(arrayOne[i] != arrayTwo[i]){
palindrome = false;
break;
}
}
//assigning text to the text boxes based on boolean palindrome
if(palindrome == true){
textField2.setText("Valid");
}
else{
textField2.setText("Invalid");
}
关于java - 检查字符串中的回文(java)(菜鸟状态),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15018030/