1.变量

变量的三要素

类型、变量名、保存的值

基本数据类型
  1. 数值
  • 整数:byte、short、int、long
    (byte范围小)
  • 小数:float、double
  1. 字符串
  • 字符串:String
    (eg:"您好")
  • 字符:char
    (eg:'a'、'好')
  1. 布尔值
  • boolean
强制转换
  • (类型名)表达式
int b =(int)9.9;
自动转换
  • 如果变量为double型,则整个表达式都可以提升为double型
  • 满足自动类型转换的条件
    (1)数值类型(整型和浮点型)互相兼容
    (2)目标类型大于源类型
    eg:double 型大于 int 型

定义变量名

  1. 定义一个变量,给变量赋值
  • 数据类型 变量名=数值;
int price=2500;
  1. 使用这个变量
System.out.println(price);

获取用户输入

public class scanner {
    public static void main(String[] args) {
        // 创建对象
        Scanner scanner= new Scanner(System.in);
        // 获取数据
        System.out.println("请输入您的年龄");
        int age=scanner.nextInt();
        System.out.println("您的年龄是"+age);
        String name=scanner.next();
        System.out.println("欢迎您"+name);
        }
    }
  • 区别
        int age=scanner.nextInt();
        String name=scanner.next();

练习题

  • 商场推出幸运抽奖活动抽奖规则: 顾客的四位会员卡号的3569 各位数字之和大于20,则为幸运顾客。
public class scanner {
    public static void main(String[] args) { 
       Scanner scanner =new Scanner(System.in);
       System.out.println("请输入4位会员卡号");
       int card = scanner.nextInt();
       int gewei = card % 10;
       int shiwei = (card / 10) % 10;
       int baiwei =(card / 100) % 10;
       int qianwei =card /1000;
       int total = gewei + shiwei + baiwei + qianwei;
       System.out.println("会员卡号" + card + "各位之和是" + total);
       boolean isLucky =total > 20;
       System.out.println("是幸运用户吗" + isLucky);
   }
}
  • 请输入一个三位数,各位的三次方之和等于本身,是水仙花数吗
public class scanner {
    public static void main(String[] args) { 
       Scanner scanner = new Scanner(System.in);
       System.out.println("请输入一个三位数");
       int t = scanner.nextInt();
       int gewei = t % 10;
       int shiwei = (t / 10) % 10;
       int baiwei = t / 100;
       double total = Math.pow(gewei,3) + Math.pow(shiwei,3) +  Math.pow(baiwei,3);
       System.out.println("三位数" + t + "各位立方之和是" + total);
       boolean iss = t == total;
       System.out.println("是水仙花数吗" + iss);
   }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容