Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Java code:: Write a console program that requests that the user enter a string.

ID: 3870514 • Letter: J

Question

Java code::

Write a console program that requests that the user enter a string. Using only String's length and charAtmethods, print the locations of each 'w', and 't'. When an input has been fully processed, request the user to enter another string. When the user enters -1, terminate the program. Use a Scanner and nextLine to read the user input.

For example, assume the user enters


wake tech is wonderful


the program prints


'w' or 't' are at locations 0, 5, 13

the user enters

Java wouldn't be the same without it

the program prints

'w' or 't' are at locations 5, 12, 17, 26, 28, 32, 35

the user enters

-1

the program prints

bye

Explanation / Answer

CharLocations.java

import java.util.Scanner;

public class CharLocations {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

System.out.println("Enter the string (-1 to quit): ");

String s = scan.nextLine();

String locations = "";

while (!s.equals("-1")) {

locations = "";

for (int i = 0; i < s.length(); i++) {

char ch = s.charAt(i);

if (ch == 'w' || ch == 't') {

locations += i + ",";

}

}

if (locations.length() > 0) {

System.out.println("'w' or 't' are at locations "

+ locations.substring(0, locations.length() - 1));

} else {

System.out.println("'w' or 't' are not found");

}

System.out.println("Enter the string (-1 to quit): ");

s = scan.nextLine();

}

}

}

Output:

Enter the string (-1 to quit):
wake tech is wonderful
'w' or 't' are at locations 0,5,13
Enter the string (-1 to quit):
Java wouldn't be the same without it
'w' or 't' are at locations 5,12,17,26,28,32,35
Enter the string (-1 to quit):
-1

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote