Java 我的do while循环在一次迭代后停止。我怎样才能让它继续下去?
我的代码在一次迭代后终止,即使Java 我的do while循环在一次迭代后停止。我怎样才能让它继续下去?,java,loops,Java,Loops,我的代码在一次迭代后终止,即使quit为true import java.util.*; public class calc { public static boolean quit; public static void main(String[] args) { keepGoing(); } public static void keepGoing() { do { Scanner s = new Scanner(System.in);
quit
为true
import java.util.*;
public class calc {
public static boolean quit;
public static void main(String[] args) {
keepGoing();
}
public static void keepGoing() {
do {
Scanner s = new Scanner(System.in);
String input = s.nextLine();
String inputLower = input.toLowerCase();
int findQuit = inputLower.indexOf("quit");
if (findQuit != -1) {
boolean quit = false;
}
} while (quit == true); {
System.out.println("OTHER CODE GOES IN PLACE OF THIS PRINTLN");
}
}
}
布尔值的默认值为false
。所以改变
public static boolean quit;
到
另外您当前仅使用阴影变量将其设置为false
。改变
if (findQuit != -1) {
boolean quit = false;
}
到
或消除if
并直接指定布尔值
quit = (findQuit == -1);
最后,不需要检查布尔值是否为true。改变
while (quit == true);
到
您必须先初始化变量quit。
定义时或之后执行,但必须在执行while循环开始之前执行
public static boolean quit = true;
必须将quit变量定义为true。因为布尔变量的默认值为false
public static boolean quit = true;
您需要更改此代码:
if (findQuit != -1) {
boolean quit = false;
}
致:
因为不需要再次定义相当大的变量
不需要使用equals检查布尔值。因此,将代码更改为:
while (quit == true);
{
System.out.println("OTHER CODE GOES IN PLACE OF THIS PRINTLN");
}
致:
完整代码:
import java.util.*;
public class calc {
public static boolean quit = true;
public static void main(String[] args) {
keepGoing();
}
public static void keepGoing() {
do {
Scanner s = new Scanner(System.in);
String input = s.nextLine();
String inputLower = input.toLowerCase();
int findQuit = inputLower.indexOf("quit");
if (findQuit != -1) {
quit = false;
}
} while (quit);
{
System.out.println("OTHER CODE GOES IN PLACE OF THIS PRINTLN");
}
}
}
如果未为staticquit
指定值,则该值将为false(请参阅)。那么它在代码中永远不会更新为true。
if (findQuit != -1) {
boolean quit = false;
}
if (findQuit != -1) {
quit = false;
}
while (quit == true);
{
System.out.println("OTHER CODE GOES IN PLACE OF THIS PRINTLN");
}
while (quit);
{
System.out.println("OTHER CODE GOES IN PLACE OF THIS PRINTLN");
}
import java.util.*;
public class calc {
public static boolean quit = true;
public static void main(String[] args) {
keepGoing();
}
public static void keepGoing() {
do {
Scanner s = new Scanner(System.in);
String input = s.nextLine();
String inputLower = input.toLowerCase();
int findQuit = inputLower.indexOf("quit");
if (findQuit != -1) {
quit = false;
}
} while (quit);
{
System.out.println("OTHER CODE GOES IN PLACE OF THIS PRINTLN");
}
}
}