【发布时间】:2015-06-04 12:13:27
【问题描述】:
我希望用户输入一个字符串,然后以选定的间隔在字符之间添加一个空格。
示例:用户输入:你好 然后每 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不是一个好主意,因为前缀get是为getter 和setter 方法保留的约定。见stackoverflow.com/questions/1568091/why-use-getters-and-setters 一般情况下,变量名不使用动词... -
你的例子或者你的描述是错误的,因为你在
hello的o之后添加了一个空格... -
好吧,如果没有下划线而只有空格,这就是我正在做的事情,如果 o 后面有空格也没关系。这只是一个例子,不在乎我的变量名是什么。 @Robert ty 虽然:)
标签: java string java.util.scanner whitespace