要循环打印连续数字?

时间:2016-11-24 02:38:29

标签: java for-loop

我应该构建一个代码,询问用户名,请求一到十之间的数字,直到我得到该范围内的数字,然后将数字从1打印到用户输入的数字,除了每三个数字应该是在程序开头输入的用户名。例如,如果数字为4且名称为Tom,则输出将为:

  1
  2
  Tom
  4

我正在努力弄清楚如何做第三部分。我宁愿使用for循环。有人可以解释我怎么做到这一点? 到目前为止,这是我的一点点。

import java.util.Scanner;

/**
 *
 * @author Home
 */
public class NewClass {
    public static void main(String[] args) {
        Scanner scan = new Scanner( System.in);

        System.out.print( "Enter your name: ");
        String name = scan.nextLine();

        System.out.print( "Please enter a number between 1 and 10: ");
        number = scan.nextInt();

        while ( number >= 1 && number <= 10)

3 个答案:

答案 0 :(得分:1)

使用模运算符%和for循环并不难实现。 %符号基本上给出了除法的余数。因此,例如12%3为0,13%3为1。

for(int i = 1; i < number ; i++ ){
  if(i%3 == 0) // This is the modulus operator, it gives the remainder
  {
     System.out.print(name);
  } else {
     System.out.print(i);
  }
}

要检查输入是否超过10,您可以在此之前使用if else语句。或者您可以将输入包装在一个循环中,直到用户给出正确的答案:

while (number < 1 || number > 10) {
    System.out.print( "Only accept numbers between 1-10");
    number = scan.nextInt();
}

虽然它会导致无限循环。你可能想给用户一些有限的尝试次数。

答案 1 :(得分:0)

    Scanner scan = new Scanner( System.in);

    System.out.print( "Enter your name: ");
    String name = scan.nextLine();

    System.out.print( "Please enter a number between 1 and 10: ");
    int number = scan.nextInt();

    while (number < 1 || number > 10) {
        System.out.print( "Please enter a number between 1 and 10: ");
        number = scan.nextInt();
    }

    for (int i = 1; i <= number; i++) {
        if (i % 3 == 0) {
            System.out.print(name + " ");
        } else {
            System.out.print(i + " ");
        }
    }

答案 2 :(得分:0)

试试这个

Scanner scan = new Scanner( System.in);
System.out.print( "Enter your name: ");
String name = scan.nextLine();

System.out.print( "Please enter a number between 1 and 10: ");
int number = scan.nextInt();

//asks for a number between one and ten until I get number within that range,
while (number < 1 || number > 10) {
    System.out.print( "No, between 1 and 10: ");
    number = scan.nextInt();
}


for (int i = 1; i <= number; i++) {
    if (i % 3 == 0) {
        System.out.print(name + " ");
    } else {
        System.out.print(i + " ");
    }
}

<强>输出

Enter your name: Tom
Please enter a number between 1 and 10: 21
No, between 1 and 10: 7
1 2 Tom 4 5 Tom 7