Java對象簡單實用(計算機案例)

來源:互聯網
上載者:User

標籤:個數   接受   實用   next   png   操作   count   util   stat   

對 Java中的對象與屬性,方法的使用,簡單寫了個案例

 1 import java.util.Scanner; 2 class Calculste 3 { 4     int a; //定義兩個整數 5     int b; 6     String option; //定義接收操作符的字串 7     public void count(){ 8  9         //對操作符進行判斷10         switch(option){11             case "+":12                 System.out.println("計算和:"+a+"+"+b+"="+(a+b));13             break;14 15             case "-":16                 System.out.println("計算差:"+a+"-"+b+"="+(a-b));17             break;18 19             case "*":20                 System.out.println("計算積:"+a+"*"+b+"="+(a*b));21             break;22 23             case "/":24             {25                 //作除法運算時,分母不能為 0 26                 if (b != 0)27                 {28                     System.out.println("計算商:"+a+"/"+b+"="+(a/b));29                 }else{30                     System.out.println("您輸入的第二個數不能為 0,請重新輸入");31                 }32             }    33             break;34 35             case "%":36                 System.out.println("計算餘:"+a+"%"+b+"="+(a%b));37             break;38 39             default:40                 System.out.println("您輸入的操作符有誤,請重新輸入");41         }42         43     } 44 }45 class demo3 46 {47     //需求: 使用java類描述一個計算機類,計算機具備運算元1, 運算元2 、操作符三個公用 的屬性,還具備計算的功能行為。48     public static void main(String[] args) 49     {50         System.out.println("兩個數的運算");51         Scanner sca = new Scanner(System.in);52 53         //建立類的對象54         Calculste cal = new Calculste();55 56         //給屬性賦值57         System.out.println("第一個數:");58         cal.a = (int)sca.nextInt();59 60         System.out.println("第二個數:");61         cal.b = (int)sca.nextInt();62 63         System.out.println("輸入運算子號:");64         cal.option = sca.next(); //接受字元的方法65         66         //調用方法運算67         cal.count();68     }69 }

 

這裡是在控制台的一些效果:

 

 

 

 

陌陌說:java語言是物件導向的程式設計語言,類,類中的對象,對象的屬性和方法 都是相當重要的

Java對象簡單實用(計算機案例)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.