Arpit Manaktala
Arpit Manaktala

Reputation: 27

How to keep prompting the user when they enter nothing

I have a simple do while loop here. The only problem I am having is this loop right now is only accepting numbers. I need it to accept everything except a blank input.

import java.util.Scanner;

public class Assignment6 {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        boolean notValid = true;
        int numberAsInt = 0;
        do {
            try {
               System.out.print("Enter a number to Convert > ");
               String number = scan.nextLine();
               numberAsInt = Integer.parseInt(number);
               notValid = false;
            }
            catch (Exception e) {
            }

        } while (notValid);
    }
}

Upvotes: 0

Views: 308

Answers (4)

Iootu
Iootu

Reputation: 344

I'm a bit confused on what you asked because you are parsing the result in your code, but I hope this is what you are asking of:

public class Assignment6 {
public static void main(String[]args){
   Scanner scan = new Scanner( System.in );
   boolean notValid = true;
   String  input;
   do{
           System.out.print( "Enter a number to Convert > "  );
           input = scan.nextLine( );
           if(!input.isEmpty())
             notValid = false;

    } while ( notValid );

   } 
}

Upvotes: 1

Sagar Pudi
Sagar Pudi

Reputation: 4814

Use this snippet in your code:

if(number.trim().equals(""))
                       {
                         notValid = ture;
                         sysytem.out.println(" Please do not enter blank space");
                        }

Upvotes: 0

Mohit
Mohit

Reputation: 1215

Here we are comparing if entered value is space than not valid will be true

 try {
                   System.out.print( "Enter a number to Convert > "  );
                   String number = scan.nextLine( );
                   if(number.equals(" "))
                   {
                     notValid = ture;
                     sysytem.out.println(" Please do not enter blank space");
                    }
                    else
                   {
                     numberAsInt = Integer.parseInt(number);
                     notValid = false;
                    }
            }

Upvotes: 0

Maroun
Maroun

Reputation: 95968

You can do something like:

String number = readLine("Enter a number to Convert > ");
while(number.isEmpty()){
     number = readLine("Please enter a *non-blank* number > ");
}

Upvotes: 1

Related Questions