Below is my Java program. Right now, the only way for the program to run correctly is to have the last column be the longest. If the last column in the array isn't the longest, then the output isn't correct. For example, if the food array has more elements in the second column than in the third column like this:
String[][] food = {
{"Bannana", "Apple", "Pear", "Orange"}, // fruits
{"GreenBean", "Iceburg", "Spenach", "peas", "carrots", "potatoes", "beans"}, // vegetables
{"Steak", "Baccon", "Beef", "TurkeyB", "TurkeyBacon", "Chicken"} // meats
};
then if, for example, chicken is entered as input, the output is this:
Yo have no favorite food
Your favorite food is Chicken
And also, if the input, for example, is biscuit, then the output is this:
Yo have no favorite food
Yo have no favorite food
So, is there any way to only print out "Yo have no favorite food" once or correctly print out the favorite food without the last column having to be the longest?
Here is the code:
package com.begg;
import java.util.*;
public class List {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
String[][] food = {
{"Bannana", "Apple", "Pear", "Orange"}, // fruits
{"GreenBean", "Iceburg", "Spenach", "peas"}, // vegetables
{"Steak", "Baccon", "Beef", "TurkeyB", "TurkeyBacon", "Chicken"} // meats
};
for(int row = 0; row < food.length; row++) {
for (int col = 0; col < food[row].length; col ++) {
System.out.print(food[row][col] + ", ");
}
System.out.println();
}
System.out.println("Enter your favorite out of the options above:");
String k = sc.next();
loop2:
for(int row2 = 0; row2<food.length; row2++) {
for (int col2 = 0; col2< food[row2].length; col2++) {
if (k.equalsIgnoreCase(food[row2][col2])) {
System.out.println("Your favorite food is " + food[row2][col2]);
break loop2;
}
else if (!(k.equalsIgnoreCase(food[row2][col2])) & col2== 5 ) {
System.out.println("Yo have no favorite food");
}
}
}
}
}
Thanks!