简体   繁体   English

确保用户输入是两倍?

[英]Ensuring user input is a double?

When using scanner is there a way to check that the user input is what we expect? 使用扫描仪时,有没有一种方法可以检查用户输入是否符合我们的期望?

Say I want a double but the user enters a String what can I do to prompt the user to re-enter the value as a double? 假设我想要一个双精度型,但是用户输入一个字符串,我该怎么做以提示用户重新输入双精度型值?

With the following code if a number is not entered I get a mismatchException. 使用以下代码(如果未输入数字)会得到mismatchException。 I don't want the program to crash if the input is wrong. 如果输入错误,我不希望程序崩溃。

Here is my code: import java.util.Scanner; 这是我的代码:import java.util.Scanner;

public class RoundingNumbers {

  private double y;
  private double x;
  public RoundingNumbers(){
    double y = 0;
    double x = 0;
  }

  public void getNumber(){
    System.out.print("Enter a decimal number: ");
    Scanner num = new Scanner(System.in);
    x = num.nextDouble();
  }

  public void roundNum(){
    y = Math.floor(x + 0.5);
  }

  public void displayNums(){
    System.out.println("The actual number is: " + x);
    System.out.println("The rounded number is: " + y);
  }

}

You can wrap it in a try catch block. 您可以将其包装在try catch块中。 See the below example function. 请参见下面的示例函数。

Whoops. 哎呦。 I wasn't paying close enough attention and didn't see your code example. 我没有给予足够的关注,也没有看到您的代码示例。

Change your getNumber() function to the below definition. 将您的getNumber()函数更改为以下定义。 Note that there are many different ways to do this. 请注意,有许多不同的方法可以执行此操作。 This is just an example. 这只是一个例子。

public void getNumber(){
    Scanner num = new Scanner(System.in);
    while(true) {
        System.out.print("Enter a decimal number: ");
        try {
           x = num.nextDouble();
           break;
       catch(InputMismatchException e) {}
    }
}

You already noticed that you recieve a InputMismatchException if they don't type what you expect. 您已经注意到,如果他们没有输入您期望的内容,则您将收到InputMismatchException。 With this in mind, you can surround the x = num.nextDouble() with a try-catch block and check for that kind of Exception. 考虑到这一点,您可以使用try-catch块将x = num.nextDouble()起来,然后检查这种异常。 For example: 例如:

while (true) {
    try {
        x = num.nextDouble();
        // move along if no exception is thrown
        break;
    } catch (InputMismatchException e) {
        // give the user an error message
        System.out.println("Type mismatch when reading your input. Please insert a double: ");
    }
}

By the way, this is not directly related to your question, but you shouldn't name your Scanner variable as num , because that name doesn't make anyone think of a Scanner - people in general would think it's an int or something. 顺便说一句,这与您的问题没有直接关系,但是您不应将Scanner变量命名为num ,因为该名称不会使任何人想到Scanner-人们通常会认为这是int或其他东西。 It's a good programming practice to give your variables names that fits them. 给您的变量合适的名称是一种很好的编程习惯。

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

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