Answered step by step
Verified Expert Solution
Question
1 Approved Answer
This is a program that needs to print out the second word of a sentence. I asked for help but i'm not quiet sure how
This is a program that needs to print out the second word of a sentence. I asked for help but i'm not quiet sure how to impliment it. Please follow what they said. (java)
Scanner in = new Scanner(System.in); System.out.println("Type in words or a sentence: "); String s = in.nextLine(); int pos = s.indexOf(" "); int pos2 = s.indexOf(" ", pos+1); if (pos2 == -1){ } else { String second = s.substring(pos+1, pos2); System.out.println(second); } The program works when you put in one word and when you put in three or more words. Although, when you put in two words, it does nothing when it's supposed to print it out. I am having a hard time fixing it. NEW I'm glad that it works with 3 or more words. When you read in your words, make your program add a space to the end of the sentence. I think that with two words it's still looking for the second space and maybe it's not finding it. This should trick it into finding itStep by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started