在Java中打印用户输入的字符串的每第三个字符 [英] print every third character of a user-inputted string in java

查看:86
本文介绍了在Java中打印用户输入的字符串的每第三个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用For-Loop帮助我编写一个打印用户输入的字符串的每三个字符的程序.未显示的字符改为打印为下划线.该程序的示例运行可能如下所示:

Using For-Loop help me to write a program that print every third character of a user-inputted string. The characters not displayed are instead printed as underscores. A sample run of the program may look like this:

输入字符串:君士坦丁堡

Enter a string: Constantinople

C _ s _ _ n _ _ n _ _ l _

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 _ _需要做一些事情以正确的下划线谢谢

But My output is: C _ _ s _ _ n _ _ n _ _ l _ _ need to do something to put the right qty of underscores Thank you

推荐答案

使用此:

for (int i = 0; i < userInput.length(); i++)
{
    System.out.print(i % 3 == 0 ? userInput.charAt(i) : "_");
}

这篇关于在Java中打印用户输入的字符串的每第三个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆