while循环不会读取循环

时间:2017-10-17 16:54:26

标签: java

对于我的程序,我要写一个程序,接受2到10之间的行数。产生一个n行的乘法三角形。每行包含最大行大小的条目。这个我没问题。但是,当用户在我的问题中输入数字0"请输入您要打印的行数:"它应该终止循环并打印"感谢您使用此程序!"我使用了一个DO ... WHILE循环来确定用户是否希望继续。在我的循环中,我声明了用户想要打印为int num的数字。只要num> = 1,我的循环就会继续。但是我继续收到该行的错误消息(num> = 1);说它找不到符号。为什么这么说?提前谢谢

import java.io.*;
import java.util.*;
public class Prog166g
{ //begin testshell 
public static void main (String[] args)
{ //begin main
 int i;
    int outer;
    int inner;
    int result;
    int example = 4;
    System.out.print("Number of rows for this triangle : " + example +"\n");
    for ( i = 1; i <= example; i++) {
        System.out.printf("%5s", i);
    }
    System.out.println("");
    for ( outer = 1; outer <= 4; outer++) {
        for ( inner = 1; inner <= outer; inner++) {
            result = outer * inner;
            System.out.printf("%5s", result);
        }
        System.out.println("");
    }
    System.out.println("");

        do{
        System.out.print("Please enter the number of rows you would like to print: ");
        Scanner kbReader = new Scanner(System.in);
        int num = kbReader.nextInt();
        System.out.println("");
        System.out.println("Number of rows for this triangle: " + num);
        for ( i = 1; i <= num; i++) {
            System.out.printf("%5s", i);
        }
        System.out.println("");
        for ( outer = 1; outer <= num; outer++) {
            for ( inner = 1; inner <= outer; inner++) {
                result = outer * inner;
                System.out.printf("%5s", result);
            }
        }
     }while (num>=1);


   System.out.println("Thank you for using this program"); 
}// ends main
}//ends testshell

2 个答案:

答案 0 :(得分:2)

您对&#34; num&#34;的声明必须在&#34; do&#34;之前。这可能是:

...
int num;
do {
    ...
    num = kbReader.nextInt();
    ...;
}
...

答案 1 :(得分:1)

你的num变量超出了范围。只需简单地将它声明在循环之上。

int example = 4;
int num; //Declare num here
System.out.print("Number of rows for this triangle : " + example +"\n");
for ( i = 1; i <= example; i++) {
    System.out.printf("%5s", i);
}
System.out.println("");
for ( outer = 1; outer <= 4; outer++) {
    for ( inner = 1; inner <= outer; inner++) {
        result = outer * inner;
        System.out.printf("%5s", result);
    }
    System.out.println("");
}
System.out.println("");

    do{
    System.out.print("Please enter the number of rows you would like to print: ");
    Scanner kbReader = new Scanner(System.in);
    num = kbReader.nextInt();
    System.out.println("");
    System.out.println("Number of rows for this triangle: " + num);
    for ( i = 1; i <= num; i++) {
        System.out.printf("%5s", i);
    }
    System.out.println("");
    for ( outer = 1; outer <= num; outer++) {
        for ( inner = 1; inner <= outer; inner++) {
            result = outer * inner;
            System.out.printf("%5s", result);
        }
    }
 }while (num>=1);


  System.out.println("Thank you for using this program"); 
}// ends main
}//ends testshell