简体   繁体   中英

Java program skipping while loop

I am having a problem with my while loop. It is compiling but it isn't entering while loop and it skips to next condition.

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 . You need to use do..while loop so that it executes at least once, eg:

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. A do loop would seem to fit well here:

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 = ""; , so name.length() == 0; .

Your while condition checks whether the length greater than 1, and it isn't so it skips.

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

(name.length() < 1) change this condition in our while and if conditions.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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