我已經給了一個任務來進行一些從ft到cm的轉換。我已經完成了大部分工作,並且轉換工作正常。我還想包括A negative number...
或A non-digit...
的聲明,當我鍵入一個字符串,例如或一個負數,顯示所述消息。Java InputMismatchException錯誤
我得到的問題是,當我輸入一個字符串或負數時,例如,當輸入時,得到輸出testProgram.NegativeNumberException
。例如testProgram.NonDigitNumberException
,當我輸入joe
時。
我在想catch
有什麼問題,但不確定它在哪裏不會點擊。
package testProgram;
import java.util.InputMismatchException;
import java.util.Scanner;
public class conversion{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
double cm = -1;
while(cm == -1){
cm = convertToCentimeters(scan);
if(cm!=-1){
System.out.println("Your result = " +cm);
}
else{
System.out.println("Please enter the values again.");
}
scan.nextLine();
}
}
public static double convertToCentimeters(Scanner scan){
double centimeters = -1;
try{
double foot = getFootValue(scan);
double inch = getInchValue(scan);
double totalInches = foot * 12 + inch;
centimeters = totalInches * 2.54;
}catch(NegativeNumberException e1){
System.out.println(e1);
}
catch(NonDigitNumberException e2){
System.out.println(e2);
}
return centimeters;
}
public static double getFootValue(Scanner scan) throws NegativeNumberException, NonDigitNumberException{
try{
System.out.println("Enter the foot value: ");
double foot = scan.nextDouble();
if(foot <= 0){
throw new NegativeNumberException ("A negative foot value has been entered.");
}
return foot;
}
catch(InputMismatchException e){
throw new NonDigitNumberException ("A non-digit foot value has been entered.");
}
}
public static double getInchValue(Scanner scan)throws NegativeNumberException, NonDigitNumberException{
try{
System.out.println("Enter the inch value: ");
double inch = scan.nextDouble();
if(inch <= 0){
throw new NegativeNumberException ("A negative inch value has been entered.");
}
return inch;
}
catch(InputMismatchException e){
throw new NonDigitNumberException ("A non-digit inch value has been entered.");
}
}
}
更換'系統。 out.println(e1);''和'System.out.println(e2);'用你的自定義信息。 –
@ScaryWombat就是這樣!謝謝! – adhamncheese