標籤:第一個 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