学习基本循环

时间:2014-10-09 20:26:02

标签: java

我的程序中有后续步骤:

  1. 我需要输入要打印数字的次数。
  2. 之后我必须输入一个值来开始。
  3. 最后,该值必须重复与输入打印值一样多次。
  4. //就我而言......

    import java.util.Scanner;
    public class Series{
        public static void main(String[] args) {
            Scanner keyb = new Scanner(System.in);
    
            System.out.println("How many numbers do you want to print? ");
            int number = keyb.nextInt();
    
            System.out.println("What value would you like to start with? ");
            int value1 = keyb.nextInt();
    
            System.out.println("Typ increased value: ");
            int increase1 = keyb.nextInt();
    
            System.out.println(value1 + increase1);
        }
    }
    

    我得到的结果是:

    How many numbers do you want to print? 
    5
    What value would you like to start with? 
    50
    Typ increased value: 
    500
    550
    

    我的问题是如何相互打印5个数字,每个打印值增加+500?

3 个答案:

答案 0 :(得分:2)

关键在于Java循环。循环允许相同的代码位执行所需的次数,或直到满足某个条件。 for loop的语法如下:

for(declaration; loop condition; step)

所以例如

for(int x = 0; x < 5; x++) {
     System.out.println("The number is " + x);
}

这将打印:

The number is 0
The number is 1
...
The number is 4

现在您可以看到这可能如何适用于您的代码。

一些Pseudocode可以帮助您入门

我们来看看你得到的代码:

System.out.println(value1 + increase1);

因此,您知道这会输出增加的值,但您需要每次都增加它。这意味着你需要跟踪价值:

runningTotal := value1;

for the amount of times to loop {
    runningTotal = runningTotal + increase1
    output runningTotal
}

现在把它变成Java,你就得到了解决方案!

额外阅读

此链接遍历Java中提供的所有循环

答案 1 :(得分:1)

java中有4种基本类型的循环 1.()(。) 2. for()
3.做{...} while()
4.对于每个循环

首先是循环:

while(Boolean_expression)
{
   //Statements
}

第二个循环:

for(initialization; Boolean_expression; update)
{
   //Statements
}

第三次做:

do
{
   //Statements
}while(Boolean_expression);

每个循环的第四个或循环的高级:

for(declaration : expression)
{
   //Statements
}

根据你的问题,你可以做的是:

for(int i = number; i < number + value1;)
{
    System.out.println(i);
    i += increase1;
}

答案 2 :(得分:0)

public static void main(String[] args) {
        Scanner keyb = new Scanner(System.in);

        System.out.println("How many numbers do you want to print? ");
        int number = keyb.nextInt();

        System.out.println("What value would you like to start with? ");
        int value1 = keyb.nextInt();

        System.out.println("Typ increased value: ");
        int increase1 = keyb.nextInt();
        for(int i = 0; i < number; i++)
        {
             System.out.println(value1);
             value1 += increase1;
        }
    }

尝试这样的事情。