使用For-Loop帮我编写一个程序,打印用户输入字符串的每三个字符.未显示的字符将打印为下划线.该程序的示例运行可能如下所示:
输入一个字符串:君士坦丁堡
C _ _ s _ _ n _ _ n _ _ l _
mycode的:
public class Ex02ForLoop {
public static void main(String[] args) {
//name of the scanner
Scanner scanner = new Scanner(System.in);
//initialize variable
String userInput = "";
//asking to enter a string
System.out.print("Enter a string: ");
//read and store user input
userInput = scanner.next();
//using For-Loop displaying in console every third character
for (int i = 0; i <= userInput.length(); i+=3)
{
System.out.print(userInput.charAt(i) + " _ _ ");
}
scanner.close();
}}
Run Code Online (Sandbox Code Playgroud)
但我的输出是:C _ _ s _ _ n _ _ n _ _ l _ _需要做一些事情才能把正确数量的下划线谢谢
用这个:
for (int i = 0; i < userInput.length(); i++)
{
System.out.print(i % 3 == 0 ? userInput.charAt(i) : "_");
}
Run Code Online (Sandbox Code Playgroud)