【问题标题】:Parallel arrays for finding the highest element用于查找最高元素的并行数组
【发布时间】:2020-10-24 21:48:04
【问题描述】:

我想在“prices”数组中找到最高的元素,然后打印“letters”数组中的对应元素

我需要一些关于我能做什么的建议。我曾尝试输出 letters[index] 但由于我认为的范围而出现错误。我对编码很陌生,所以现在真的很难过。

  String[] letters = {"A", "B", "C", "D", "E", "F", "G"};
  double[] prices = {1.00, 2.00, 50.00, 4.00, 5.00, 6.00, 7.00};
  double big = prices[0];      
  //for loop to find the highest value in the array
   for(int index = 0; index < prices.length; index++)  
   { 
    if(prices[index] > big)
     {
        big = prices[index];     
     }             
   }       
 System.out.println("The letter with the highest value is " + big);

【问题讨论】:

  • 不要使用并行数组,创建组合这两个值的对象,然后找到价格最高的对象。

标签: java arrays algorithm


【解决方案1】:

您需要两个变量:一个用于跟踪当前的“最高值”,另一个用于跟踪该值的索引。

double big = prices[0];
int bigIndex = 0;

然后

if (prices[index] > big) {
    big = prices[index];
    bigIndex = index;
}

最后:

System.out.println("The letter with the highest value is " + letters[bigIndex]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多