在Java中,是否可以为具有双重输入的异常处理创建可以初始化变量的方法?

huangapple go评论75阅读模式
英文:

Is is possible to create method for exception handling with double input that can initialize variable in java?

问题

我想知道是否可能创建一个异常处理方法,就像这样:

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    
    do {
        try {
            double a = in.nextDouble();
            double b = in.nextDouble();
            double c = in.nextDouble();

            // 与变量a、b和c一起工作的一些代码
        }
        catch(java.util.InputMismatchException exc) {
            System.out.println("输入错误。");
            in.next();
        }
    } while(true);
}

这样,我可以从键盘输入一些变量,如果不是double类型,就会显示"输入错误",并要求您重新输入。是否可能创建一个方法来处理所有这些?在Java中是否可能创建能够像这样工作的方法:

double a, b, c;
myMethodTest(a);

并且实际上会像第一段代码一样工作?如果可能的话,应该如何做?我知道会有一个错误,显示"变量可能尚未初始化",但是否有方法可以解决这个问题?方法能否初始化放在()中的变量,就像myMethodTest(a)可以可能初始化a并为我处理所有异常吗?

英文:

I'm wondering if it's possible to create method for exception handling like this:

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        
        do {
            try {
                double a = in.nextDouble();
                double b = in.nextDouble();
                double c = in.nextDouble();

                // some code that works with a, b and c variables
            }
            catch(java.util.InputMismatchException exc) {
                System.out.println("Wrong input.");
                in.next();
            }
        } while(true);
    }

So I can input some variables from keyboard, if it's not double, then it says "Wrong input." and wants you to type again. Is it possible to create method that will handle all of this? Is it even possible in Java to create method that can work like this:

double a, b, c;
myMethodTest(a);

and would actually work in the same way as the first code? How to do that, if possible? I know that there is an error that says "variable may not have been initialized", but is there a way to work around it? Can method initialize the variable that I put in (), like myMethodTest(a) could possibly initialize a and do all the exception handling for me?

答案1

得分: 2

按照以下方式进行操作:

import java.util.Scanner;

public class Main {
    public static void main(String[] argv) {
        Scanner in = new Scanner(System.in);
        double a, b, c;
        a = getDouble(in, "Enter the value of a: ");
        b = getDouble(in, "Enter the value of b: ");
        c = getDouble(in, "Enter the value of c: ");
        System.out.println(a + ", " + b + ", " + c);
    }

    static double getDouble(Scanner in, String inputMessage) {
        double n = 0;
        boolean valid = true;
        do {
            valid = true;
            System.out.print(inputMessage);
            try {
                n = Double.parseDouble(in.nextLine());
            } catch (NullPointerException | NumberFormatException e) {
                System.out.println("Invalid input. Try again");
                valid = false;
            }
        } while (!valid);
        return n;
    }
}

一个示例运行:

Enter the value of a: a
无效的输入。请重试
Enter the value of a: abc
无效的输入。请重试
Enter the value of a: 10
Enter the value of b: 10.5
Enter the value of c: hello
无效的输入。请重试
Enter the value of c: 20
10.0, 10.5, 20.0
英文:

Do it as follows:

import java.util.Scanner;

public class Main {
	public static void main(String[] argv) {
		Scanner in = new Scanner(System.in);
		double a, b, c;
		a = getDouble(in, "Enter the value of a: ");
		b = getDouble(in, "Enter the value of b: ");
		c = getDouble(in, "Enter the value of c: ");
		System.out.println(a + ", " + b + ", " + c);
	}

	static double getDouble(Scanner in, String inputMessage) {
		double n = 0;
		boolean valid = true;
		do {
			valid = true;
			System.out.print(inputMessage);
			try {
				n = Double.parseDouble(in.nextLine());
			} catch (NullPointerException | NumberFormatException e) {
				System.out.println("Invalid input. Try again");
				valid = false;
			}
		} while (!valid);
		return n;
	}
}

A sample run:

Enter the value of a: a
Invalid input. Try again
Enter the value of a: abc
Invalid input. Try again
Enter the value of a: 10
Enter the value of b: 10.5
Enter the value of c: hello
Invalid input. Try again
Enter the value of c: 20
10.0, 10.5, 20.0

答案2

得分: 0

以下是您要求的翻译内容:

您可以使用类似于 hasNextDouble() 的方法来检查有效的双精度数值。以下是示例代码,您可以根据需要进行修改:

public static void onlyDouble() {

    double myDouble = 0;
    System.out.println("请输入双精度数值:");
    do {
        while (!in.hasNextDouble()) {
            System.out.println("请输入有效的双精度数值:");
            in.next();
        }
        myDouble = in.nextDouble();
    } while (myDouble <= 0);

}

希望这能帮助您
英文:

You can check like hasNextDouble() for valid double I have sample code for you below you can modify that according to your need-

 public static void onlyDouble() {

    double myDouble = 0;
    System.out.println(&quot; Please enter Double&quot;);
    do {
        while (! in.hasNextDouble()){
            System.out.println(&quot; Please enter valid Double :&quot;);
            in.next();
        }
        myDouble = in.nextDouble();
    }while (myDouble  &lt;= 0);

}

Hope this will help you.

huangapple
  • 本文由 发表于 2020年3月16日 15:41:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/60702001.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定