将循环外的字符串与java中的循环外的字符串进行比较

时间:2014-03-03 03:55:42

标签: java string for-loop compare

我正在编写一个程序,从用户那里取一个单词,比如“banana”,单词“b”的第一个字母就像ananab一样把它放在最后,然后检查它是否拼写相同的单词。我已经研究了几天并尝试了几个但仍然不确定如何检查用户给出的字符串和一个for循环内的字符串。到目前为止,这是我的计划。

public static void main(String[] args) {

    System.out.println("Enter words that can be checked for backward spelling");
    System.out.println("Please enter a word to check");
    Scanner keyboard = new Scanner(System.in);

    String words = keyboard.nextLine();
    String firstLetter = String.valueOf(words.charAt(0));
    String words2 = words.substring(1);
    String otherwords = words2+firstLetter;


    for (int i=otherwords.length()-1; i>=0; i--){
        String newwords=String.valueOf(otherwords.charAt(i));
        boolean match = newwords.equalsIgnoreCase(words);
        if (match){
            System.out.println("This word matches the criteria we are lookin for");}
        }
}
}

3 个答案:

答案 0 :(得分:0)

public static void main(String []args){

String input = new Scanner(System.in).nextLine();

char addToEnd = input.charAt(0);
String newString = input.substring(1);
newString+=addToEnd;

if(input.equals(newString)){
System.out.println("This is a match");

}

答案 1 :(得分:0)

试试这个:

public static void main(String[] args) {

    System.out.println("Enter words that can be checked for backward spelling");
    System.out.println("Please enter a word to check");
    Scanner sc = new Scanner(System.in);
    String word = sc.nextLine();
    StringBuilder sb = new StringBuilder();
    sb.append(word.substring(1));
    sb.append(word.charAt(0));
    System.out.println(sb.toString().equals(word)?"This is a match.":"This is not a match.");
}

答案 2 :(得分:0)

System.out.println("Enter words that can be checked for backward spelling");
System.out.println("Please enter a word to check");
Scanner keyboard = new Scanner(System.in);
String word = keyboard.nextLine();
keyboard.close();
String firstLetter = word.substring(0, 1);
String newWord = word.substring(1) + firstLetter;
// reverse the word
String reversedWord = "";
for (int i = 0; i < word.length(); i++) {
    reversedWord = word.substring(i, i + 1) + reversedWord;
}
// check if it matches
if (reversedWord.equalsIgnoreCase(newWord)) {
    System.out.println("This word matches the criteria we are looking for!!!");
}