这是我希望控制台输出带有“ 示例”一词的示例。
What will your word be?: example
eeeeeee
exxxxxx
exaaaaa
exammmm
examppp
exampll
example
我不知道从哪里开始。我将不胜感激。
修改
很抱歉,您不清楚并没有提供任何代码。这就是我到目前为止所拥有的。
import java.util.Scanner;
public class muster{
public static void main(String s[]){
Scanner sc=new Scanner(System.in);
System.out.println("What will your string be?");
String word=sc.next();
for(int i=0;i<word.length();i++)
System.out.println(word.substring(0,i+1));
}
}
这将读取用户输入,并从第一个字母开始打印单词,并在每行中打印一个新字母。我仍然需要的是,代码会重复单词的长度与word.length的其余部分一样。
答案 0 :(得分:2)
你离得很近。您已经有想法将子字符串从0打印到[1 ; 1 ; 1]
。然后,您只需要一个内部循环,该循环从i
开始,一直循环到i+1
并在word.length
打印出字符。另外,您需要使用i
,以便它们位于同一行:
System.out.print()
输出:
Scanner sc=new Scanner(System.in);
System.out.println("What will your string be?");
String word=sc.next();
for(int i=0;i<word.length();i++) {
System.out.print(word.substring(0,i+1));
for(int j = i+1; j < word.length(); j++) {
System.out.print(word.charAt(i));
}
System.out.println();
}