2016-02-13 134 views
1

晚上好,我有使用Scanner 這是有問題的代碼一些問題:掃描儀調試運行

public static void main(String[] args) { 
     System.out.println("Chose 1 or 2 = "); 
     Scanner scan = new Scanner(System.in); 
     byte a = scan.nextByte(); 
     scan.close(); 
     if (a==1) HW(); 
     else if (a==2) { 
      System.out.print("Calculation program ... !\nInput Number 1st number = "); 
      Scanner Catch = new Scanner(System.in); 
      int x = Catch.nextInt(); 
      System.out.println(""); 
      System.out.print("Input Operand +,-,*,/ = "); 
      Scanner Catchc = new Scanner (System.in); 
      char z = Catchc.next().charAt(0); 
      System.out.println(""); 
      System.out.print("Input 2nd number = "); 
      Scanner Catch2 = new Scanner (System.in); 
      int y = Catch2.nextInt(); 
      Catch.close(); 
      Catchc.close(); 
      Catch2.close(); 
     calc(x,y,z); 
     } 
     else System.out.println("Please input number 1 or 2 "); 
    } 
} 

那是一個簡單的計算器和我沒有錯誤,程序並沒有終止,但是它做調試代替。它顯示 「沒有這樣的元素例外」

Calc的方法:

public static void calc(int x, int y, char z) { 
    int result; 
    result = 0; 
    switch (z) { 
    case '+': result = x + y; 
    case '-': result = x - y; 
    case '/': result = x/y; 
    case '*': result = x * y; 
    } 
    System.out.println("Result of " + x + " " + z + " " + y + " is..." + " " + result); 
} 

我是初學者,請幫我傢伙(:

在此先感謝^^

回答

0

Scanner工作s,你應該只創建1,並且永遠不要關閉它們,直到你的程序完成爲止,這是因爲關閉掃描器會關閉傳入的InputStream,這個輸入流是你的程序的輸入,所以你的程序不能再接收inpu t在那之後。

重寫代碼僅創建1臺掃描儀,並通過向其他功能:

public static void main(String[] args) { // TODO Auto-generated method stub 
    System.out.println("Chose 1 or 2 = "); 
    Scanner scan = new Scanner(System.in); 
    byte a = scan.nextByte(); 
    if (a==1) 
     HW(); 
    else if (a==2) { 
     System.out.print("Calculation program ... !\nInput Number 1st number = "); 
     int x = scan.nextInt(); 
     System.out.println(""); 
     System.out.print("Input Operand +,-,*,/ = "); 
     char z = scan.next().charAt(0); 
     System.out.println(""); 
     System.out.print("Input 2nd number = "); 
     int y = scan.nextInt(); 
     calc(x,y,z); 
    } 
    else 
     System.out.println("Please input number 1 or 2 "); 
} 
+0

這是有幫助的,謝謝@Ferrybig – Bill