Home > database >  I can't add a string to itself
I can't add a string to itself

Time:11-29

I'm new to java and trying to add a string to itself (plus other strings also) and it runs but doesn't do anything at all, as in it just outputs "test", which is what it is before everything else seems to work

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

        
        
    }
}

CodePudding user response:

use concat for the string concatenation.

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

CodePudding user response:

Try this Solution, but you should use StringBuilder if you want to edit a String for a multiple times

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

}

}
  •  Tags:  
  • java
  • Related