gpt4 book ai didi

java - Do while 循环不会读取循环内输入的变量

转载 作者:行者123 更新时间:2023-12-01 20:10:13 24 4
gpt4 key购买 nike

对于我的程序,我要编写一个接受 2 到 10 行之间的程序。生成 n 行的乘法三角形。每行包含不超过其行大小的条目。这一点我没有问题。然而,当用户在我的问题“请输入您想要打印的行数:”中输入数字 0 后,它应该终止循环并打印“感谢您使用此程序!”我使用了 DO...WHILE 循环来确定用户是否希望继续。在我的循环中,我将用户想要打印的数字声明为 int num。只要 num>=1,我的循环就应该继续。但是,我继续在 while (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

最佳答案

“num”的声明必须位于“do”之前。这可能是:

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

关于java - Do while 循环不会读取循环内输入的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46795331/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com