【问题标题】:java to set a recycle of letters in a certain rangejava设置一定范围内的字母循环
【发布时间】:2020-03-12 13:58:18
【问题描述】:
public static void main(String[] args) {
    String name = "Netbeans 8.2";
    String output = "";
    char charData[] = {};

    for (int i = name.length(); i > 0; i--) {
        output = name.charAt(i-1) + output; 
        System.out.println(output);
    }

    for (int i = name.length(); i < 40; i++) {
           output = " " + output;
           System.out.println(output);
    }      

    charData = output.toCharArray(); 
    char last = charData[39]; // von char [39]
    int j=0;
    for (int i = 38; i >= 0; i--) {    //somewhere here must be redone to fix the problem, I know where I get wrong.
        charData[i + 1] = charData[i];  
        for (charData[j] = 0; j < 15; j--) {        
            charData[0] = last; 
            output = new String(charData);
        }
        System.out.println(output);
    }
}

/*
The expected outcome should be like:

2
.2
8.2
 8.2
s 8.2
ns 8.2
ans 8.2
beans 8.2
tbeans 8.2
etbeans 8.2
Netbeans 8.2
 Netbeans 8.2
  ......
   (till length 40)
                            Netbeans 8.2
2                            Netbeans 8.
.2                            Netbeans 8
8.2                             Netbeans 
       .....
etbeans 8.2                            N

*/

最后一个字符一旦移动到右侧并达到数组范围的限制将再次出现在左侧的开头,这意味着我应该使用 for 让其余被吃掉的字符继续出现从每次回收的开始。这是我已经花费了一整天并且无法正确执行的问题。我不熟悉通过'for'方法获取字符串值。

有人有想法吗?万分感激! 感谢您的支持!享受编码!

【问题讨论】:

  • 欢迎来到 SO!请阅读minimal reproducible example 并相应地编辑您的帖子。您的代码似乎执行完美,但有问题缺少预期输出和实际输出以及问题的详细说明

标签: java arrays string char


【解决方案1】:

这可能是进行“环回”打印的方法之一。你还没有完全解释你为什么要这样做,所以这就是我可以帮助你的。我建议阅读代码内的 cmets,因为它们可能会帮助您理解一些事情。

public static void main(String[] args) {
    // String name = "Netbeans 8.2";
    String output = "Netbeans 8.2";
    char[] charData;

    // this is unnecessary: you're just copying name into output
    // for (int i = name.length(); i > 0; i--) 
    //    output = name.charAt(i - 1) + output; 

    // adding a whitespace character to the beginning of output
    for (int i = output.length(); i < 40; i++) 
        output = " " + output;

    charData = output.toCharArray();

    // how many times do you want it printed? in my case: 100 times
    for (int i = 0; i < 100; i++) { 
        char last = charData[charData.length - 1]; // save the rightmost character

        // move every character one place to the right, losing the rightmost
        for (int j = charData.length - 1; j > 0; j--) 
            charData[j] = charData[j - 1];

        charData[0] = last; // change first character to what we've saved
        // output= new String(charData); also unnecessary - println can print char arrays as well 
        System.out.println(charData);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-15
    • 2013-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-14
    • 2017-02-03
    • 1970-01-01
    相关资源
    最近更新 更多