防止for循环中的语句打印每次迭代?

时间:2017-11-02 01:36:48

标签: java

我有一个程序,它接受输入的任何字符串并向后打印。但是,我想要打印的语句在每次迭代后打印,因为它在for循环中。但是,当我将它移到for循环之外时,它无法识别变量“letter”。我该如何解决这个问题?

import java.util.Scanner;

public class ReadBackwards {

   public static void main(String[] args) {

   Scanner keyboard = new Scanner(System.in);

   String word;
   char letter;
   int counter, wordLength;

   System.out.print("Please type a word: ");
   word = keyboard.next();

   wordLength = word.length();

   for(counter = wordLength-1; counter >= 0; counter--) {

   letter = word.charAt(counter);

   System.out.print(word + " backwards is " + letter);

   }

   }
}

2 个答案:

答案 0 :(得分:0)

一种选择是使用System.out.print()代替println(),只需在一行中打印单个字符:

System.out.println(word + " backwards is: ");
for (counter = wordLength-1; counter >= 0; counter--) {
    letter = word.charAt(counter);
    System.out.print(letter);
}

Demo

答案 1 :(得分:0)

将每个字母附加到类似StringBuilder的字母然后打印出来。您还应该尝试限制变量的范围(我不确定我在大多数变量中都看到了值)。你可以做到

String word = keyboard.next();
StringBuilder sb = new StringBuilder();
for (int counter = word.length() - 1; counter >= 0; counter--) {
    sb.append(word.charAt(counter));
}
System.out.println(word + " backwards is " + sb.toString());

而且,这可能会进一步简化为

String word = keyboard.next();
System.out.println(word + " backwards is " 
        + new StringBuilder(word).reverse().toString());