2015-11-24 44 views
-2

我非常非常新的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; 
    } 
} 
+2

嘗試一下至少 – Tempux

+2

你的問題是什麼?有錯誤嗎?你堅持哪部分? – Atri

+0

我的程序打印出「假開始並以同一個字母結尾」。如果第一個和最後一個字符不相等,並且它打印出「真實的開始和結束於同一個字母」。如果第一個和最後一個字符是真的,我怎麼才能讓它打印出'單詞+開始和結束於同一個字母'? –

回答

1

看來你基本上已經知道了,但這裏有一個稍微更新的版本。

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(); 
     if(checkString(word)) { 
      System.out.printf("%s begins and ends with the same letter.\r\n" , word); 
     } else { 
      System.out.printf("%s does not begin and end with the same letter.\r\n", 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; 
    } 
} 
+0

我可以問\ r和\ n做什麼? –

+0

'\ r \ n'是打印新行的標準方式。它們分別代表回車和換行符。 –

相關問題