在Java中每行显示五个数字

时间:2014-11-23 18:53:32

标签: java

//我想在用户输入的范围内显示所有可被3和4整除的数字和5个数字 每行,但我的代码没有工作。我在第二次犯了一个错误,但我无法弄明白。请帮助我。

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    System.out.println("Enter lowest value:");
    int lowest = input.nextInt();

    System.out.println("Enter upper value:");
    int upper = input.nextInt();

    for(int i = lowest; lowest <= upper; lowest++){
        for(int j = 0; j < 5; j++ ){
            if(lowest % 3 == 0 && lowest % 4 == 0){
                System.out.print(lowest + "  ");
            }
        }
        System.out.println();   
    }
}  

2 个答案:

答案 0 :(得分:1)

将您的for循环更改为:

for(int i = lowest; i <= upper; i++){
    for(int j = 0; j < 5 && i <= upper; i++){
        if(i % 3 == 0 && i % 4 == 0){
            System.out.print(i + "  ");
            j++;
        }
    }
    System.out.println();
}

原始代码存在一些问题。例如,i从未使用过。此外,由于i从未在第二个for循环中递增,因此相同的值将被打印5次。

另一件事是i % 3 == 0 && i % 4 == 0相当于i % 12 == 0

答案 1 :(得分:0)

您没有使用最低值,但没有增加最低值:)。试试这个:

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    System.out.println("Enter lowest value:");
    int lowest = input.nextInt();

    System.out.println("Enter upper value:");
    int upper = input.nextInt();

    int printCount = 1;
    while(lowest <= upper){
        if(lowest % 3 == 0 && lowest % 4 == 0){
            System.out.print(lowest + "  "); //print a number divisible by 3,4
            if(printCount%5==0){
                System.out.println();        //when printCount reaches a multiple of 5 i.e. 5,10,15.., print a new line
            }
            printCount++;
        }
        lowest++;
    }
}  
相关问题