简体   繁体   English

捕获/尝试在扫描仪的输入不匹配异常中不起作用?

[英]Catch/try not working for input mismatch exception with scanner?

Alright so I'm taking a CS security class that has some basic java programing in it and our first assignment is to play with BigInteger . 好吧,所以我要学习一个CS安全类,该类中包含一些基本的Java程序,我们的第一个任务是使用BigInteger However, we also have to "bullet proof" our program. 但是,我们还必须“防弹”我们的程序。 And while my method isn't the most ideal, it works EXCEPT for the first input. 虽然我的方法不是最理想的方法,但除了第一个输入之外,它的工作原理还不错。 Aka if I type in an invalid input for any of the input.new---(); 如果我为任何输入输入了无效的输入,也就是新的input.new---(); my program will prompt the user to try again with valid numbers. 我的程序将提示用户使用有效数字再试一次。 But the first input.nextInt(); 但是第一个input.nextInt(); will still take invalid input and crash, displaying the "java.util.InputMismatchException" and then rambles on about scanner. 仍然会接受无效的输入并崩溃,显示"java.util.InputMismatchException" ,然后在扫描仪上四处乱逛。 Any ideas as to why this is happening? 有什么想法为什么会这样? ps The program must not display an error log under any circumstances. ps在任何情况下,程序都不得显示错误日志。

import java.io.*;
import java.util.*;
import java.math.*;

class BigNumber{
   public static void main(String args[]){

     while(true){ 
      try{
         Scanner input = new Scanner(System.in);

         System.out.print("if you wish to exit the program type in '0,' to continue running the program type in any other value: ");
         double esc= input.nextDouble();
         if(esc == 0){ break;}
         else{System.out.println("Ok, program running...");}
         input.nextLine();

         System.out.print("Enter number a: ");
         String aValue = input.nextLine();

         System.out.print("Enter number b: ");
         String bValue = input.nextLine();

         System.out.print("Enter a number 'n': ");
         String nValue = input.nextLine();
         while (Integer.parseInt(nValue) < 1)
         {
            if (Integer.parseInt(nValue) < 1)
            {
               System.out.print("Please enter a valid number (n>1): ");
               nValue = input.nextLine();
            }
         }

         BigInteger a= new BigInteger(aValue);
         BigInteger b= new BigInteger(bValue);
         BigInteger n= new BigInteger(nValue);

         System.out.println("---------------------------");
         System.out.println("1) a xor b: " + a.xor(b));
         System.out.println("2) b xor b: " + b.xor(b));
         System.out.println("3) a xor b xor a: " + a.xor(b).xor(a));
         System.out.println(" ");
         System.out.println("4) ab mod n: " + a.modPow(b,n));
         System.out.println(" ");
         System.out.println("5) a shifted to the right by 6: " + a.shiftRight(6));
         System.out.println("6) b shifted to the left by 3: " + b.shiftLeft(3));
         System.out.println("---------------------------");

      }
      catch (NumberFormatException e){
         System.out.println("-----> Please try entering a valid number(s) <-----");
      }

    } 
  }
}

Your catch block only handles NumberFormatException . 您的catch块仅处理NumberFormatException If you're trying to handle all Exception (s) then I suggest you change this 如果您尝试处理所有Exception那么建议您更改此设置

catch (NumberFormatException e){

to something like

catch (Exception e){

nextDouble() will read double value. nextDouble()将读取双nextDouble()值。 If parseDouble fails, a InputMismatchException is thrown. 如果parseDouble失败,则抛出InputMismatchException

Here the code of the class: 下面是该类的代码:

public double nextDouble() {
    // Check cached result
    if ((typeCache != null) && (typeCache instanceof Double)) {
        double val = ((Double)typeCache).doubleValue();
        useTypeCache();
        return val;
    }
    setRadix(10);
    clearCaches();
    // Search for next float
    try {
        return Double.parseDouble(processFloatToken(next(floatPattern())));
    } catch (NumberFormatException nfe) {
        position = matcher.start(); // don't skip bad token
        throw new InputMismatchException(nfe.getMessage());
    }
}

Oracle says 甲骨文说

public class InputMismatchException extends NoSuchElementException Thrown by a Scanner to indicate that the token retrieved does not match the pattern for the expected type, or that the token is out of range for the expected type. 公共类InputMismatchException扩展了NoSuchElementException,由Scanner抛出,以指示检索到的令牌与预期类型的​​模式不匹配,或者令牌超出预期类型的​​范围。

public class NumberFormatException extends IllegalArgumentException Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format. 公共类NumberFormatException扩展IllegalArgumentException被抛出以指示应用程序已尝试将字符串转换为数字类型之一,但是该字符串没有适当的格式。

you used only NumberFormatException in the catch block so it only catch the NumberFormatException . 您只在catch块中使用了NumberFormatException ,因此它仅捕获了NumberFormatException To catch other exception you have to add other catch block 要捕获其他异常,您必须添加其他捕获块

catch (NumberFormatException e){
         System.out.println("-----> Please try entering a valid number(s) <-----");
catch (InputMismatchException e){
         System.out.println("-----> Please try entering a valid number(s) <-----");

OR if you used base Exception class it will catch any kind of Exception 或者,如果您使用了基本Exception类,它将捕获任何类型的Exception

catch (Exception e){
         System.out.println("-----> Please try entering a valid number(s) <-----");

InputMismatchException and NumberFormatException are different classes. InputMismatchExceptionNumberFormatException是不同的类。 there is no relationship between them,your program throws InputMismatchException and you are trying to catch NumberFormatException . 它们之间没有关系,您的程序将引发InputMismatchException并且您尝试捕获NumberFormatException You will need one more catch block for InputMismatchException exception. 对于InputMismatchException异常,您将需要一个catch块。

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

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