异常处理只接受双输入。因此,当用户输入“k”时,它会显示“错误!请输入一个数字!”。但是,它不是允许用户重新输入输入,而是跳转到下一个输入“平均脉冲”。如何使其工作以使其保持在同一行并允许重新输入值?
//主要课程
public class Main { //Master class
public static void main( String args[] ) //Standard header for main method
{
kbentry input = new kbentry(); //Creates object of kbentry class
System.out.print("\nPlease enter a number for Total Impulse: " ); //Print message to enter 1. input
double totalImpulse = input.totalImpulse1(); //Holds the variable entered
System.out.println("You have entered : " + totalImpulse); //Shows the variable entered
System.out.print("\nPlease enter a number for Average Impulse: " ); //Print message to enter 2. input
double averageImpulse = input.averageImpulse2(); //Holds the variable entered
System.out.println("You have entered : " + averageImpulse); //Shows the variable entered
}
}
// kbentry class
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class kbentry{ //Class name
double totalImpulse1(){ //Method for 1. input
BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); //Creates BufferedReader object for System.in
//Total Impulse entry
String strTotalImpulse = null; // These must be initialised
double intTotalImpulse = 0; //Setting it double
try {
strTotalImpulse = in.readLine(); //Reads string value from the keyboard
}
catch (IOException ioe) { // ignore exception
}
try {
intTotalImpulse = Double.parseDouble(strTotalImpulse); // convert it to double
}
catch (NumberFormatException nfe) {
System.out.println("Error! Please enter a number!" + nfe.toString()); //Error message if its not a double
}
return intTotalImpulse; //return value
}
double averageImpulse2(){ //Method for 2. input
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));//Creates BufferedReader object for System.in
// String for AverageImpulse
String strAverageImpulse = null; // These must be initialised
double intAverageImpulse = 0; //Setting it double
try {
strAverageImpulse = in.readLine(); //Reads string value from the keyboard
}
catch (IOException ioe) { // ignore exception
}
// convert it to integer
try {
intAverageImpulse = Double.parseDouble(strAverageImpulse); // convert it to double
}
catch (NumberFormatException nfe) {
System.out.println("Error! Please enter a number!" + nfe.toString()); //Error message if its not a double
}
return intAverageImpulse; //return value
}
}
答案 0 :(得分:2)
如果用户输入的不是double,那么你将获得NumberFormatException,因为你必须再次在你身上调用该方法
catch (NumberFormatException nfe) {
System.out.println("Error! Please enter a number!" + nfe.toString()); //Error message if its not a double
//again ask for input
System.out.print("\nPlease enter a number for Total Impulse: ");
return totalImpulse1();
}