Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/348.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java LastDigitDistribution_Java - Fatal编程技术网

Java LastDigitDistribution

Java LastDigitDistribution,java,Java,我的Java教科书中有一个问题让我非常困惑。在这个问题中,我应该将一个Sequence类实现为SquaredSequence类和其他各种共享next()方法的类。next()方法应该返回一个int,然后由LastDigitDistribution类处理。书中给出了程序运行后应该返回的值,但是我无法理解这些值是如何产生的。我想知道有没有人能给我解释一下 public class LastDigitDistribution { private int[] counters; /**

我的Java教科书中有一个问题让我非常困惑。在这个问题中,我应该将一个Sequence类实现为SquaredSequence类和其他各种共享next()方法的类。next()方法应该返回一个int,然后由LastDigitDistribution类处理。书中给出了程序运行后应该返回的值,但是我无法理解这些值是如何产生的。我想知道有没有人能给我解释一下

public class LastDigitDistribution
{
   private int[] counters;

   /**
      Constructs a distribution whose counters are set to zero.
   */
   public LastDigitDistribution()
   {
      counters = new int[10];
   }

   /**
      Processes values from this sequence.
      @param seq the sequence from which to obtain the values
      @param valuesToProcess the number of values to process
   */
   public void process(Sequence seq, int valuesToProcess)
   {
      for (int i = 1; i <= valuesToProcess; i++)
      {
         int value = seq.next();
         int lastDigit = value % 10;
         counters[lastDigit]++;
      }
   }

   /**
      Displays the counter values of this distribution.
   */
   public void display()
   {
      for (int i = 0; i < counters.length; i++)
      {
         System.out.println(i + ": " + counters[i]);
      }
   }
}
这是tester类

 public class SequenceDemo
  {
    public static void main(String[] args)
  {
     LastDigitDistribution dist1 = new LastDigitDistribution();
     dist1.process(new SquareSequence(), 1000);
     dist1.display();
     System.out.println();
   }
控制台值:

0:100

1:200

2:0

3:0

4:200

5:100

6:200

7:0

8:0

9:200

我无法理解这些价值观是如何形成的

该类统计最后数字的出现次数。例如,给定从1到10的平方数序列:

  • 1:2,1和9的平方是最后一位数字1
  • 4:2,2和8的平方有最后一位4
  • 。。。等等
对于1到1000的顺序, 显然有100个平方数以0结尾,200个平方数以1结尾,依此类推

程序使用模运算符获取数字的最后一位:

int lastDigit = value % 10;

方形序列中的下一个方法如下所示

第一次迭代

int n=0 然后 n++等于n=1

返回n*n=1*1=1

值=1

lastDigit=1%10=1

计数器[1]++=计数器[1]=1

下一个方法的值将是1*1、2*2、3*3、4*4。。。等等

计数器[]的值的原因如下

方形序列始终以数字0、1、4、5、6、9结尾示例1、4、9、16、25、36、49、64、81、100、121、

因此,计数器数组中将有计数器[0]、计数器[1]、计数器[4]、计数器[5]、计数器[6]和计数器[9]元素的值

此数组中的值表示以相应数字结尾的平方数的计数(lastdigit=squarevalue%10)

这就是值的到达方式

10*10,20*20,30*30,…,990*990,1000*1000,对于每个以0结尾的正方形,我们添加计数器[0]++,因此计数器[0]=100

没有一个正方形以数字2、3、7和8结尾,因此将没有 计数器[2]、计数器[3]、计数器[7]、计数器[8]的值

int lastDigit = value % 10;