【问题标题】:Using while loop to determine amount of chars to be created使用 while 循环确定要创建的字符数
【发布时间】:2016-02-07 20:51:52
【问题描述】:

我正在尝试制作一个使用 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 ;


    }

有什么建议吗?

【问题讨论】:

  • @Satya 问题指定了一个while循环。所以你不能指出任何问题,因为它有 33 个答案,我想我在第一页上没有看到任何带有 while 循环的答案。如果您看到任何使用 while 循环的答案,请分享它的链接。

标签: java


【解决方案1】:

只需使用 for 循环..

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

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

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

【讨论】:

    【解决方案2】:

    你只需要在每次迭代后向反向字符串添加一个字符,如下所示:

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

    【讨论】:

      【解决方案3】:

      使用 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);
      

      【讨论】:

        【解决方案4】:
        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--;
                    }
        

        看看这个

        【讨论】:

          猜你喜欢
          • 2016-08-14
          • 2017-12-06
          • 2012-10-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-03-29
          • 2013-12-20
          相关资源
          最近更新 更多