2012年10月31日 星期三

透過鍵盤輸入做運算

1.BufferedReader 輸入

import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Test{

    public static void main(String[] args)throws IOException{
  
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));


//這邊讓畫面顯示出輸入第幾個數字,方便識別
        System.out.println("請輸入第一個數");
        String str1 = br.readLine();
        System.out.println("請輸入第二個數");
        String str2 = br.readLine();

//將輸入的數值轉換成int值
        int num1 = Integer.parseInt(str1);
        int num2 = Integer.parseInt(str2);
        int sum = num1+num2;


        System.out.println("第一個數是" + num1);
        System.out.println("第二個數是" + num2);
        System.out.println("兩者相加是" + sum);
  
    }

}
由於變數宣告都是統一寫在一起,因此一旦輸入非數字,在最後運算結果的時候就會跳出錯誤的訊息
但是如果寫成如下:
        String str1 = br.readLine();
        System.out.println("請輸入第二個數");
         int num1 = Integer.parseInt(str1);
 便會在一開始輸入值就產生錯誤

2.Scanner 輸入

import java.util.Scanner;

public class Test{

    public static void main(String[] args){
 

        System.out.println("請輸入第一個數");
        Scanner a = new Scanner(System.in);
//這邊用int宣告可以確保輸入一定是數字
        int x =a.nextInt();

      
        System.out.println("請輸入第二個數");
        Scanner b = new Scanner(System.in);
        int y = b.nextInt();

        int sum = x + y;
        System.out.println("第一個數是"+x);

        System.out.println("第二個數是"+y);

        System.out.println("總和是"+sum);
 


    }

}
一旦輸入非數字,在第一個值就會跳出錯誤訊息

沒有留言:

張貼留言