2013-03-06 28 views
1
import java.util.*; 
public class S1 { 
    public static void main(String[] args) { 
     String twoDm[][]= new String[3][3]; 
     int i,j; 

     int[] c=new int[2]; 
     //int []d =new int[1]; 

     Scanner sc=new Scanner(System.in); 
     for(i=0;i<3;i++){ 
      for(j=0;j<3;j++){ 
       twoDm[i][j]=sc.next(); 
      String x= twoDm[i][j]; 
       if(x=="aa"){ 
        c[0]=i;//values here are not getting into array c// 
        c[1]=j; 

       } 

     for(int f:c){ 
       System.out.println(f);  

      } 
     } 

陣列℃,同時印刷00示出了爲什麼是什麼可以是問題陣列並不在環路

+0

你想在這裏做什麼?這段代碼試圖解決什麼問題? – 2013-03-06 05:33:31

+0

我想獲得數組的索引,例如,如果我提供「e」,所以我和j是e的索引...試圖獲得該索引 – Sandepp1 2013-03-06 05:37:10

回答

9

x是String i的值和j不進入陣列獲得的值。您不能使用==來測試字符串上的相等性。

您想改爲使用x.equals("aa")。如果x爲空,則可以使用"aa".equals(x)代替(此表單不會給你一個NullPointerException)。

+2

我通常使用''aa「.equals(x)'來避免' NullPointerException' – 2013-03-06 05:38:23

+0

@BobWang:是的,這絕對是首選樣式。我將添加它。雖然,取決於他們在做什麼,但瞭解「x」爲空可能會有所幫助。 – Makoto 2013-03-06 05:38:44

1

if語句改成這樣:

if("aa".equals(x){ 
    c[0]=i;//values here are not getting into array c// 
    c[1]=j; 
} 

使用String.equals(other String)功能比較字符串,而不是==操作。

函數檢查字符串的實際內容,==運算符檢查對象的引用是否相等。

希望它有幫助..