使用For-循环帮助我编写一个程序,将用户输入的字符串的每三个字符打印一次。未显示的字符将被打印为下划线。程序的示例运行如下所示:
输入字符串: Constantinople
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();
}}但是我的输出是:C_s_n_n_l__需要做一些事情来调整正确的下划线,谢谢
发布于 2016-02-14 18:12:29
用这个:
for (int i = 0; i < userInput.length(); i++)
{
System.out.print(i % 3 == 0 ? userInput.charAt(i) : "_");
}发布于 2016-02-14 18:12:01
试着替换这个:
for (int i = 0; i <= userInput.length(); i+=3)通过以下方式:
for (int i = 0; i < userInput.length(); i++)
{
if(i % 3 == 0)
System.out.print(userInput.charAt(i));
else
System.out.print("_");
}https://stackoverflow.com/questions/35395271
复制相似问题