简体   繁体   中英

print every third character of a user-inputted string in java

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 _

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();
}}

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

Use this:

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

Try to replace this:

 for (int i = 0; i <= userInput.length(); i+=3)

With:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM