【问题标题】:Java questions using only for-loops [closed]仅使用 for 循环的 Java 问题 [关闭]
【发布时间】:2015-08-29 03:41:20
【问题描述】:

我是 Java 编程的新手,所以我希望你们中的任何人都可以帮助我。

这个问题让你用一个循环练习。

(a) 编写一个程序 OddSequencer.java,使用 for 循环打印以下系列 1 2 4 7 11 16。提示:首先识别此序列中的模式。特别是这个序列中连续的两个数有什么区别?

对不起,我不是想把它扔给你们。我知道对于 (a) 部分,数字系列中有一个模式,它从 1 (1+1) -> 2 (2+2) -> 4 (4+3) -> 7 (7+4) ) -> 11 (11+5) -> 16

我现在拥有的是

public class OddSequencer {
    public static void main(String [] args){
       for(int i = 1; i <= 16; i) // i'm not sure what the last condition is supposed to be
       System.out.println(i);
    }
}

(b) 编写一个名为 SumLoops.java 的程序,其 main 方法使用 for 循环打印从 3 到 30(包括 3 和 30)的 3 的倍数之和。

我现在拥有的是

public class SumLoops {
    public static void main(String [] args){
        for(int i = 3; i <= 30; i+=3)
            System.out.println(i);   
    }
}

你的程序的输出应该是这样的:

D:\is200\lab1>java SumLoops
Sum of multiples of 3 from 3 to 30 = 165

D:\is200\lab1>

【问题讨论】:

  • "i was hoping if any of you could help me with this." 不是一个具体的可回答问题,相反,您需要提出一个实际的具体问题,而不仅仅是将您的作业交给我们做。请查看help centerhow to ask good questions 部分,了解有关如何改进您的问题并增加获得体面帮助的机会的更多信息。
  • 你有一些代码要显示吗?
  • 不要在 cmets 中发布这些内容,而是edit 并改进您的问题。多一点努力可以走很长的路。
  • 如果我激怒了你们中的任何人,我很抱歉。

标签: java for-loop


【解决方案1】:

考虑一下:

     /*Outputs a serious of 5 numbers, starting at 1.

      The difference between one number to the next one is
      a sequence of numbers, starting at 1 and incremented by 1
      i.e: 1,2,3,4,5
    */

    //represents the difference between one number and the next one.
    //the first difference is 1. 
    int step = 1;

    //represents the numbers to output. Initialized to first number
    int outputNumber = 1;

    //loop over all steps
    for( step=1;  step <= 6 ; step++){

        //do output
        System.out.print(" "+ outputNumber ) ; 
        outputNumber += step; //add step to get the next output number 
    }

对于 b:

        //the sum of multiplies
        int sumOfMultiples =0;

        //loop that runs from i=1 as long as i*30 <=30
        for(int i = 1; (3*i) <=30; i++){

            sumOfMultiples += 3*i;
        }

            System.out.println("Sum of multiples of 3 from 3 to 30 = "+sumOfMultiples);

我希望 cmets 说清楚。

【讨论】:

  • 谢谢。如果我把 (a) 的代码写在纸上,会是这样吗? s = 1(初始值) + 1(初始 i 值) = 2 s = 2(新值) + 2(i++) = 4 s = 4(新值) + 3(i++) = 7 等等..
  • @STJJ 我更改了变量名称和 cmets 以澄清 a。我希望它使逻辑更清晰。随意询问是否需要更多说明。
  • 感谢您对我如此耐心!我知道它是如何工作的! :)
猜你喜欢
  • 2020-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-14
  • 1970-01-01
  • 2021-02-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多