我希望用户输入一个字符串,然后在所选间隔的字符之间添加一个空格。在用户输入的字符串之间添加空格
示例:用户输入:你好 然后每2个字母要求一个空格。 输出= 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);
}
}
这就是到目前为止我的代码,这可能是解决它的完全错误的方式,如果我错了这么纠正我。在此先感谢:)
将getInput命名为getInput并不是一个好主意,因为前缀get是按照惯例为getter和setter方法保留的。请参阅http://stackoverflow.com/questions/1568091/why-use-getters-and-setters一般来说,使用动词的变量名称是不常见的...... – Robert 2015-03-31 08:33:17
,并且您的示例或描述是错误的,因为您添加了一个'你好''o'后面的空格... – Robert 2015-03-31 08:39:25
好吧,如果没有下划线和空白,这就是即时通讯做的事情,如果在o后面有一个空格,这无关紧要。这只是一个例子,不能不在意我的变量名称是什么。 @Robert TY虽然:) – BriannaXD 2015-03-31 09:05:48