0

My goal is to ask the user to enter a bunch of strings in a loop, and when they enter "stop", the loop breaks and prints all those strings with a comma at the end of each word. For example, if the user enters "first", "second", "third", and "fourth", then the program would print the following:

first, second, third, fourth

public static void main(String[] args) 
{
    Scanner kb = new Scanner(System.in);
    int i;
    String s;
    String[] listOfStrings = new String[1000];
    String last = "";
    System.out.println("Please enter some Strings: ");
    for (i = 1; i>0; i++) {
        listOfStrings[i] = kb.next();
        last = listOfStrings[i] + ",";
        if (listOfStrings[i].equalsIgnoreCase("stop")) {

            break;
        }
    }
        System.out.print(last);

There is a problem because it always just winds up printing the last word and nothing else. Any help would be greatly appreciated.

1
  • According to your code you are printing the last one. You will need to print each String in listOfStrings. Commented Feb 20, 2016 at 3:17

1 Answer 1

2

I would use an ArrayList:

Scanner sc = new Scanner(System.in);
List<String> list = new ArrayList<String>();

while (sc.hasNext()) {
    String s = sc.next();
    if (s.equalsIgnoreCase("stop")) {
        break;
    } else {
        list.add(s);
    }
}

for (int i = 0; i < list.size(); i++) {
    System.out.println(list.get(i) + ",");
}

If you want everything in one line, you can do this:

Scanner sc = new Scanner(System.in);
String line = "";

while (sc.hasNext()) {
    String s = sc.next();
    if (s.equalsIgnoreCase("stop")) {
        break;
    } else {
        line += s + ", ";
    }
}

System.out.println(line.substring(0, line.length()-2));
Sign up to request clarification or add additional context in comments.

3 Comments

I'm using NetBeans 8.1 and for some reason "List<String> list = new ArrayList<String>();" doesn't work.
You need to import them into the project, you can try autofixing in Netbeans, if I remember correctly netbeans shows red exclamation on error line, you can hover your mouse over it and then click auto resolve
You need to import it: import java.util.*;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.