JAVA 基础 / 第十五课:操作符 / JAVA的所有操作符4

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()读取了整数后,再接着读取字符串,读出来的是回车换行:" ",因为nextInt仅仅读取数字信息,而不会读走回车换行" ".

所以,如果在业务上需要读取了整数后,接着读取字符串,那么就应该连续执行两次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);
    }
}
原文地址:https://www.cnblogs.com/Parker-YuPeng/p/8522712.html