如何在java中使用while循环反转字符串?

时间:2016-02-06 23:26:08

标签: java string while-loop

我有一个任务,我需要让代码接受用户输入的单词,用大写字母表示,反向输出。到目前为止这是我的代码,但我真的不知道我是怎么做到的。

import java.util.Scanner;

public class WordSizeChecker {

    public static void main(String[] args) {
        Scanner kb = new Scanner (System.in);
        System.out.print("Please enter a word: ");
        String oword = kb.nextLine();
        String word = oword.toUpperCase();
        int length = word.length();
        int i = 0;
        while (i < length)
        {
            System.out.println(word.substring(i,length));
            length--;
        }

    }

}

输出:

  

请输入一个词:国际象棋   CHESS
  CHES
  CHE
  CH
  ç

3 个答案:

答案 0 :(得分:2)

oword = oword.toUpperCase();
for(int i = oword.length() - 1; i >= 0; i--)
{
    System.out.print(oword.charAt(i));
}
System.out.println();

或循环

<!-- Project Name Form-->
<form class="col s6">
  <div class="input-field col s6">
      <input placeholder="{{projectDoc}}" name="tname" type="text" class="validate">
      <label>Thing Name</label>
  </div>

  <button id="yoid" class="btn waves-effect waves-light tbutton" type="submit">
      <i class="material-icons right">Submit</i>
  </button>
</form>

"click .tbutton": function(e) {
  var bid = e.currentTarget.id;
  e.preventDefault();
  console.log(bid); // Logs 'yoid'
}

答案 1 :(得分:0)

public static void main(String[] args) {
    Scanner kb = new Scanner (System.in);
    System.out.print("Please enter a word: ");
    String oword = kb.nextLine();
    String word = oword.toUpperCase();
    int length = word.length();

    StringBuilder sb = new StringBuilder();
    // start from the end of the input string
    int i = length - 1;
    while (i >= 0) {
      // add the "next" character to the output
      sb.append(word.charAt(i));
      // step 1 character back
      i--;
    }
    System.out.println(sb.toString());
}

答案 2 :(得分:0)

String original, reverse = "";
  Scanner in = new Scanner(System.in);

  System.out.println("Enter a string to reverse");
  original = in.nextLine();

  int length = original.length();

  for ( int i = length - 1 ; i >= 0 ; i-- )
     reverse = reverse + original.charAt(i);

  System.out.println("Reverse of entered string is: "+reverse);