简体   繁体   English

扫描器Java验证和多个实例

[英]scanner java validation and multiple instances

I am new to java and doing an assignment. 我是java的新手,正在做作业。 I have to request 3 inputs from the user and I have validation. 我必须从用户处请求3个输入,并且需要验证。 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. 因此,我有两个create 3扫描仪实例,并且还使用一个字符串在while循环中将错误的输入分配给能够再次提示。 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". 例如,如果键入“ 1234bubble”,然后按Enter,则nextInt()将返回1234,下一个nextLine()将显示“ 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. 对于这样的输入,通常不希望这样做,因为“ 1234bubble”不是整数,并且当用户按下Enter键时应该会失败。

For that reason, I typically only use the function nextLine(). 因此,我通常只使用nextLine()函数。 Then, I just process the data manually using functions like Integer.parseInt(..). 然后,我只是使用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();
    }

}

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

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