【问题标题】:How to place the first character of a string in the last position of the string in Java?如何将字符串的第一个字符放在Java中字符串的最后一个位置?
【发布时间】:2020-06-12 02:53:34
【问题描述】:

初级 Java 程序员。对于学校作业,我需要编写一个程序,如果它的第一个成员/字符已放置在最后一个位置(例如 2567 和 5672),则使用一个数字和相同的数字进行一些计算。我决定将数字转换为字符串,获取每个字符串的第一个字符并将其放在后面以获得我需要的第二个数字。虽然我认为这是一个非常愚蠢的问题,但我似乎无法找到一种以我需要的方式操作字符串的方法,那么我该怎么做呢?

提前致谢!

由于我发布了整个代码,因此我还将包括整个问题的内容: 计算 A 和 B 之间的差异(例如 2567 和 5672)是否大于 5000。如果是 - A 应该打印,那么对于 10 - 10000 范围内的所有数字 A 和 B 是 A ,它是第一个最后一个字符。



public class new1 {

    public static void main (String[] args){

        int bot = 10;
        int top = 10000;
        int difference = 5000;
        int a, b, c;
        a = bot;

        while (a<10000) {
            String str1 = String.valueOf(a);
            // my question comes at about this point
            String str2 = "10"; // this line is just as an example; my idea is to then convert back to int and store in b for calculation;
            b = Integer.parseInt(str2);

            c = a - b;

            if (c > difference)
                System.out.println(c);
            else
                a++;
        }
        System.out.println("End");
    }
}

【问题讨论】:

  • 你总是会得到 4 位数字吗?
  • 此外,在此处发布问题时,通常会显示您尝试过的工作。这里的大多数人会拒绝被视为一种为你编写代码的服务,并且不会提供帮助。请包括您的代码,无论是否有效。
  • @DevZer0 数字将在 10 到 10000 之间。
  • 发布您为尝试解决问题所做的工作。
  • "我似乎找不到一种按我需要的方式操作字符串的方法" - 您的需求可能可以通过使用String 的多种方法来满足(例如startsWithcharAt)。您应该查看JavaDocs for String 以了解String 公开的方法。

标签: java string methods char


【解决方案1】:
  1. 将输入作为字符串。
  2. 获取此字符串中除第一个位置之外的所有字符。
  3. 将第一个位置的字符附加到上面的字符串中

    String str = String.valueOf(2567); System.out.println(str.substring(1)+str.substring(0,1));

【讨论】:

    【解决方案2】:

    if it's first member/character has been placed in the last position (e.g. 2567 and 5672).

    我不确定我是否理解,但第一个字符是 charAt(0),最后一个字符是 charAt(str.length()-1)

    好的,我重新阅读了您的示例,我想我看到了不同的解释。您也可以使用substring() 删除字符,然后使用连接再次添加它们,这对于+ 来说是最简单的。

    while (a<10000) {
        String str1 = String.valueOf(a);
        // problem: move first char to last;
        String str2 = "10"; // example; convert to int and store in b for calculation;
    
        // this takes the first character of str1 and moves it to 
        // end of str2.
    
        // 1. Make a copy first
        char first = str1.charAt(0);
        // 2. Now remove the character and assign to str2
        str2 = str1.substring(1);
        // 3. Place the saved copy at the end
        str2 = str2 + first;
    
        b = Integer.parseInt(str2);
    
        c = a - b;
    
        if (c > difference)
            System.out.println(c);
        else
            a++;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-17
      • 1970-01-01
      • 2022-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多