【问题标题】:How to print the sequence 3 7 13 17 23 ...upto 100 in java如何在java中打印序列3 7 13 17 23 ...最多100
【发布时间】:2014-11-15 12:21:39
【问题描述】:

它想要这样的序列:3 7 13 17 23 27 33 37 ....up to 100 但我得到以下输出:

3 13 23 33..
7 17 27 37

代码是:

class abc extends Thread
{
    public void run()
    {
        int i;
        for(i=3; i<97; i+=10)
            {
                System.out.println(i);
                try
                { sleep(100);}
                catch(Exception e){}
            }
        for(i=7; i<97; i+=10)
            {
                System.out.println(i);
                try
                { sleep(100);}
                catch(Exception e){}
            }
    }
}
    class Print3n7n13n17
    {
        public static void main(String args[])
        {
            abc p= new abc();
            abc p1= new abc();
            p.start();
            p1.start();
        }
    } 

【问题讨论】:

  • 这就是线程的全部意义所在。它们同时执行。如果你想打印一个序列,你应该使用顺序代码。
  • 序列是+4 +6 +4 +6,您正在添加+10 +10 +10。为什么你的代码不起作用并不奇怪?
  • 思考如何解决问题是绝对错误的。我认为你应该了解一下多线程是如何工作的。这个问题甚至不需要多线程

标签: java multithreading for-loop


【解决方案1】:

既然你的问题没有说你必须使用两个线程,为什么不让它变得简单呢?

    for(i=3; i<97; i+=10)
    {
        System.out.println(i);
        System.out.println(i+4);
    }

【讨论】:

    【解决方案2】:
    int start = 3
    while(start < 97)
    {
        //Print the number
        System.out.println(start);
        //The next number is greater than its previous by 4
        start = start+4;
        System.out.println(start);
        //And then it increments by 6
        start = start+6;
    }
    

    【讨论】:

      猜你喜欢
      • 2017-07-15
      • 2022-01-23
      • 1970-01-01
      • 2015-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多