您好我想制作一个以直角三角形显示名称的程序,但我这个程序的另一面输出是
import java.util.Scanner;
public class NameGame2 {
public static void main(String[]args)
{
Scanner x = new Scanner(System.in);
String name, name2 = "";
System.out.print("What is your name : ");
name = x.nextLine();
System.out.println();
for(int i=0; i<name.length(); i++) {
name2 = name2 + name.charAt(i);
System.out.println(name2);
} System.out.print("\n");
}
}
I want the output to be like this outputof my code is
R A
ER AS
HER ASH
SHER ASHE
ASHER ASHER
答案 0 :(得分:1)
试试这个你需要一个空格循环,而字符应该从最后一个索引开始。全部代码
Scanner x = new Scanner(System. in );
System.out.print("What is your name : ");
String name = x.nextLine();
System.out.println();
for (int i = name.length() - 1; i >= 0; i--) {
for (int k = 0; k <= i; k++)
System.out.print(" ");
for (int j = i; j <= name.length() - 1; j++) {
System.out.print(name.charAt(j));
}
System.out.println();
}
输出
R
ER
HER
SHER
ASHER
答案 1 :(得分:1)
Java-8解决方案:
import java.util.Scanner;
import java.util.stream.IntStream;
public class NameGame2 {
public static void main(String[] args) {
System.out.print("What is your name : ");
String name = new Scanner(System.in).nextLine();
IntStream.rangeClosed(1, name.length())
.mapToObj(pos -> String.format("%" + name.length() + "s",
name.substring(name.length() - pos)))
.forEach(System.out::println);
}
}