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);
}
}
I don't understand why displayArray
doesn't work, System.out.println
should print my array after checking the condition but it doesn't work.
I assume it's in Java. When you compare string use
string.equals(String)
Instead of ==
It should work with :
if(choix.equals("p") || choix.equals("P"))
if(choix.equals("D") || choix.equals("d"))
When you are comparing Object
s, ==
not only compares their value, but compares the given objects as well. For example:
String a = "foo";
String b = "foo";
a == b; //false
a.equals(b); //true
since equals
compares whether the objects are similar, ==
compares whether the objects are the same. Also, if you are using quotes inside a String
, you need to escape them with \\"
, since if you use just use "
then you are closing the String
, resulting in errors. So, you should do something like this:
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);
}
}
Also, you need to structure your code, since, as it is, it is difficult to read it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.