使用while循环在java中计数10

时间:2017-01-19 17:43:20

标签: java

这段代码的目标是数到50乘10但我似乎无法弄清楚如何用while循环来做。我会将整数ntp乘以10吗?

import java.util.Scanner;

public class CountingWhile {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Type in a message, and I'll display it how ever many times you want");
        System.out.print("Message: ");
        String message = keyboard.nextLine();
        System.out.print("Number of times printed: ");
        int ntp = keyboard.nextInt();

        int n = 10;
        while (n <= ntp) {
            System.out.println(n + ". " + message);
            n += 10; //its the same as "n = n + 1" or "n++"
        }
    }
}

2 个答案:

答案 0 :(得分:1)

我不确定我是否理解您的问题,但此代码不会打印任何内容。您告诉程序打印一些消息5次但是在循环中已经处于开始状态将不是true,而且sice 10&lt; = 5是false。你为什么不加倍数,你在你的间隔(在这种情况下10)给你的程序?

答案 1 :(得分:-1)

import java.util.Scanner;

public class CountingByTens {
  public static void main( String[] args ) {
    Scanner keyboard = new Scanner(System.in);
    System.out.println( "Type in a number and we will count by tens." );
    int inputNumber = keyboard.nextInt();

    int n = 10;
    while ( n  <=  inputNumber ) {
       System.out.println( n );
       n += 10;
    }
  }
}