Write a console program that requests that the user enter a string. Using only S
ID: 3793680 • Letter: W
Question
Write a console program that requests that the user enter a string. Using only String's length and indexOf methods, print, in ascending order, 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
Name the class and java file GimmeW.
Explanation / Answer
GimmeW.java:
import java.util.Scanner;
public class GimmeW {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
while(true){ //repet until user enters -1
System.out.println("Please enter a string");
String string=sc.nextLine();
if(string.equals("-1")){ //check if user entered -1
System.out.println("bye");
break;
}
int startSearchingFromPos=-1;
//Only the string after 'startSearchingFromPos' index will be searched
System.out.print("'w' or 't' are at locations ");
int loopCount=0;
while(true){
loopCount++;
int indexW=string.indexOf('w',startSearchingFromPos+1);
int indexT=string.indexOf('t',startSearchingFromPos+1);
if(indexW==-1 && indexT==-1){ //No more 'w' or 't' found
startSearchingFromPos=-1;
break;
}
else if(indexW==-1)
startSearchingFromPos=indexT;
else if(indexT==-1)
startSearchingFromPos=indexW;
else if(indexW<indexT)
//check which index comes first, w's index or t's index
startSearchingFromPos=indexW;
else
startSearchingFromPos=indexT;
if(loopCount>1)
System.out.print(", ");
System.out.print(startSearchingFromPos);
}
System.out.println();
}
}
}
Sample run:
Please enter a string
wake tech is wonderful
'w' or 't' are at locations 0, 5, 13
Please enter a string
Java wouldn't be the same without it
'w' or 't' are at locations 5, 12, 17, 26, 28, 32, 35
Please enter a string
-1
bye
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.