Cant figure out whats wrong with this very simple code? public class worker { pu
ID: 3801533 • Letter: C
Question
Cant figure out whats wrong with this very simple code?
public class worker {
public static void main(String[] args){
//read in the file into string array of words
String[] commands = {"a","b","c"};
for(int i = 0; i<= commands.length; i++){
if (commands[i] == "a") {
System.out.print(commands[i]);
}
else if (commands[i] == "b") {
System.out.print(commands[i]);
}
else if (commands[i] == "c") {
System.out.print(commands[i]);
}
else{
System.out.print("none of these was found!");
}
}
}
}
Explanation / Answer
public class Worker {
public static void main(String[] args){
//read in the file into string array of words
String[] commands = {"a","b","c"};
for(int i = 0; i< commands.length; i++){ // Here was mistake //
if (commands[i] == "a") {
System.out.print(commands[i]);
}
else if (commands[i] == "b") {
System.out.print(commands[i]);
}
else if (commands[i] == "c") {
System.out.print(commands[i]);
}
else{
System.out.print("none of these was found!");
}
}
}
}
Explanation :
length of command array is 3 but you was running loop 4 times from 0 to 3 (for i=0; i<=3 ;)(means 4 times i=0,1,2,3) but it should run 3 times from 0 to 2 (i=0,1,2)
So I corrected for loop (i=0; i< 3;i++)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.