数组搜索和输出

时间:2015-03-23 13:01:30

标签: java arrays

我无法从此代码中纠正两个问题。

  1. 搜索主菜:我不确定为什么它不允许用户输入通过控制台输入。我也不确定该部分的for循环是否正确。 (用户可能会搜索主菜,并且打算打印出食物的当天。

  2. 最高价格:这部分代码唯一不对的是代码总是打印出最后输入的食物而不管最高价格。

  3. 代码:

    String[] daysOfTheWeek = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
    String[] foods = new String [5];
    double[] prices = new double [5];
    
    //What is being served?
    
    Scanner keyboard = new Scanner(System.in);
    
    for (int i = 0; i < daysOfTheWeek.length; i++) {
        System.out.println("What entree is being served on " + daysOfTheWeek[i]);
        foods[i] = keyboard.nextLine();
        //Price of items     
    }
    
    for (int i = 0; i < foods.length; i++) {
        System.out.println("What is the price on " + foods[i]);
        prices[i] = keyboard.nextDouble();
    }
    
    //Search for Entree
    String answer;
    
    System.out.println("What food would you like to search for?");
    answer = keyboard.nextLine();
    
    for (int i = 0; i < foods.length; i++) {
        if (answer == foods[i])
            System.out.println("This food item will be served on + daysOfTheWeek[i] ");
    }
    
    //Highest Price
    
    double highest = prices [0];
    int position = 0;
    
    for (int i = 0; i < prices.length; i++) {
        if (prices[i] > highest)
            highest = prices[i];
        position = i;
    }
    System.out.println("The highest price item was " + foods[position]);
    

3 个答案:

答案 0 :(得分:3)

关于你的第一个问题:在互联网上搜索如何比较Java中的字符串(提示:使用==不是你想要做的)。

关于你的第二个问题:

if(prices[i] > highest)
  highest = prices[i];
  position = i;

尝试添加大括号; - )

if(prices[i] > highest) {
  highest = prices[i];
  position = i;
}

答案 1 :(得分:2)

你忘了使用大括号:

if(prices[i] > highest){
    highest = prices[i];
    position = i;
}

另外,比较字符串和==通过引用比较它们:当且仅当它是同一个对象而不是相同的值时,这将返回True。 使用string1.equals(string2)。

答案 2 :(得分:2)

我之前只采用了代码的相关部分。

在这里你错误地比较了字符串,你应该使用String.equals(otherString)。你也没有收集theOfTheWeek [i},它被包含在一个字符串文字中。

for(int i = 0; i < foods.length; i++)
{
    if (answer.equalsIgnoreCase(foods[i])) {
        System.out.println("This food item will be served on " + daysOfTheWeek[i]);
    }
}

这里我初始化了双倍最高值作为整数可以包含的绝对最低值。你也忘了用括号括起来。如果省略大括号,那么只有if语句/ for循环/下面的第一行被视为语句的主体 - 将其包装在大括号中允许您输入多行。

double highest = Integer.MIN_VALUE;
int position = 0;

for(int i = 0; i < prices.length; i ++)
{
        if(prices[i] > highest) {
            highest = prices[i];
            position = i;
        }

}