java 无法将字符串添加到自身

vxqlmq5t  于 2022-12-02  发布在  Java
关注(0)|答案(2)|浏览(148)

我是java的新手,我试图给自己添加一个字符串(也包括其他字符串),它运行了,但什么也不做,就像它只是输出“test”一样,这是它在其他一切似乎都工作之前的样子

package chucknorris;

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Input string:");
        String input = scanner.nextLine();
        int length = input.length();
        String output = "test";
        

        for (int current = 0;current <= length;current++) {
            String letter = input.substring(current, current);
            output = output + letter + " ";

            if (current == length) {
                System.out.println(output);
            }
        }

        
        
    }
}
wxclj1h5

wxclj1h51#

尝试此解决方案,但如果要多次编辑字符串,则应使用StringBuilder

import java.util.Scanner;

 public class Main {

 public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Input string:");
    String input = scanner.nextLine();
    int length = input.length();
    String output = "test";

    for (int current = 0;current <= length;current++) {

        if (current >= length) {
            break;
        }
        String letter = input.substring(current, current + 1);
        output = output + letter;

    }

    System.out.println(output);

}

}
h79rfbju

h79rfbju2#

请使用concat进行字符串连接。

public static void main(String[] args) {
  Scanner scanner = new Scanner(System.in);
  System.out.println("Input string:");
  String input = scanner.nextLine();
  int length = input.length();
  String output = "test";
        
  output = output.concat(output).concat(input).concat("");

  System.out.println(output);     
}

相关问题