1
everyone。我在爲Java編程課程分配任務時遇到問題,並希望對此有所意見。Java迴文分配 - 布爾總是返回False值
對於該方法的分配pA的是創建僅使用字符串和字符方法的方法。因此,我編寫了以下方法,當我嘗試調用方法pA時,它會自動返回一個假值。我想我的循環可能有問題,但因爲我不確定,所以我想我會在這裏問一下,看你有什麼要說的。
在此先感謝您,爲您的時間。
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in); //Creates Scanner object to take user input
String pal; //String to contain user input
boolean test = false; //boolean to test if user input is a palindrome.
System.out.println("This program determines if your input is a palindrome!");
System.out.println("Please enter your input to see if it's a palindrome.");
pal = keyboard.nextLine();
pA(pal, test);
if (test == true)
{
System.out.println("Congratulations! You have a palindrome!");
}
else if (test == false)
{
System.out.println("Unfortunately, you do not have a palindrome.");
}
}
public static boolean pA(String pal, boolean test) //Part A of Assignment 7.
{
int l = pal.length(); //integer to contain length of string
int i; //Loop control variable
test = false;
for (i = 0; i < l/2; i++) //for loop that tests to see if input is a palindrome.
{
if (pal.charAt(i) == pal.charAt(l-i-1)) //Compares character at point i with respective character at the other end of the string.
{
test = true; //Sets boolean variable to true if the if statement yields true.
} else
test = false; //Otherwise, a false value is returned.
break;
}
return test; //Return statement for boolean variable
} //End pA
從這裏,當我嘗試運行程序,使用輸入「tubbut」當我得到了以下信息:
運行:
此程序確定,如果您的輸入是一個迴文!
請輸入您的意見,看它是否是迴文。
tubbut
不幸的是,你沒有迴文。
BUILD SUCCESSFUL(總時間:2秒)
這幫助了很多替代
;非常感謝你! – Brian 2014-09-25 22:11:04