数组(搜索最高价值)

时间:2015-03-23 04:52:35

标签: java arrays

我遇到了最后一个“for”循环的问题。由于“for”循环,代码无法运行。我试图找到最高价格项目,然后我试图将该价格输出给用户。在此之前,用户必须输出价格。 “if”声明中两个价格中的“i”似乎效果不佳。

双倍最高=价格[0];

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

以下完整代码 {         //数组

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

        }
    for (int i = 0; i < foods.length; i ++)
        {
        System.out.println("What is the price on " + foods[i]);

        prices[i] = keyboard.nextDouble();
        }

    double highest = prices [0];

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

}

}

3 个答案:

答案 0 :(得分:2)

您的问题是您在for语句后面有;

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

实现目标:

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

答案 1 :(得分:0)

中删除分号
for(int i = 0; i < prices.length; i ++);

您所写的内容具有以下效果:

    for(int i = 0; i < prices.length; i ++){
        //do nothing
    }

答案 2 :(得分:0)

你的for循环有问题。你做了一件事

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

for循环应该在这里继续(price.length-1)。 它肯定会帮助你在两个for循环中。因为循环从数组中的0开始。