簡體   English   中英

為什么println不顯示我的數組

[英]Why println doesn't show my array

public static void displayArray(int tab[]){
    int i;
    String choix; // choice


    System.out.println("\n you want to see the values you entred from first position or last ?");
    System.out.println("tape "P" for first , and"D" for last);
    choix=sc1.nextLine(); // sc1 for nextLine , sc for nextInt to avoid buffering problems .

    if(choix=="p"||choix=="P") 
    {    for(i=0;i<k;i++)      //k is the maximum of the array(max index)
        System.out.println("T["+i+"]= "+tab[i]); // why this instruction doesn't work ??

    }

    if(choix=="D"||choix=="d")
    {for(i=k-1;i>=0;i--)
        System.out.println("T["+i+"]= "+tab[i]);// this one too doesn't work

    }}      


     public static void main(String[] args) {
        // TODO Auto-generated method;stub
         int tab[]=new int[4];

         System.out.println(readIntArray(tab));
         displayArray(tab);
    }    
}

我不明白為什么displayArray不起作用, System.out.println應該在檢查條件后打印我的數組,但是不起作用。

我認為它是在Java中。 比較字符串時

string.equals(String)

代替==

它應該與:

if(choix.equals("p") || choix.equals("P"))
if(choix.equals("D") || choix.equals("d"))

當比較Object==不僅比較它們的值,而且還比較給定的對象。 例如:

String a = "foo";
String b = "foo";
a == b; //false
a.equals(b); //true

因為equals比較對象是否相似,所以==比較對象是否相同。 另外,如果在String內使用引號,則需要使用\\"將引號轉義,因為如果僅使用"則將關閉String ,從而導致錯誤。 因此,您應該執行以下操作:

public static void displayArray(int tab[]){
    int i;
    String choix; // choice


    System.out.println("\n you want to see the values you entred from first position or last ?");
    System.out.println("tape \"P\" for first , and\"D\" for last);
    choix=sc1.nextLine(); // sc1 for nextLine , sc for nextInt to avoid buffering problems .

    if(choix.equals("p")||choix.equals("P")) 
    {    for(i=0;i<k;i++)      //k is the maximum of the array(max index)
        System.out.println("T["+i+"]= "+tab[i]); // why this instruction doesn't work ?? 
        //Your code did not even reach this point due to using unescape quotes inside a String and incorrect comparisons in your if

    }

    if(choix.equals("D")||choix.equals("d"))
    {for(i=k-1;i>=0;i--)
        System.out.println("T["+i+"]= "+tab[i]);// this one too doesn't work
        //The reason is the very same as above

    }}      


     public static void main(String[] args) {
        // TODO Auto-generated method;stub
         int tab[]=new int[4];

         System.out.println(readIntArray(tab));
         displayArray(tab);
    }    
}

另外,您還需要構建代碼,因為就這樣而言,很難閱讀它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM