【问题标题】:How can I return the element number of an array?如何返回数组的元素编号?
【发布时间】:2017-11-18 17:30:50
【问题描述】:

我已经编写了下面的代码,现在我需要对其进行编辑,以便它显示超过 3000 的结帐号码。即它必须显示:

以下结帐已花费超过 3000.00 英镑: 结帐编号“元素编号” 结帐编号“元素编号”等

我一直在尝试几种不同的方法,但还没有成功。谢谢你的帮助 !

import java.util.Scanner;
public class Checkouts
{
   static final int NUMBER_OF_CHECKOUTS = 6, MAX_TAKING = 1000000;

   public static void main(String[] args)
   {
      Scanner scan = new Scanner(System.in);
      double[] checkoutList = new double[NUMBER_OF_CHECKOUTS];

  System.out.println();
  for (int index = 0; index < checkoutList.length; index++)
  {
     System.out.print("\tEnter takings for checkout number ");
     System.out.print((index + 1) + ": ");
     checkoutList[index] = scan.nextDouble();
     while (checkoutList[index] < 0 || checkoutList[index] > MAX_TAKING)
     {
        System.out.print("\tImpossible! - enter takings for checkout number ");
        System.out.print((index + 1) + " again: ");
        checkoutList[index] = scan.nextDouble();
     } 
  }
  System.out.println();
  double totalTakings = 0;
  for (int index = 0; index < checkoutList.length; index++)
  {
     totalTakings += checkoutList[index];
  }

  System.out.println("The total takings for the supermarket is " + totalTakings );

} }

【问题讨论】:

  • 你能解释一下你的代码是做什么的吗?你采取了什么方法?
  • 您已经知道如何编写 for 循环,我猜您也知道 if 语句。所以你应该能够结合两者来实现你想要的。循环检查结帐,如果其中一个大于 3000,然后打印其索引。

标签: java arrays elements


【解决方案1】:

由于您已经有一个遍历每个索引的 for 循环,我们可以在那里进行检查:

  System.out.println("The following checkouts have taken more than 3000.00 pounds:");
  for (int index = 0; index < checkoutList.length; index++)
  {
     totalTakings += checkoutList[index];

     if(checkoutList[index] > 3000.00){
         //now we can be sure the current index is the location of
         //a checkout that was > 3000.00 pounds
         System.out.println("Checkout Number: " + index);
     }
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 2022-12-22
    • 1970-01-01
    • 2011-08-07
    • 2021-12-11
    • 1970-01-01
    相关资源
    最近更新 更多