try and catch inputmismatchexception:检查整数时出错-逻辑不正确

6fe3ivhb  于 2021-07-11  发布在  Java
关注(0)|答案(1)|浏览(323)

我正在尝试创建一个方法,使用带有catch inputmatch的try-and-catch语句检查输入错误。它不起作用。有人能告诉我为什么我的return语句不返回用户的输入并将其存储在主类中调用的整数中(不包括call语句)。

System.out.print("Please enter the percent achieved for " + sName + ": %");
 PromptErrorCheckingPercent(iPercent);

        public static int PromptErrorCheckingPercent(int test){
    Scanner keyboard = new Scanner(System.in);
    boolean valid = false;
        while (!valid)
        {
            try
            {
                test = keyboard.nextInt();
                valid = true;
            }
            catch(InputMismatchException e)
            {
                System.out.println("Invalid Input. Please enter a valid integer");
                keyboard.nextLine(); //nextLine for a reason 
            }
        }   
        return test;
lo8azlld

lo8azlld1#

InputMismatchException 被抛出而不是 keyboard.nextLine(); //nextLine for a reason . 此外,不需要在的参数/参数中传递值 promptErrorCheckingPercent() 方法,因为您正在尝试的内容在java中是不允许的。
可能您认为传递该变量将有助于将数据存储在该变量中。它是 C-language 支持 Pointer (变量的地址)但为了安全起见,不允许在 JAVA .
你可以查看下面的代码,看看它是否能解决你的问题。

import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Please enter the name:");
        String sName = keyboard.nextLine();
        System.out.print("Please enter the percent achieved for " + sName + ": %");
        int iPercent = promptErrorCheckingPercent();
    }

    public static int promptErrorCheckingPercent() {
        Scanner keyboard = new Scanner(System.in);
        boolean valid = false;
        int test = -1;
        while (!valid) {
            try {
                test = keyboard.nextInt();
                valid = true;
            } catch(InputMismatchException e) {
                System.out.println("Invalid Input. Please enter a valid integer");
                return promptErrorCheckingPercent(); // Recursion by calling the method itself
            }
        }   
        return test;
    }
}

相关问题