문제

나는 (약간 인터넷 검색을 통해) 혼자서 대부분의 코드를 완성했지만 예상치 못한 문제에 부딪혔습니다.먼저, 선택 정렬을 사용하여 사용자가 입력한 이름 목록을 성의 가사순으로 정렬해야 합니다.내 코드는 다음과 같습니다.

    import java.util.*;
class Name_Sort
{
    public static void main (String args[])
    {
        Scanner in = new Scanner (System.in);
        System.out.print ("Enter the number of names you wish to enter: ");
        int n = in.nextInt();
        String ar[] = new String [n];
        for (int i = 0; i<ar.length; i++)
        {
            System.out.print("Please enter the name: ");
            ar[i]= in.nextLine();
        }
        String temp;
        for (int b = 0; b<n; b++)
        {
            for (int j=b+1; j<n; j++)
            {
                if ((compareLastNames(ar[b], ar[j]))>0)
                {
                    temp = ar[b];
                    ar[b] = ar[j];
                    ar[j] = temp;
                }
            }
        }
        System.out.println ("The names sorted in alphabetical order are: ");
        for (int a = 0; a<n; a++)
            System.out.print (ar[a]+"\t");
    }

    private static int compareLastNames(String a, String b) 
    {
        int index_a = a.lastIndexOf(" ");
        String surname_a = a.substring(index_a);
        int index_b = b.lastIndexOf(" ");
        String surname_b = b.substring(index_b);
        int lastNameCmp = surname_a.compareToIgnoreCase(surname_b);
        return lastNameCmp;
    }
}

문제는 사용자로부터 이름을 가져올 때 특히 다음 부분에서 발생하는 것 같습니다.

Scanner in = new Scanner (System.in);
    System.out.print ("Enter the number of names you wish to enter: ");
    int n = in.nextInt();
    String ar[] = new String [n]; //Array to store the names in.
    for (int i = 0; i<ar.length; i++)
    {
        System.out.println("Please enter the name: ");
        ar[i]= in.nextLine();

    }

BlueJ 터미널 창의 출력은 다음과 같습니다.

Name_Sort.main({ });
Enter the number of names you wish to enter: 5
Please enter the name: 
Please enter the name: 

그것은 표시되어야 하는 것이 아닙니다.내가 뭘 잘못하고 있는 걸까요?한동안 곰곰이 생각해 보았으나 딱히 떠오르는 것이 없습니다.

그리고 위의 오류에도 불구하고 계속해서 몇 가지 이름을 입력하더라도 여기 코드의 이 부분에서 또 다른 오류가 발생합니다.

private static int compareLastNames(String a, String b) 
{
    int index_a = a.lastIndexOf(" ");
    String surname_a = a.substring(index_a);// This is the line the compiler highlights.
    int index_b = b.lastIndexOf(" ");
    String surname_b = b.substring(index_b);
    int lastNameCmp = surname_a.compareToIgnoreCase(surname_b);
    return lastNameCmp;
}

오류는 다음과 같습니다

java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (injava.lang.String)

이것은 공백 문자가 " " 현재 없나요?그런데 왜?

다음은 터미널 창의 스크린샷입니다.http://imgur.com/l7yf7Xn

문제는 이름을 먼저 사용하여 배열을 초기화하고 사용자로부터 입력을 받지 않으면 코드가 제대로 실행되고 원하는 결과를 생성한다는 것입니다.도움 좀 주세요?

또한 여기에 있는 일부 사람들이 이것에 대해 매우 까다롭다는 것을 알고 있기 때문에 예, 이것은 숙제입니다. 예, 모든 코드를 혼자서 수행했습니다. 이름을 알파벳 순서로 정렬하는 방법을 검색할 수 없었기 때문에 구글링했습니다. 내가 가지고 있던 원래 아이디어를 정확하게 코드화해 보세요.두 성의 각 문자에 대한 ASCII 값을 비교하여 어느 것이 먼저 와야 하는지 확인했습니다.좋다: if((int) surname1.charAt(0)>(int) surname2.charAt(0)) 그러면 surname2가 surname1 앞에 와야 합니다. 그렇지 않고 둘 다 동일한 첫 번째 문자가 있으면 두 번째 문자를 가져오는 식으로 진행됩니다.

시간을 내어 읽어주셔서 감사합니다.

도움이 되었습니까?

해결책

문제는 in.nextInt() 명령은 int 값만 읽습니다.따라서 in.nextLine()을 사용하여 계속 읽으면 다음을 받게 됩니다. "\n" 키를 입력하세요.따라서 이 문제를 해결하려면 추가 항목을 추가해야 합니다. in.nextLine() 루프에 들어가기 전에.아니면 다른 것을 사용하세요 scanner.

    int n = in.nextInt();
    String ar[] = new String [n]; //Array to store the names in.

    in.nextLine(); // < --- an extra next Line

    for (int i = 0; i<ar.length; i++)
    {
        System.out.println("Please enter the name: ");
        ar[i]= in.nextLine();

    }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top