如何在 do while 循环中初始化变量而不传递值直到循环结束?
How to initialize a variable in a do while loop without passing the value until the loop has closed?
我一直在写一个程序,要求输入1到4之间的数字。为了防止输入超出范围的数字。但是,该变量不断传递给另一段代码并导致程序失败。
这是 do while 循环:
do
{
System.out.println("Please enter a quarter number 1-4: ");
quarter = scanIn.nextInt();
}while((quarter > 5 ) && (quarter < 0));
这是运行变量的代码段:
for (int n = ((quarter * 3)-3); n < (quarter*3); n++)
{
String sum = fmt.format(monthSales[n]);
System.out.printf("Sales for month %d: %s\n", n+1, sum);
}
这是returns输入错误时的错误:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -6
at lab4.Lab4.main(Lab4.java:57)
我曾尝试将 "quarter" 的范围限制在循环内,但 while 子句不起作用。在循环关闭之前如何防止变量传递?
p.s。这个问题是作业的一部分,因此我必须使用 do while 循环。
我在你的代码中看到一件事:
"do/while"条件好像不对。据我所知,如果您的意图是不断询问用户,直到 s/he 告知 1 到 4 之间的有效季度,则条件应该类似于
do {
// ...
} while (quarterNum < 1 || quarterNum > 4);
如果我假设 quarter 在中间的某些代码中接收到 quarterNum 的值,则第二部分似乎是正确的,并且仅当 quarter 不是有效值(准确地说是 -1)时才会发生异常。修复 do/while 条件,它将不再可能。
我看不出限制变量范围对您的问题有什么影响。 (我什至不明白你所说的 "prevent[ing] the variable from passing until the loop has closed" 是什么意思)。
希望能帮到你
我一直在写一个程序,要求输入1到4之间的数字。为了防止输入超出范围的数字。但是,该变量不断传递给另一段代码并导致程序失败。 这是 do while 循环:
do
{
System.out.println("Please enter a quarter number 1-4: ");
quarter = scanIn.nextInt();
}while((quarter > 5 ) && (quarter < 0));
这是运行变量的代码段:
for (int n = ((quarter * 3)-3); n < (quarter*3); n++)
{
String sum = fmt.format(monthSales[n]);
System.out.printf("Sales for month %d: %s\n", n+1, sum);
}
这是returns输入错误时的错误:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -6
at lab4.Lab4.main(Lab4.java:57)
我曾尝试将 "quarter" 的范围限制在循环内,但 while 子句不起作用。在循环关闭之前如何防止变量传递? p.s。这个问题是作业的一部分,因此我必须使用 do while 循环。
我在你的代码中看到一件事:
"do/while"条件好像不对。据我所知,如果您的意图是不断询问用户,直到 s/he 告知 1 到 4 之间的有效季度,则条件应该类似于
do {
// ...
} while (quarterNum < 1 || quarterNum > 4);
如果我假设 quarter 在中间的某些代码中接收到 quarterNum 的值,则第二部分似乎是正确的,并且仅当 quarter 不是有效值(准确地说是 -1)时才会发生异常。修复 do/while 条件,它将不再可能。
我看不出限制变量范围对您的问题有什么影响。 (我什至不明白你所说的 "prevent[ing] the variable from passing until the loop has closed" 是什么意思)。
希望能帮到你