【问题标题】:I'm trying to check if a word is abecedarian using compareTo我正在尝试使用 compareTo 检查一个单词是否是初学者
【发布时间】:2015-04-25 14:30:07
【问题描述】:

我想保持我的程序几乎相同。 我使用了很多 String 方法,例如 charAtsubstringindexOf。 如果单词中的字母按字母顺序出现,则该单词被称为“abecedarian”。

import java.util.*;

public class Abecedarian{
    public static void main( String[] args ){
        String word=getWord();

    }

    public static String getWord(){
        Scanner keyboard = new Scanner(System.in);
        String word;
        System.out.print("Enter a word: ");
        word=keyboard.nextLine();
        return word;
    }

    public static boolean isAbecedarian(String word){

【问题讨论】:

    标签: java string loops compareto


    【解决方案1】:

    您可以遍历单词中的字符并确保它们按字母升序排列:

    public static boolean isAbecedarian (String word) {
        int length = word.size();
        if (length <= 1) {
            return true;
        }
    
        word = word.toLowerCase(); // just in case
    
        char prev; 
        char curr;
    
        for (int i = 1; i < length; ++i) {
            prev = word.charAt(i - 1);
            curr = word.charAt(0);
            if (prev > curr) {
                return false;
            }
        }
    
        return true;
    }
    

    【讨论】:

      【解决方案2】:

      尝试使用:

      if (word.compareTo("abecedarian") == 0) {
         //yes it is equal
      }
      

      使用equals String 方法检查相等性有更好的方法,例如:

      if ("abecedarian".equals(word)) {
          ...
      }
      

      【讨论】:

      • 哇,我实际上是在谷歌上搜索 abecedarian 的定义,因为我认为提问者正在寻找单词的某些属性,而不是字面上的字符串“abecedarian”。现在有意义
      • 引用OP“如果单词中的字母按字母顺序出现,则该单词被称为“abecedarian”。”
      • 是的,对不起,我一开始是想解释什么是初学者,但我忘记了
      猜你喜欢
      • 2023-02-21
      • 2020-06-04
      • 1970-01-01
      • 2013-03-29
      • 2014-12-15
      • 1970-01-01
      • 2019-01-06
      • 2021-07-28
      • 2020-08-15
      相关资源
      最近更新 更多