mardi 31 mars 2015

Adding a space inbetween a user inputed string

I want a user to enter a String and then add a space in between a character at a chosen interval.


example: user enters: hello then asks for a space every 2 letters. output = he_ll_o_



import java.util.Scanner;

public class stackOverflow {


public static void main(String[] args) {


System.out.println("enter a string");
Scanner input = new Scanner(System.in);
String getInput = input.nextLine();

System.out.println("how many spaces would you like?");
Scanner space = new Scanner(System.in);
int getSpace = space.nextInt();


String toInput2 = new String();

for(int i = 0; getInput.length() > i; i++){

if(getSpace == 0) {
toInput2 = toInput2 + getInput.charAt(i);
}
else if(i % getSpace == 0) {
toInput2 = toInput2 + getInput.charAt(i) + "_"; //this line im having trouble with.
}

}


System.out.println(toInput2);

}



}


Thats my code so far, it might be the completely wrong way of solving it, so correct me if im wrong. thanks in advance :)


Aucun commentaire:

Enregistrer un commentaire