0

For some reason when I try to ask a user for names so I can add them to a list and sort them alphabetically, this code will not print anything out. It will not even get past the while loop, does anyone have any idea what the problem is? Also another question; how can you execute some code if the user presses the enter button when asked for input value, would it just be null? Thanks!

import java.util.Scanner;
import java.util.*;

public class project16u
{
    public static void main(String[] args) 
    {
        int n;
        String input = "nothing";
        String temp;
        ArrayList<String> names = new ArrayList<String>();
        Scanner s1 = new Scanner(System.in);
        System.out.println("Enter all the names:");
        while(!input.equals("done")){
            input = s1.nextLine();
            names.add(input);
        }
        for (int i = 0; i < names.size()-1; i++) 
        {

                if (names.get(i).compareTo(names.get(i+1))>0) 
                {
                    temp = names.get(i);
                    names.add(i, names.get(i+1));
                    names.add(i+1, temp);
                    i=0;
                }
        }
        System.out.print("Names in Sorted Order:");
        for (int i = 0; i < names.size() - 1; i++) 
        {
            System.out.print(names.get(i).toString() + ",");
        }
        System.out.print(names.get(names.size()-1));
    }
}
1
  • You'll need to debug your code. It surely stays within the for loop because you are resetting i=0 at some point within it, which is generally a bad practice: All loops should iterate once and just once on every value of the control variable. They might exit promptly, but not lately. Commented Mar 26, 2017 at 17:22

2 Answers 2

1

add inserts the name at the requested index. Thus, in your case, you will have two copies of the same name in the list, rather than the one you intended.

You probably want to use set instead.

Sign up to request clarification or add additional context in comments.

Comments

0

You may need to change the loop condition to

s1.hasNextLine() && !input.equals("done")

Comments

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.