2017-02-28 127 views
0

我已经给了一个任务来进行一些从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."); 
     } 
    } 
} 
+2

更换'系统。 out.println(e1);''和'System.out.println(e2);'用你的自定义信息。 –

+0

@ScaryWombat就是这样!谢谢! – adhamncheese

回答

0

或者改为@可怕的建议,你可以在构造函数的自定义异常添加为 -

NegativeNumberException(String str) { 
    System.out.println(str); 
} 

这将帮助您打印的消息,当您

throw new NegativeNumberException ("A n...."); 
+1

是的,我不喜欢我的建议 –