在调用输入有效性检查的位置存在问题

时间:2015-09-24 18:23:51

标签: java function input

我遇到的问题是没有正确检查用户输入的有效性。如果我输入一个字母或字符串作为选择而不是循环并再次询问,它会中断。我很确定我有我的功能,isDouble和isInt,正确而且更多的是放置问题。建议?

public class Main 
{
    static Scanner scan = new Scanner(System.in);

    public static void main(String[] args) 
    {
        displayMenu();

        int entryChoice = scan.nextInt();

        while (entryChoice != 9) 
        {
            System.out.println(userSelection(entryChoice));

            displayMenu();
            isInt(entryChoice);
            entryChoice = scan.nextInt();
        }

        scan.close();
        System.exit(0);
    }

    public static boolean isDouble(double x)
    {
        double userInput = x;
        try 
            {
                userInput = Double.parseDouble(scan.next());
                return true; 
            } 
            catch (NumberFormatException ignore) 
            {
                System.out.println("Invalid input.  Try again.");

                return false;
            }
    }
    public static boolean isInt(int x)
    {
        int userInput = x;
            try 
            {
                userInput = Integer.parseInt(scan.next());
                return true;
            } 
            catch (NumberFormatException ignore) 
            {
                System.out.println("Invalid input");
                return false;
            }
    }

    public static void displayMenu() 
    {
        System.out.println("Please select from the following choices:");
        System.out.println();
        System.out.println("1) Addition");
        System.out.println("2) Subtraction");
        System.out.println("3) Multiplication");
        System.out.println("4) Division");
        System.out.println("5) Raise to a Power");
        System.out.println("6) Square Root");
        System.out.println("7) Store a Number");
        System.out.println("8) Recall Stored Number");
        System.out.println("9) Exit Program");
        System.out.println();
        System.out.println("Enter your choice here: ");
    }

    public static double userSelection(int entryChoice) 
    {
        double result = 0;
        double x = 0;
        double y = 0;

        if (entryChoice == 6) 
        {
            System.out.println("Enter one number: ");
            x = scan.nextDouble();
        } 
        else 
        {
            System.out.println("Enter two numbers seperated by a space");

            x = scan.nextDouble();
            y = scan.nextDouble();
        }
        switch (entryChoice) 
        {
            case 1:
                result = x + y;
                break;

            case 2:
                result = x - y;
                break;

            case 3:
                result = x * y;
                break;

            case 4:
                if (y == 0)
                {
                    System.out.println("Can't divide by zero.  Please enter another number.");
                    y = scan.nextDouble();
                    result = x / y;
                }
                else 
                {
                    result = x / y;
                }
            break;

            case 5:
                result = Math.pow(x, y);
                break;

            case 6:
                result = Math.sqrt(x);
                break;

            case 7:
                //store a number
                break;

            case 8:
                //recall a stored number
                break;

            case 9:
                result = 0;
                break;
            default:

        }
        return result;
    }
}

2 个答案:

答案 0 :(得分:0)

  

我很确定我有我的功能,isDouble和isInt,正确而且更多是放置的问题。

你没有。

您的isInt()方法会忽略其参数,从扫描程序中读取新值并检查它是否为数字,并且不会返回新值,无论它是否为数字。

在任何情况下,您用来收集用户输入的Scanner类已经为您进行了此类验证。你用

开始了正确的方向
int entryChoice = scan.nextInt();

但尝试从Scanner获取令牌是危险的,而不先检查它是否有一个令你获得。

如果查看API docs for Scanner,您会看到nextFoo()hasNextFoo()方法的完整列表。这些是为了一起使用。

一般来说,你想要的是一个循环,它提示用户输入所需的输入,直到他们给出它,如下所示:

    Scanner scan = new Scanner(System.in);
    System.out.println("Please enter a number");
    while (!scan.hasNextInt()) {
        scan.next(); // throw away non-numeric input
        System.out.println("Please enter a number");
    }
    System.out.println("User entered: " + scan.nextInt());

这将最终重新提示用户,直到他们给你一个数字:

  

请输入数字
  苹果
  请输入一个数字
  狐狸
  请输入一个数字
  承担
  请输入一个数字
  42个
  用户输入:42

答案 1 :(得分:0)

这是你的代码,但是我做了很多改变。希望这对你有所帮助。

import java.util.InputMismatchException;
import java.util.Scanner;

public class Main {
static Scanner scan = new Scanner(System.in);
static int entryChoice = 0;
static boolean tester = true;
static double result;

public static void main(String[] args) {
    displayMenu();

    boolean check = isInt(entryChoice);
    while (check && entryChoice != 9) {
        result = userSelection(entryChoice);
        System.out.print(result == 0 && !tester ? "" : result + "\n");
        if (!tester)
            break;

    }

    scan.close();
    System.exit(0);
}

/*
 * public static boolean isDouble(double x) {
 * 
 * try { x = Double.parseDouble(scan.next()); return true; } catch
 * (NumberFormatException ignore) { System.out.println(
 * "Invalid input.  Try again.");
 * 
 * return false; } }
 */

public static boolean isInt(int x) {

    try {
        x = Integer.parseInt(scan.next());
        entryChoice = x;
        return true;
    } catch (NumberFormatException ignore) {
        System.out.println("Invalid input");
        System.err.println("program will be terminated!");
        tester = false;
        return false;
    }
}

public static void displayMenu() {
    System.out.println("Please select from the following choices:");
    System.out.println();
    System.out.println("1) Addition");
    System.out.println("2) Subtraction");
    System.out.println("3) Multiplication");
    System.out.println("4) Division");
    System.out.println("5) Raise to a Power");
    System.out.println("6) Square Root");
    System.out.println("7) Store a Number");
    System.out.println("8) Recall Stored Number");
    System.out.println("9) Exit Program");
    System.out.println();
    System.out.println("Enter your choice here: ");
}

public static double userSelection(int entryChoice) {
    double result = 0;
    double x = 0;
    double y = 0;

    if (entryChoice == 6) {
        try {
            System.out.println("Enter one number: ");
            x = scan.nextDouble();
        } catch (InputMismatchException ignore) {
            System.out.println("Invalid input");

        }
    } else {
        try {
            System.out.println("Enter two numbers seperated by a space");
            x = scan.nextDouble();
            y = scan.nextDouble();
        } catch (InputMismatchException ignore) {
            System.err.println("Invalid input,program will be terminated !");
            tester = false;
            // return ;

        }
    }
    switch (entryChoice) {
    case 1:
        result = x + y;
        break;

    case 2:
        result = x - y;
        break;

    case 3:
        result = x * y;
        break;

    case 4:
        if (y == 0 && tester) {
            System.out.println("Can't divide by zero.  Please enter another number.");
            try {
                y = scan.nextDouble();
            } catch (InputMismatchException ex) {
                System.err.println("invalid input, program will be terminated");
                tester = false;
            }
            result = x / y;
        } else if (tester) {
            result = x / y;
        }
        break;

    case 5:
        result = Math.pow(x, y);
        break;

    case 6:
        result = Math.sqrt(x);
        break;

    case 7:
        // store a number
        break;

    case 8:
        // recall a stored number
        break;

    case 9:
        result = 0;
        break;
    default:

    }
    return result;
}
}