【问题标题】:Favorite food Java program gone wrong最喜欢的食物 Java 程序出错了
【发布时间】:2018-09-02 20:17:10
【问题描述】:

下面是我的 Java 程序。现在,程序正确运行的唯一方法是让最后一列最长。如果数组中的最后一列不是最长的,则输出不正确。例如,如果food 数组在第二列中的元素比在第三列中的元素多,如下所示:

String[][] food = {
        {"Bannana", "Apple", "Pear", "Orange"}, // fruits
        {"GreenBean", "Iceburg", "Spenach", "peas", "carrots", "potatoes", "beans"}, // vegetables 
        {"Steak",   "Baccon", "Beef", "TurkeyB", "TurkeyBacon", "Chicken"} // meats 
};

例如,如果输入 chicken 作为输入,则输出如下:

Yo have no favorite food
Your favorite food is Chicken

另外,如果输入是biscuit,那么输出是这样的:

Yo have no favorite food
Yo have no favorite food

那么,有没有办法只打印一次"Yo have no favorite food" 或正确打印出最喜欢的食物,而最后一列不必是最长的?

代码如下:

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");
                }
            }
        }

    }
}

谢谢!

【问题讨论】:

  • 你能解释一下你的问题吗?不清楚。
  • 请阅读minimal reproducible example并相应地完善您的问题。
  • 我试图编辑问题以便更容易理解。我添加的示例基于我自己对 OP 代码的测试。

标签: java arrays for-loop if-statement user-input


【解决方案1】:

改变这部分:

else if (!(k.equalsIgnoreCase(food[row2][col2])) & col2== 5 ) {
    System.out.println("Yo have no favorite food");
}

到这里:

else if (!(k.equalsIgnoreCase(food[row2][col2])) && row2 == food.length-1 && col2 == food[row2].length-1) {
    System.out.println("Yo have no favorite food");
}

应该做我认为你正在寻找的东西。编辑后的else if 会检查数组的所有值是否都已检查(不管哪一列更长),如果没有匹配输入,那么它将执行一次System.out.println("Yo have no favorite food");

【讨论】:

  • 谢谢!!!这是我要修复的部分。我本来打算添加更多的蔬菜,但是为什么要从 food.length 中减去 1?
  • 我减去 1,因为数组的最高索引是 length-1。例如,如果数组的长度为 2,则元素索引为 0 和 1。如果不减去 1,则将得到 ArrayIndexOutOfBoundsException
  • This post 很好地解释了ArrayIndexOutOfBoundsException
【解决方案2】:

使用 Hashset 而不是两个 for 来迭代 2d array。类似的代码;

import java.util.HashSet;
import java.util.Scanner;

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();

        final HashSet<Object> setOfFood = new HashSet<>();
        //Add all food to hashset
        for (String[] subFoodList : food) {
            for (String subFood : subFoodList) {
                setOfFood.add(subFood.toLowerCase());
            }
        }

        //if set containts scanners string returns relevant response
        if (setOfFood.contains(k.toLowerCase())) {
            System.out.println("Your favorite food is " + k);
        } else {
            System.out.println("Yo have no favorite food");
        }

    }
}

【讨论】:

    猜你喜欢
    • 2021-10-19
    • 2016-03-10
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-02
    • 1970-01-01
    相关资源
    最近更新 更多