[英]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.