反串印刷法 [英] Reverse string printing method
问题描述
我正在尝试解决以下问题,但是如何编写接受 String 作为参数的方法?
I am trying to solve the following problem but how do write the method that accepts String as an argument?
编写一个名为 printReverse
的方法,它接受一个 String
作为参数并以相反的顺序打印字符.如果空string 作为参数传递,该方法不应产生任何输出.一定要写一个 main 方法来令人信服地展示你的行动计划.不要使用相反的方法StringBuilder
或 StringBuffer
类!
Write a method named
printReverse
that accepts aString
as an argument and prints the characters in the opposite order. If the empty string is passed as an argument, the method should produce no output. Be sure to write a main method that convincingly demonstrates your program in action. Do not use the reverse method of theStringBuilder
orStringBuffer
class!
到目前为止,我已经以更简单的方式解决了这个问题:
So far I have solved it in a easier manner:
import java.util.Scanner;
class ReverseString {
public static void main(String args[]) {
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);
}
}
推荐答案
我强烈建议您阅读 基础教程.
你可以简单地:
private static String myReverse(String str) {
String reverse = "";
int length = str.length();
for( int i = length - 1 ; i >= 0 ; i-- ) {
reverse = reverse + str.charAt(i);
}
return reverse;
}
在您的 main
中,您只需:
And in your main
, you simply:
String reversed = myReverse(in.nextLine());
请注意,方法是static
,因为您是从静态方式(main
方法).如果您不希望它成为静态,则必须通过对象来访问它.
Note that the method is static
because you're referring to it from a static manner (main
method). If you don't want it to be static, you'll have to access it via an object.
另请注意,始终为 for
循环使用大括号是一种很好的做法,即使它包含一行也是如此.
Also note that it's a good practice to always have curly brackets for for
loops, even if it contains a single line.
这篇关于反串印刷法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!