2014-03-03 31 views
0

我正在编写一个程序,从用户那里接受一个单词,如“香蕉”取出单词“b”的第一个字母,将它放在最后然后ananab检查它是否拼写相同的单词。我一直在做这个工作几天,并且尝试了几件事,但仍然不确定如何检查用户给出的字符串,其中有一个字符串在for循环中。这是我的计划到目前为止。比较循环外部的字符串和循环外部的java

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");} 
     } 
} 
} 

回答

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"); 

} 
+0

好的,谢谢你......我加入了循环,因为我需要扭转串一次,我在末尾添加字母,否则它不会是同一个词。这将是ananab而不是香蕉是否有其他方式来反转字符串没有循环,我以前试过字符串缓冲区我可能不得不再次使用它? –

+0

有没有必要扭转回来的字符串。我们从未失去它。如果用户输入“香蕉”,则字符串输入将是“香蕉”,并且字符串newString将是“ananab”。 if语句后,我们仍然有字符串输入... – Solace

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."); 
} 
+0

好的完美,谢谢你们! –

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!!!"); 
} 
+0

德罗巴,谢谢你,这是非常好的,我将阅读通过线路和练习用别的东西,所以我明白了! –

+0

不要忘记标记为答案,谢谢。 – Drogba