我的 while 循环有问题。它正在编译,但没有进入 while 循环,而是跳到下一个条件。
public class Tr {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String name = "";
while(name.length() > 1) {
System.out.print("Enter name : ");
name = in.nextLine( );
if(name.length() > 1) {
System.out.println("It needs to be greater than 1");
}
}
}
}
最佳答案
这是因为 name
的长度为 0,因此控件永远不会进入 while
。您需要使用 do..while
循环,以便它至少执行一次,例如:
do{
System.out.print("Enter name : ");
name = in.nextLine( );
if(name.length() <= 1){
System.out.println("It needs to be greater than 1");
}
}while(name.length() <= 1);
关于Java程序跳过while循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46825551/