0

我需要帮助解决这个问题。我应该制作一个程序,我需要比较 10 只股票价格,并使用该程序找到一天中最大的涨幅。该程序只能使用 for 循环/if else 和 main 方法。我正在使用扫描仪来获取股票价格的整数。每次我运行代码时,我得到的只是我放入扫描仪的最后一个值。请帮忙。代码如下。

import java.util.Scanner;

//48  54  49  47  62  64  59  70  75  82
class Increase
{
 public static void main (String [] args)
 {
   Scanner in = new Scanner(System.in);
   final int Days = 10;
   int highval = 0;
   int lowval = 0; 
   int increase = 0; 
   int day = 0;
   System.out.print("Enter the stock prices for " + Days + " number of days.");
   int x = in.nextInt();

   for (int i = 0; i < Days-1; i++)
   {
    int y = in.nextInt();
     if (increase < (y - x));
     { 
       increase = (y - x);
       highval = y;
       lowval = x;
       day = i; 
     }
    x = y;
   }    

   System.out.println("The largest increase is " + increase);
   System.out.println("from  " +lowval + " to " + highval );
   System.out.println("between days " + day + " and " + (day + 1));
 }
}
4

1 回答 1

0

问题在于 ; 在行中 if (increase < (y - x)); (空任务)

这导致始终执行以下循环。

{
increase = (y - x);
       highval = y;
       lowval = x;
       day = i; 

}

修复更改如下。

import java.util.Scanner;


    class Increase
    {
     public static void main (String [] args)
     {
       Scanner in = new Scanner(System.in);
       final int Days = 10;
       int highval = 0;
       int lowval = 0; 
       int increase = 0; 
       int day = 0;
       System.out.print("Enter the stock prices for " + Days + " number of days.");
       int x = in.nextInt();

       for (int i = 0; i < Days-1; i++)
       {
        int y = in.nextInt();
         if (increase < (y - x))
         { 
           increase = (y - x);
           highval = y;
           lowval = x;
           day = i; 
         }
        x = y;
       }    

       System.out.println("The largest increase is " + increase);
       System.out.println("from  " +lowval + " to " + highval );
       System.out.println("between days " + day + " and " + (day + 1));
     }
    }
于 2013-11-04T04:43:54.427 回答