JAVA 基礎 / 第十五課:操作符 / JAVA的所有操作符4

來源:互聯網
上載者:User

標籤:第一個   scan   imp   結果   system.in   span   連續   bubuko   gpo   

2018-03-07

1.賦值操作

賦值操作的操作順序是從右至左: int i = 5+5; 
首先進行5+5的運算,得到結果10,然後把10這個值,賦給i

public class HelloWorld {    public static void main(String[] args) {        int i = 5+5;    }}
2.對本身進行運算,並賦值

+=即自加:i+=2;   等同於:i=i+2; 
其他的 -= , *= , /= , %= , &= , |= , ^= , >= , >>>= 都是類似,不做贅述

public class HelloWorld {    public static void main(String[] args) {        int i =3;        i+=2;        System.out.println(i);                 int j=3;        j=j+2;        System.out.println(j);          }}

二、使用SCANNER讀取整數

截至目前為止,學習了使用System.out.println("") 向控制台輸出資料。 
在接下來的練習中,需要用到從控制台輸入資料,所以需要用到Scanner類

1.使用Scanner讀取整數

注意: 使用Scanner類,需要在最前面加上,表示匯入這個類,才能夠正常使用:

import java.util.Scanner;

import java.util.Scanner; public class HelloWorld {    public static void main(String[] args) {        Scanner s = new Scanner(System.in);        int a = s.nextInt();        System.out.println("第一個整數:"+a);        int b = s.nextInt();        System.out.println("第二個整數:"+b);    }}
2.使用Scanner讀取浮點數

import java.util.Scanner;  public class HelloWorld {    public static void main(String[] args) {        Scanner s = new Scanner(System.in);        float a = s.nextFloat();        System.out.println("讀取的浮點數的值是:"+a);     }}
3.使用Scanner讀取字串

import java.util.Scanner;  public class HelloWorld {    public static void main(String[] args) {        Scanner s = new Scanner(System.in);        String a = s.nextLine();        System.out.println("讀取的字串是:"+a);    }}
4.讀取了整數後,接著讀取字串

需要注意的是,如果在通過nextInt()讀取了整數後,再接著讀取字串,讀出來的是斷行符號換行:"\r\n",因為nextInt僅僅讀取數字資訊,而不會讀走斷行符號換行"\r\n".

所以,如果在業務上需要讀取了整數後,接著讀取字串,那麼就應該連續執行兩次nextLine(),第一次是取走整數,第二次才是讀取真正的字串

import java.util.Scanner;   public class HelloWorld {    public static void main(String[] args) {        Scanner s = new Scanner(System.in);        int i = s.nextInt();        System.out.println("讀取的整數是"+ i);        String rn = s.nextLine();        String a = s.nextLine();        System.out.println("讀取的字串是:"+a);    }}

 

JAVA 基礎 / 第十五課:操作符 / JAVA的所有操作符4

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.