我非常非常新的Java,和我有這樣的指令:方法檢查第一和最後一個字符,如果等於
定義和測試一個名爲checkString方法,將採取這個詞作爲參數,並檢查是否字符串以相同的字母開頭和結尾。如果兩個字母都相同,則方法返回true,否則返回false(返回布爾值)。該程序將小寫字母和大寫字母視爲等效。
此外,我需要使用printf語句
樣本輸出將是:
類型的字符串:ABBA
ABBA開始,以相同的字母
結束這是我到目前爲止:
import java.util.Scanner;
public class Excercise5 {
public static void main(String[] arg) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Type a string: ");
String word = keyboard.nextLine();
System.out.printf ("%s begins and ends with the same letter." , checkString(word));
}
public static boolean checkString (String word) {
int length = word.length();
word = word.toUpperCase(); //since you are testing them as upper case
char firstLetter = word.charAt(0);
char lastLetter = word.charAt(length - 1);
return firstLetter == lastLetter;
}
}
嘗試一下至少 – Tempux
你的問題是什麼?有錯誤嗎?你堅持哪部分? – Atri
我的程序打印出「假開始並以同一個字母結尾」。如果第一個和最後一個字符不相等,並且它打印出「真實的開始和結束於同一個字母」。如果第一個和最後一個字符是真的,我怎麼才能讓它打印出'單詞+開始和結束於同一個字母'? –