Answer to Question #297585 in Java | JSP | JSF for Posher

Question #297585

Write a program to take a String as input then display the word in one column and its position on the String in another column.

Enter a String

Coronavirus was the Worst pandemic

Coronavirus \t 1

was \t 2

the \t 3

Worst \t 4

pandemic \t 5


1
Expert's answer
2022-02-14T12:04:50-0500


import java.util.*;


class App {


	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		System.out.println("Enter a String: ");
		String s = in.nextLine();
		int length = s.length();
		String word = "";
		int position = 0;
		for (int i = 0; i < length; i++) {
			char c = s.charAt(i);
			if (c != ' ') {
				word = word + c;
			} else {
				position++;
				System.out.println(word + "\t" + position);
				word = "";
			}
			if (i == length - 1) {
				position++;
				System.out.println(word + "\t" + position);
			}
		}


		in.close();
	}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS