Reputation: 168
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
Upvotes: 0
Views: 9691
Reputation: 8387
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("_");
}
Upvotes: -1
Reputation: 17142
Use this:
for (int i = 0; i < userInput.length(); i++)
{
System.out.print(i % 3 == 0 ? userInput.charAt(i) : "_");
}
Upvotes: 6