简体   繁体   English

Java程序跳过while循环

[英]Java program skipping while loop

I am having a problem with my while loop. 我的while循环有问题。 It is compiling but it isn't entering while loop and it skips to next condition. 它正在编译,但没有进入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");
            }
        }
    }
}

That's because the name has 0 length and hence, the control never enters while . 这是因为name长度name 0,因此控件从不会进入while You need to use do..while loop so that it executes at least once, eg: 您需要使用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);

It appears that the logic you want is to prompt the user for a name, and keep prompting until a name with length greater than one is entered. 看来,您想要的逻辑是提示用户输入名称,并一直提示直到输入的名称长度大于1。 A do loop would seem to fit well here: 一个do循环似乎很适合这里:

Scanner in = new Scanner(System.in);
String name;

do {   
    System.out.print("Enter name with length > 1: ");
    name = in.nextLine();
    // you can print an optional feedback message
    if (name.length() <= 1) {
        System.out.println("length needs to be greater than 1");
    }
} while (name.length() <= 1);

Your variable name gets initialized to name = ""; 您的变量name被初始化为name = ""; , so name.length() == 0; ,所以name.length() == 0; .

Your while condition checks whether the length greater than 1, and it isn't so it skips. 您的while条件会检查长度是否大于1,否则不会跳过。

因为name.length()始终返回0,所以您的条件永远不会为真。

(name.length() < 1) change this condition in our while and if conditions. (name.length()<1)在我们的while和if条件中更改此条件。

You have defined an empty string called name and the condition for your while loop condition checks if the length of name is greater than 1 or not. 您已经定义了一个名为name的空字符串,并且while循环条件的条件将检查name的长度是否大于1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM