how to check the data type validity of user's input (Java Scanner class)

前端 未结 5 1410
情话喂你
情话喂你 2020-12-17 07:29

I am trying to make a simple UI that asks users to input double-type numbers, if theirs input is not of double type, the program should keep printing the prompt until user i

5条回答
  •  遥遥无期
    2020-12-17 07:52

    I think the reason your code is not working due to first it will check the given input is of type double or not(sc.hasNextDouble()) if not then take again input(sc.hasNext()... no use of this line),then again you are taking input (userInput = sc.nextDouble())

    I would suggest to do like this:

    Scanner sc = new Scanner(System.in);
    System.out.println("Type a double-type number:");
    double userinput;
    while (!sc.hasNextDouble())
    {
        System.out.println("Invalid input\n Type the double-type number:");
    }
    
    userInput = sc.nextDouble(); 
    

    you need to give the input again if you are providing double input at first time,i think if any time you give double input then you have to provide it again ,it looks to impossible to provide input only one time.

提交回复
热议问题