我在java中的catch块有点困难。帮助将不胜感激。
do {
System.out.println ("If you want to exit the program, press 0. To continue, press 1.");
try {
returnint = Input.nextInt();
} catch (Exception e) {
returnint=12;
return; //after this code executes, I CANNOT RE-ENTER A NUMBER
} finally {
if (!(returnint==1 || returnint==0)) {
System.out.println ("Invalid response. Please retry.");
} continue;
} while (returnint!=1 && returnint!=0);
所以问题是由于某种原因,循环不会重复。对此有任何帮助,包括更好地理解 try-catch-finally 块,将不胜感激。
编辑:程序开始时还有一个 try 块,在程序返回那里后,它也会以某种方式触发它。这里有什么帮助吗?
编辑2:下面的完整代码。
import java.util.Scanner;
public class PrimeNumberChecker {
/**
* @param args
*/
public static void main(String[] args) {
int returnint=1;
boolean isprime=true;
Scanner Input = new Scanner(System.in); //creates scanner
do{
long prime,root,primediv,i;
try {
System.out.println("Please input a number to be checked"); //prompts user for input
prime = Input.nextLong();//detects and stores next int input
}catch(Exception exc){
System.out.println("The following exception has been thrown: "+exc+" Program aborted.");
returnint=0;
return;
}
root=(long) Math.sqrt(prime); //takes the int sqrt of the input number
for(i=2;(i<=root&&isprime==true);i++){ //for loop to check for prime factors
if (prime%i==0) { //if a number divides into the number exactly, this returns true
isprime=false; //and so this returns false
}
}
if (isprime==false) {
primediv=prime;
System.out.println("The number is not prime.");
System.out.println("The factors of the number are: ");
for(i=2;primediv>1;i++) { //this is a loop to factorise the number if it is NOT prime
if (primediv%i==0) { //if it finds a factor, it prints it and checks if the factor appears twice
primediv=primediv/i;
System.out.println(i);
i--;
}
}
} else {
System.out.print(prime); //the output if the number is prime
System.out.println(" is a prime number");
}
try {
do {
System.out.println ("If you want to exit the program, press 0. To continue, press 1.");
if (!(returnint==1 || returnint==0)) {
System.out.println ("Invalid response. Please retry.");
}
returnint = Input.nextInt();
continue;
} while (returnint!=1 && returnint!=0);
} catch (Exception e) {
System.out.println("ERROR: " + e.getMessage());
throw e;
} finally {
System.out.println("Exit. Return value was set to " + returnint);
}
}while (returnint==1);
}
}