2014-08-28 19 views
-1

我是新來的Java和正在解決一些問題。我被困在一個問題上,讓我「編寫一個程序來輸入十個單詞,然後按字母順序顯示第一個和最後一個單詞」。這個問題不明確。這可能意味着將所有輸入單詞按字母順序排列,並顯示其中的第一個和最後一個(較難)或按字母順序顯示第一個和最後一個輸入單詞(更簡單)。我寫了下面的代碼:使用compareTo();方法似乎並沒有工作

import java.util.Scanner; 

public class Alphabetical { 

public static void main(String[] args) { 

    String[] s = new String[10]; 
    for (int i = 0; i < 10; i++) { 
     System.out.println("Enter word"); 
     Scanner ins = new Scanner(System.in); 

     s[i] = ins.nextLine().toLowerCase(); 
    } 

    int result = s[0].compareTo(s[10]); 

    if (result < 0) { 
     System.out.println(s[0]); 
     System.out.println(s[10]); 
    } 
    else if(result>0){ 
     System.out.println(s[10]); 
     System.out.println(s[0]); 
    } 
    else{ 
     System.out.println("Words are identical so cannot be placed in alphabetical order"); 
     } 
    } 

} 

但我發現了一個出界異常,其中compareTo方法被放置,我不知道爲什麼。如果有人能幫上忙,那會很棒。如果任何人都可以幫助更難的問題,那會更好。

+0

您可能應該在發佈此問題之前在線搜索了例外情況。 – DonyorM 2014-08-28 07:58:19

回答

2

new String[10]創建10個元素的數組。

s[10]是數組的第11個元素,因爲元素從0開始。因此,您必須將s[9]作爲最後一個元素。 compareTo不是你的問題

1

因爲你的「s」數組有10個元素。你改變你的代碼

import java.util.Scanner;

公共類的字母順序{

公共靜態無效的主要(字串[] args){

String[] s = new String[10]; 
for (int i = 0; i < 10; i++) { 
    System.out.println("Enter word"); 
    Scanner ins = new Scanner(System.in); 

    s[i] = ins.nextLine().toLowerCase(); 
} 

int result = s[0].compareTo(s[9]); 

if (result < 0) { 
    System.out.println(s[0]); 
    System.out.println(s[9]); 
} 
else if(result>0){ 
    System.out.println(s[9]); 
    System.out.println(s[0]); 
} 
else{ 
    System.out.println("Words are identical so cannot be placed in alphabetical order"); 
    } 
} 

}

0

你得到有關陣列錯誤的原因是因爲數組開始索引爲0並且比數組的大小小1。因此,對於大小爲10的數組,最高索引是9.您是否在發佈此問題之前嘗試在網上搜索異常?

問題意味着什麼,你必須向誰給你的任務/問題的人澄清。

相關問題