我无法让我的程序减去用户在下一行输入的字符,直到它达到零。例如,用户输入5表示长度和字符Y,程序应该在第一行打印五个“Y”,然后在第二行打印四个“Y”直到零。像这样...
LN(YYYYY)
LN(YYYY)
LN(YYY)
LN(YY)
LN(Y)
我不能让程序超过我得到的第一行:
LN(YYYYY
LN(Y)
LN(Y)
LN(Y)
LN(Y)
我有什么:
int length;
char d; // tried using only char 'd' but scanner has a hard time with chars, so I used String
String UserChar;
//scanner is needed
Scanner sc = new Scanner(System.in);
//get user data and initialize variables
System.out.println("Please input a positive whole number.");
length = sc.nextInt();
sc.nextLine();
System.out.println("Please input one character.");
UserChar = sc.next();
sc.nextLine();
sc.close();
//do computation
for(int a = length; a > 1 ; a = a - 1) //prints user input on first line
{
System.out.print(UserChar);
}
for(int i = 0; i < length; i = i + 1) //how many lines get printed
{
System.out.println(UserChar);
}
// print results (occurs in previous step)
}
}
答案 0 :(得分:0)
要执行此操作,您需要使用嵌套循环。第一个循环将控制我们打印的长度,然后第二个循环将根据第一个循环中使用的变量进行打印。例如:
//Gets how many chars to print going from n..1
for(int a = length; a >= 1 ; a = a - 1)
{
for(int i = 0; i < a; i = i + 1) //prints char a times
{
System.out.print(UserChar);
}
System.out.println();
}