OK, so here's my assignment...ask the user for a sentence, then print each word along with its position in the sentence. Then ask for another sentence... if the sentence is empty, terminate. My code works... but I don't know how to get it to loop back to asking for another sentence. Any help is greatly appreciated.

import java.util.Scanner;
import java.util.StringTokenizer;

public class StringAssign1b {
	public static void main(String[] args) {
		int pos = 0;
		String input;
		Scanner s = new Scanner(System.in);

		int count = 0;

		System.out.print("Enter a sentence: ");
		input = s.nextLine();

		StringTokenizer str = new StringTokenizer(input);

		if (!input.equals("/r/n")) {
			while (str.hasMoreTokens()) {
				count++;
				String word = str.nextToken();
				System.out.println(pos + " " + word);
				pos++;
			}

		}
	}
}

cut up the main method into several methods. One to handle input, one for processing it, one for output (maybe, not strictly needed for something this trivial but good practice).
In your main, just have an infinite loop that reads input, processes it, and produces output, with a terminating condition (for example, have it terminate when receiving a specific input).

package com.kash;

import java.util.Scanner;
import java.util.StringTokenizer;

public class TestMain {
	public static void main(String[] args) {
		int pos = 0;
		String input;
		Scanner s = new Scanner(System.in);

		int count = 0;

		while (true) {
			System.out.print("Enter a sentence: ");
			input = s.nextLine();
			System.out.println("input = \"" + input + '"');

			StringTokenizer str = new StringTokenizer(input);

			if (!input.equals("")) {
				while (str.hasMoreTokens()) {
					count++;
					String word = str.nextToken();
					System.out.println(pos + " " + word);
					pos++;
				}
			} else
				break;
		}
	}
}
commented: Thanks a lot! +0

Thanks a bunch! That works to loop my program... however, my pos int wasn't resetting... so I added pos = 0; to the beginning of the while you suggested... Thanks a lot, I really appreciate it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.