使用while循环确定要创建的字符数量

时间:2016-02-07 12:35:06

标签: java

我正在尝试创建一个使用while循环来反转字符串的应用程序。只是想知道我是否走在正确的道路上。 所以我想我会做一个while循环来确定我应该做多少chars。然后我会在控制台中反向打印它们。

到目前为止,这是我的代码。任何帮助将不胜感激。

    // Get the text from the input from the user
    // Outputs it to the Text area 
    // Uses while loop to calculate how many chars to create    

    String Startword = txfInput.getText();


    int LengthOfWord = Startword.length();
    int Counter      = 1;



    while (Counter <= LengthOfWord) 

    {            

        // Creates amounts of chars based off the counter





        Counter = Counter +1 ;


    }

有什么建议吗?

4 个答案:

答案 0 :(得分:0)

您需要在每次迭代后向反向String中添加一个字符,如下所示:

String Startword = txfInput.getText();
String rev="";

int LengthOfWord = Startword.length();
int Counter      = 1;

while (Counter <= LengthOfWord) 
{            
    rev=Startword.charAt(Counter-1)+rev; // Add a character to rev.
    Counter = Counter +1 ;

}

System.out.println(rev);

答案 1 :(得分:0)

使用char数组可能更容易:

char[] output = new char[Startword.length];
for(int i = 0; i < Startword.length; i++){
    output[i] = Startword.charAt(Startword.length - i - 1);
}
String rev = new String(output);

答案 2 :(得分:0)

只需使用for循环..

String reverse = "";
for (int i = word.length()-1; i>=0; i--)
{
 reverse += word.charAt(i); 
}

如果你想要一段时间......那么

while(i >= 0)
{
reverse += word.charAt(i); 
i--;
}

答案 3 :(得分:0)

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

    char[] stringArray;

    stringArray = s.toCharArray();

            int temp;
            int low=0;
            int high=stringArray.length-1;
            while(low<high){
                temp= stringArray[low];
                stringArray[low] = stringArray[high];

                System.out.print(stringArray[low]);


                low ++;
                high--;
            }

检查出来