dimanche 2 septembre 2018

Favorite food java program gone wrong

Here is my java program. Right now, the only way to kill the loop is to have the last column 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

                /*
                 * Your longest part of your array should be the longest
                 * if it's not, using the length  of the column to end a loop may cause problems
                 * if you use the row instead, everything after the row three will execute  
                 * 
                 */


        };

        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++) {
                test:
                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");
                }
            }
        }

    }
}

Is there any way to print out "you have no food" without using the last column being the longest? Thanks!

Aucun commentaire:

Enregistrer un commentaire