好的,所以我正在学习一个 CS 安全课程,其中包含一些基本的 java 编程,我们的第一个任务是玩BigInteger
. 但是,我们还必须对我们的程序进行“防弹”。虽然我的方法不是最理想的,但它适用于第一个输入。Aka 如果我为我的任何程序输入无效输入,input.new---();
将提示用户使用有效数字再试一次。但是第一个input.nextInt();
仍然会接受无效输入并崩溃,显示"java.util.InputMismatchException"
然后漫无目的的扫描仪。关于为什么会发生这种情况的任何想法?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) <-----");
}
}
}
}