如果等于,则检查第一个和最后一个char的方法

时间:2015-11-24 23:24:46

标签: java printf

我对java非常新,我有这个指示:

定义并测试一个名为checkString的方法,该方法将单词作为参数接收并检查String是否以相同的字母开头和结尾。如果两个字母都相同,则该方法返回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 个答案:

答案 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;
   }
}

答案 1 :(得分:-2)

如果接收到的字符串的第一个字母和最后一个字母相同,则该方法将返回true。否则会返回false。主要内容:执行所需的定义并要求用户输入字符串。