Question
Write a program in JAVA that (1) Reads in a line of text (2)Then outputs the line so that the first word and the second
Write a program in JAVA that (1) Reads in a line of text (2)Then outputs the line so that
- the first word and the second word are swapped and No space at the beginning of the line
Assumptions about the line of text: (1) There may be some spaces before the first word, (2) The line contains no punctuation, words are separated from each other by one or more spaces,
(3)Remark: using methods of string, see textbook, or the API online
The sentence can be viewed as...
spaces followed by firstWord followed by secondWord followed by otherWords
(1) use trim method to remove spaces before the firstWord (2)use indexOf to find the first space position in the line (3)use substring to get first word and the rest of the line
(4)use substring to find the second word, which is the first word of the rest of the line (5)form a new string use concatenation (6)length: find the length of the string
(7)charAt: find a character at a specified position (8)substring: find a substring between specified positions (9)indexOf: find the position of a given character
(10)lastIndexOf: find the last position of a given character (11)trim: remove the leading and trailing space of a string (12)+ : concatinate 2 strings
see sample output below
Sample Output: please enter a line of text with no punctuation one two three Four five six seven I have changed your text: two one three Four five six seven
I have posted correct code for most of the problem all I need is for someone to help me write the code to put back together the 3 sections of output in format of second word, first word, rest of words thanks
import java.util.Scanner;
public class wordswap {
public static void main(String[] args) { // read input Scanner scan = new Scanner(System.in); System.out.println("please enter a line of text with no punctuation"); String input = scan.nextLine(); //use trim method to remove spaces before the firstWord input = input.trim(); //use indexOf to find the first space position in the line int index = input.indexOf(' ');
//separate first word rom the rest of the line String first = input.substring(0,index) ; String remaining = input.substring(index);
// separate the second word from the rest remaining = remaining .trim(); // (use substring to find the second word, which is the first word of the rest of the line String secondspace = second.remaining(0, remaining.indexOf(' ')); String third = remaining.substring(remaining.indexOf(' ')); System.out.println( secondWord + " " + firstWord + " " + finalstr);
}
}
Step 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