Java程序跳过while循环

标签 java while-loop

我的 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/

相关文章:

java - Gradle和Spring Boot : create task for multipart project

java - 使用扫描仪读取

C while 循环跳过输入

java - 将 Long[] 转换为 long[](原始)java

java - 从 Textarea 读取时不保留换行符

c# - Java 等价于 C# async/await?

c++ - 标志控制 while 循环搜索 txt 文件

java - 如何遍历 R.java 类的 id 属性?

python - 在Python循环中计算余额和每月付款

sql - SQL Server 2008 R2 有没有办法避免这种循环?