简体   繁体   中英

scanner java validation and multiple instances

I am new to java and doing an assignment. I have to request 3 inputs from the user and I have validation. If I do it with only one instance of the scanner I get all messed up.

If I use three instances with a bit of workaround my code works. Only I guess this is not best practice. I have been reading a bit the manual regarding the scanner, but cannot understand the problem

Thanks

enter code here
Scanner input=new Scanner(System.in);               
Scanner input2=new Scanner(System.in);          

int input_integer=0;
double input_double=0.0;
String input_string="";
double value=0;

System.out.print("\n Please enter a number: ");     

    while(!input.hasNextInt()){ 
        System.out.println("***** Error: the char inserted is not a number! *****");
        String input_wrong=input.next();
        System.out.print("\n Please enter a number: ");     
    }   

    input_integer=input.nextInt();

    System.out.print("\n Please enter a double: ");     
    while(!input.hasNextDouble()){  
        System.out.println("***** Error: the char inserted is not a double! *****");
        String input_wrong=input.next();
        System.out.print("\n Please enter an double: ");    
    }           
    input_double=input.nextDouble();

    System.out.print("\nPlease enter a string: ");          
    input_string=input.nextLine();

So I had two create 3 scanner instances and also to use a string to assign the wrong input in the while cycle to the able to prompt again. Any suggestion? I am sure there is a better way but I would try to understand..

Thanks!

I'm not exactly sure I understand what problem you're having, but scanner has some strange behaviors which are not immediately obvious. For instance, if you type "1234bubble" then press enter, then nextInt() will return 1234 and the next nextLine() will say "bubble". That is usually not desired behavior for inputs like this because "1234bubble" is not an integer and should have failed when the user pressed enter.

For that reason, I typically only use the function nextLine(). Then, I just process the data manually using functions like Integer.parseInt(..). That way, I can guarantee that I'm processing the whole line in a clear and obvious manner, unlike other techniques which create confusing code.

Here's how I would have written your program:

import java.io.IOException;
import java.util.Random;
import java.util.Scanner;

public class Main
{
    static Random rand = new Random();

    public static void main(String[] args) throws IOException
    {
        Scanner input = new Scanner(System.in);

        int input_integer = 0;
        double input_double = 0.0;
        String input_string = "";
        double value = 0;

        while (true)
        {
            System.out.print("Please enter an integer: ");

            // Get the entire next line of text
            String text = input.nextLine();

            try
            {
                // Try to turn the line into an integer
                input_integer = Integer.parseInt(text);

                // Turning it into an int succeeded!
                // Leave the while loop
                break;
            } catch (NumberFormatException e)
            {
                // Turning it into an int failed.
                System.out.println("***** Error: the text inserted is not an integer! *****");  
            }
        }

        while (true)
        {
            System.out.print("Please enter a double: ");

            // Get the entire next line of text
            String text = input.nextLine();

            try
            {
                // Try to turn the line into a double
                input_double = Double.parseDouble(text);

                // Turning it into an double succeeded!
                // Leave the while loop
                break;
            } catch (NumberFormatException e)
            {
                // Turning it into an double failed.
                System.out.println("***** Error: the text inserted is not a double! *****");    
            }
        }

        System.out.print("Please enter a string: ");
        input_string = input.nextLine();

        // This is done automatically when the program stops, but it's
        // a good habit to get into for longer running programs.
        input.close();
    }

}

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