JAVA零基础学习2(算术逻辑三元运算符、原码反码补码、标准的类如何描写)

news2024/9/22 4:15:33

JAVA零基础学习2(算术逻辑三元运算符、原码反码补码、标准的类如何描写)

  • 算术运算符
      • 算术运算符
      • 自增和自减运算符
      • 算术运算符的优先级
      • 示例代码
  • 逻辑运算符
  • 三元运算符
      • 示例代码
        • 示例1:简单的条件判断
        • 示例2:嵌套的三元运算符
  • 原码反码补码
  • foreach
  • switch简化
  • 二维数组
  • 类和对象
  • 标准的类的写法步骤
  • Java小试一试小游戏

算术运算符

在Java中,算术运算符用于执行基本的数学运算。以下是Java中常见的算术运算符及其用法:

算术运算符

  1. 加法运算符(+)
    • 用于两个操作数的加法。
    • 也可以用于字符串的连接。
    int a = 10;
    int b = 20;
    int sum = a + b; // 30
    
    String firstName = "John";
    String lastName = "Doe";
    String fullName = firstName + " " + lastName; // John Doe
    

数字进行运算时,数据类型不一样不能运算,需要转成- -样的,才能运算。

类型转换:
隐式转换:
1、取值范围小的,和取值范围大的进行运算,小的会先提升为大的,再进行运算。整数和小数取值范围大小关系:
double > float > long > int > short > byte

2、byte short char三种类型的数据在运算的时候,都会直接先提升为int,然后再进行运算。
强制转换:
当从较大范围的数据类型转换为较小范围的数据类型时,需要使用强制类型转换。这可能会导致精度丢失或溢出。

// 浮点数转换为整数
        double myDouble = 9.78;
        int myInt = (int) myDouble; // 强制类型转换

当“+”操作中出现字符串时,这个“+”是字符串连接符,而不是算术运算符了。会将前后的数据进行拼接,并产生一个新的字符串。

连续进行" + "操作时,从左到右逐个执行。
1 +99+ "年"加在一起的结果是“100年”

int age = 18;
System. out. print1n("我的年龄是"+ age + "岁"); //"我的年龄是18岁"
System. out . println("我的年龄是" + "age"+"岁"); //"我的年龄是age岁"
System. out. println(1 +2+"abc"+ 2 + 1);//"3abc21"

  1. 减法运算符(-)

    • 用于两个操作数的减法。
    int a = 20;
    int b = 10;
    int difference = a - b; // 10
    
  2. 乘法运算符(*)

    • 用于两个操作数的乘法。
    int a = 10;
    int b = 20;
    int product = a * b; // 200
    
  3. 除法运算符(/)

    • 用于两个操作数的除法。
    • 整数除法会舍弃小数部分。
    int a = 20;
    int b = 10;
    int quotient = a / b; // 2
    
    double x = 20.0;
    double y = 3.0;
    double result = x / y; // 6.666...
    
  4. 取模运算符(%)

    • 用于求两个操作数的余数。
    int a = 20;
    int b = 3;
    int remainder = a % b; // 2
    

自增和自减运算符

  1. 自增运算符(++)

    • 将操作数的值加1。
    • 前缀自增(++a)先加1后使用。
    • 后缀自增(a++)先使用后加1。
    int a = 10;
    int b = ++a; // a变为11,b为11
    int c = a++; // a变为12,c为11
    
  2. 自减运算符(–)

    • 将操作数的值减1。
    • 前缀自减(--a)先减1后使用。
    • 后缀自减(a--)先使用后减1。
    int a = 10;
    int b = --a; // a变为9,b为9
    int c = a--; // a变为8,c为9
    

算术运算符的优先级

算术运算符在表达式中的优先级按照以下顺序排列(从高到低):

  1. ++(前缀),--(前缀)
  2. */%
  3. +-
  4. ++(后缀),--(后缀)

括号 () 可以用来改变运算的优先级。

示例代码

public class ArithmeticOperators {
    public static void main(String[] args) {
        int a = 10;
        int b = 3;

        // 加法
        int sum = a + b;
        System.out.println("Sum: " + sum); // 13

        // 减法
        int difference = a - b;
        System.out.println("Difference: " + difference); // 7

        // 乘法
        int product = a * b;
        System.out.println("Product: " + product); // 30

        // 除法
        int quotient = a / b;
        System.out.println("Quotient: " + quotient); // 3

        // 取模
        int remainder = a % b;
        System.out.println("Remainder: " + remainder); // 1

        // 自增和自减
        int x = 5;
        System.out.println("Initial x: " + x); // 5
        System.out.println("x++: " + x++); // 5
        System.out.println("After x++: " + x); // 6
        System.out.println("++x: " + ++x); // 7
        System.out.println("x--: " + x--); // 7
        System.out.println("After x--: " + x); // 6
        System.out.println("--x: " + --x); // 5
    }
}

通过这些示例,你可以了解Java中算术运算符的基本用法及其操作。掌握这些运算符是编写有效Java代码的基础。

逻辑运算符

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

三元运算符

在Java中,三元运算符(也称为条件运算符)是一种简洁的方式来处理简单的条件语句。它的语法如下:

result = condition ? value1 : value2;

这里:

  • condition 是一个布尔表达式。
  • 如果 conditiontrue,则 resultvalue1 的值。
  • 如果 conditionfalse,则 resultvalue2 的值。

示例代码

以下是使用三元运算符的示例代码:

示例1:简单的条件判断
public class TernaryOperatorExample {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;

        // 使用三元运算符判断较大值
        int max = (a > b) ? a : b;
        System.out.println("The maximum value is: " + max);
    }
}

在这个例子中,a > b 是条件。如果条件为 truemax 将被赋值为 a;否则,max 将被赋值为 b

示例2:嵌套的三元运算符

你也可以嵌套使用三元运算符来处理多个条件:

public class NestedTernaryOperator {
    public static void main(String[] args) {
        int a = 5;
        int b = 10;
        int c = 15;

        // 使用嵌套的三元运算符找出最大值
        int max = (a > b) ? (a > c ? a : c) : (b > c ? b : c);
        System.out.println("The maximum value is: " + max);
    }
}

在这个例子中,我们嵌套了三元运算符来比较三个值 abc

原码反码补码

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
隐式转换(一般小转大):前面补零

强制转换(一般大转小):前面去掉零

在这里插入图片描述

在这里插入图片描述

foreach

在Java中,foreach 循环(增强型 for 循环)是一种简洁的方法,用于遍历数组或集合。它简化了传统的 for 循环,并且不需要使用索引变量。以下是一些示例,展示了如何使用 foreach 循环遍历数组和集合。

遍历数组
示例代码

public class ForEachExample {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};

        // 使用 foreach 循环遍历数组
        for (int number : numbers) {
            System.out.println(number);
        }
    }
}

在这个示例中,number 是数组 numbers 中的每一个元素。在每次循环迭代中,number 都被赋值为数组中的下一个元素。
在这里插入图片描述
在这里插入图片描述

switch简化

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

二维数组

在这里插入图片描述
在这里插入图片描述
二维数组遍历
在这里插入图片描述
arr3.length是行数
arr3[1].length是每一行的列数。

类和对象

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
封装
在这里插入图片描述
private
在这里插入图片描述
在这里插入图片描述
变量前面+this 就是成员位置的name;如果不加一般遵循就近原则。
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

标准的类的写法步骤

分为四步:
1、属性。
2、空参,可以用快捷键alt+inset。
3、带有全部参数的构造,可以用快捷键alt+inset。
4、get和set方法,一般对private的属性进行,可以用快捷键alt+inset。

package com.heima.demo1;

public class text1 {
    //1、属性
    private String username ;//e
    private  String password;
    private  String email;
    private  String gender;
    private int age;
   //2、空参,可以用快捷键alt+inset
    public text1(){};
    //3、带哟全部参数的构造,可以用快捷键alt+inset
    public text1(String username,String password,String email,String gender,int age){};
    //记得做赋值
    this.username=username;
    this.password=password;
    this.email=email;
    this.gender=gender;
    this.age=age;
    //4、get和set方法,一般对private的属性进行,可以用快捷键alt+inset
    
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

在这里插入图片描述

Java小试一试小游戏

奥特曼打小怪兽
需要有两个class 一个是role.java 另一个是play1.java
play1.java 内容

package palyStart;
import java.util.Random;

public class paly1 {
    public static void main(String[] args) {
        role role1=new role("奥特曼",30,'女');
        role role2=new role("怪兽",30,'男');
        role1.showRoleInfo();
        role2.showRoleInfo();
        while (true)
        {
            role1.attack(role2);
            if(role2.getBlood()==0)
            {
                System.out.println(role2.getUsername()+"已经被KO!");
                break;
            }
            role2.attack(role1);
            if(role1.getBlood()==0)
            {
                System.out.println(role1.getUsername()+"已经被KO!");
                break;
            }
        }
    }
}

role.java 中的内容

package palyStart;
import java.util.Random;
public class role {

        private String username;
        private int blood;
        private char gender;
        private String face;//长相随机
    String[] boyfaces= {"风流俊雅","气字轩昂","相貌英俊","五官端正","相貌平平"," -塌糊涂","面目狰狞"};
    String[] girlfaces ={"美奂绝伦","沉鱼落雁","婷婷玉立","身材娇好","相貌平平","相貌简陋","惨不忍睹"};

    public role() {
    }

    public role(String username, int blood,char gender) {
        this.username = username;
        this.blood = blood;
        this.gender=gender;
        setFace(gender);
    }
    public char getGender() {
        return gender;
    }

    public void setGender(char gender) {
        this.gender = gender;
    }

    public String getFace() {
        return face;
    }

    public void setFace(char gender) {
        if(gender=='男')
        {
            Random r=new Random();
            int index=r.nextInt(boyfaces.length);
            this.face=boyfaces[index];
        } else if (gender=='女') {
            Random r=new Random();
            int index=r.nextInt(girlfaces.length);
            this.face=girlfaces[index];
        }
        else{
            this.face="怪物";
        }
    }

        /**
         * 获取
         * @return username
         */
        public String getUsername() {
            return username;
        }

        /**
         * 设置
         * @param username
         */
        public void setUsername(String username) {
            this.username = username;
        }

        /**
         * 获取
         * @return blood
         */
        public int getBlood() {
            return blood;
        }

        /**
         * 设置
         * @param blood
         */
        public void setBlood(int blood) {
            this.blood = blood;
        }
        public void attack(role role)
        {
            //输出一个攻击的效果
            String[] attacks_desc={
                    "%s使出了一招[背心钉],转到对方的身后,一掌向%s背心的灵台穴拍去。",
                    "%s使出了一招[游空探爪],飞起身形 自半空中变掌为抓锁向%s。",
                    "%s大喝一声,身形下伏,一招[劈雷坠地],捶向%s双腿。",
                    "%s运气于掌, -瞬间掌心变得血红,一式[掌心雷],推向%s。",
                    "%s阴手翻起阳手跟进,一招[没遮拦] ,结结实实的捶向%s。",
                    "%s.上步抢身,招中套招,-招[劈挂连环] ,连环攻向%s"};
            Random r=new Random();
            int index=r.nextInt(attacks_desc.length);
            String KungFu=attacks_desc[index];
            System.out.printf(KungFu,this.getUsername(),role.getUsername());
            System.out.println();

            //随机造成1-20的伤害
            int hurt=r.nextInt(20)+1;
            //剩余血量
            int remainblood= role.getBlood()-hurt;
            if(remainblood<0)
            {
                remainblood=0;
            }
            role.setBlood(remainblood);
            //受伤的描述
            //    injured受伤描述:
            String[] injureds_desc={
                "结果%s退了半步,毫发无损",
                "结果给%s造成一处瘀伤",
                "结果一击命中,%s痛得弯下腰",
                "结果%s痛苦地闷哼了一声,显然受了点内伤",
                "结果%s摇摇晃晃,跤摔倒在地",
                "结果%s脸色一下变得惨白,连退了好几步",
                "结果「轰」的一声, %s口中鲜血狂喷而出",
            "结果%s-声惨叫,像滩软泥般塌了下去"};
            if(remainblood>=90)
            {
                System.out.printf(injureds_desc[0],role.getUsername());
            } else if (remainblood>=80&&remainblood<90) {
                System.out.printf(injureds_desc[1],role.getUsername());
            } else if (remainblood>=70&&remainblood<80) {
                System.out.printf(injureds_desc[2],role.getUsername());
            } else if (remainblood>=60&&remainblood<70) {
                System.out.printf(injureds_desc[3],role.getUsername());
            } else if (remainblood>=40&&remainblood<60) {
                System.out.printf(injureds_desc[4],role.getUsername());
            } else if (remainblood>=20&&remainblood<40) {
                System.out.printf(injureds_desc[5],role.getUsername());
            }else if(remainblood>10&&remainblood<20)
            {
                System.out.printf(injureds_desc[6],role.getUsername());
            }else {
                System.out.printf(injureds_desc[7],role.getUsername());
            }
            System.out.println();

//            //this 表示动作方法的调用者
//            System.out.println(this.getUsername()+"打了"+role.getUsername()+",造成了"+hurt+"的伤害,"+role.getUsername()+"还剩下"+role.getBlood()+"血量");
        }

    public void showRoleInfo() {
        System.out.println("姓名为:"+getUsername());
                System.out.println("血量为:"+getBlood());
                        System.out.println("性别为:"+ getGender());
                                System.out.println("长相为:"+ getFace());
    }
}

运行结果:
在这里插入图片描述
end,继续加油哦!!!!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1940124.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

WebGSI地图切片|栅格地图切片原理|地图矢量切片原理

介绍 图栅格切片是WebGIS中使用的一种新技术&#xff0c;通过地图栅格切片可以有效缩短服务器的地图生成时间和地图传输时间&#xff0c;提高系统的响应速度。 地图切片是在多个比例尺下配置地图&#xff0c;预先将每个比例尺下的地图绘制成小图片&#xff0c;保存到服务器上一…

set(集合),multiset容器及pair队组的创建

1.set的基本概念&#xff1a;所有元素再插入时自动按升序排序&#xff0c;set/multiset属于关联式容器&#xff0c;底层结构是用二叉树实现的 set与multiset区别&#xff1a; set中不允许容器中有重复的元素 multiset允许容器中有重复的元素 2.set的构造函数 3.set的大小和…

【Linux】进程间通信之-- 共享内存与信号量的介绍(下)

前言 上一篇&#xff0c;我们由进程间通信&#xff0c;引入并讲述了管道、匿名管道和命名管道&#xff0c;本节&#xff0c;将继续学习进程间通信的另一种方式之&#xff0c;共享内存。还要学习几个系统调用接口&#xff0c;并演示两个进程通过共享内存来进行通信。。。 目录 1…

数据结构——队列(链式结构)

一、队列链式结构定义 队列的链式存储结构是一种用链表实现的队列,它不像顺序存储结构那样需要预先分配固定大小的空间。链式存储结构的队列由节点组成,每个节点包括数据和指向下一个节点的指针。队列的链式存储结构可以动态地分配内存,更灵活地处理数据。在链式存储结构中…

【07】LLaMA-Factory微调大模型——微调模型导出与微调参数分析

上文介绍了如何对微调后的模型进行使用与简单评估。本文将介绍对微调后的模型进行导出的过程。 一、llama-3微调后的模型导出 首先进入虚拟环境&#xff0c;打开LLaMA-Factory的webui页面 conda activate GLM cd LLaMA-Factory llamafactory-cli webui 之后&#xff0c;选择…

SQL39道常见题型

SQL1 查询所有列 现在运营想要查看用户信息表中所有的数据&#xff0c;请你取出相应结果。 select * from user_profile 结果&#xff1a; SQL2 查询多列 还是上面那个输入&#xff0c;题目换成&#xff1a;现在运营同学想要用户的设备id对应的性别、年龄和学校的数据&#…

TIM基本定时器

TIM基本定时器 文章目录 TIM基本定时器1.定时器的分类2.定时器运行流程3.基本定时器的配置流程4.中断配置 1.定时器的分类 以STM32F1系列为例&#xff0c;它的定时器可以根据其特性和功能被分为三大类&#xff1a; 基本定时器&#xff1a; 包括&#xff1a;TIM6和TIM7。特点&a…

数据结构全部知识-----第一 关于数据结构的介绍

数据结构是计算机存储、组织数据的方式。它是计算机科学中的一个重要概念&#xff0c;主要目的是使数据的存储和访问更高效、更方便。常见的数据结构包括&#xff1a; 线性结构&#xff1a; 1. **数组&#xff08;Array&#xff09;** &#xff1a;一种基础的数据结构&#xf…

【BUG】已解决:AttributeError: ‘WindowsPath‘ object has no attribute ‘rstrip‘

AttributeError: ‘WindowsPath‘ object has no attribute ‘rstrip‘ 目录 AttributeError: ‘WindowsPath‘ object has no attribute ‘rstrip‘ 【常见模块错误】 【错误原因】 【解决方案】 欢迎来到英杰社区https://bbs.csdn.net/topics/617804998 欢迎来到我的主页&…

C++中的多路转接技术之epoll

epoll 是干什么的&#xff1f;举个简单的例子 epoll的相关系统调用**epoll_create**和epoll_create1区别 epoll_ctl参数解释 **epoll_wait**参数说明返回值 epoll的使用 **epoll**工作原理epoll的优点(和 **select** 的缺点对应)epoll工作方式**水平触发**Level Triggered 工作…

针对汽车应用而设计的SCT4026D、SCT4062K、SCT3105K、SCT3080A、SCT3060A全新系列碳化硅 (SiC) MOSFET

全新系列碳化硅 (SiC) MOSFET SCT4026DWAHRTL SCT4062KWAHRTL SCT3105KRC15 SCT3080ALHRC11 SCT3080ARC15 SCT3060ARC15 ——明佳达 AEC-Q101 SiC功率MOSFETs是汽车和开关电源的理想选择。SiC功率MOSFETs可以提高开关频率&#xff0c;减少所需的电容、电抗器和其他元件的体积…

react开发-配置开发时候@指向SRC目录

这里写目录标题 配置开发时候指向SRC目录VScode编辑器给出提示总体1.配置react的 2.配置Vscode的1.配置react的2,配置VSCode的提示支持 配置开发时候指向SRC目录VScode编辑器给出提示 总体1.配置react的 2.配置Vscode的 1.配置react的 1. 我么需要下载一个webpack的插件 这样…

【闲谈】我的创作纪念日(CrowdStrike、无人驾驶)

感谢地心引力 &#xff0c;有幸再次遇见你&#xff1a; 还记得 2020 年 07 月 22 日吗&#xff1f;你撰写了第 1 篇技术博客&#xff1a;《遗传算法实例解析》在这平凡的一天&#xff0c;你赋予了它不平凡的意义。也许是立志成为一名专业 IT 作者、也许是记录一段刚实践的经验。…

【iOS】——探究isKindOfClass和isMemberOfClass底层实现

isKindOfClass 判断该对象是否为传入的类或其子类的实例 // 类方法实现&#xff0c;用于检查一个类是否属于另一个类或其父类链上的任何类。(BOOL)isKindOfClass:(Class)cls {// 从当前类开始&#xff0c;tcls将沿着元类的继承链向上遍历。for (Class tcls self->ISA(); …

MySQL:库表操作

MySQL&#xff1a;库表操作 库操作查看创建字符编码集 删除修改备份 表操作创建查看删除修改 库操作 查看 查看存在哪些数据库&#xff1a; show databases;示例&#xff1a; 查看自己当前处于哪一个数据库&#xff1a; select database();示例&#xff1a; 此处由于我不处于任…

Unity UGUI 之 Input Field

本文仅作学习笔记与交流&#xff0c;不作任何商业用途 本文包括但不限于unity官方手册&#xff0c;唐老狮&#xff0c;麦扣教程知识&#xff0c;引用会标记&#xff0c;如有不足还请斧正 1.Input Field是什么&#xff1f; 给玩家提供输入的输入框 2.重要参数 中英文对照着看…

JSONNode树形解析或流式解析

哈喽&#xff0c;大家好&#xff0c;我是木头左&#xff01; 什么是JSONNode&#xff1f; JSONNode是一个用于处理JSON数据的数据结构&#xff0c;它提供了一种简单、灵活、高效的方式来操作JSON数据。JSONNode可以看作是一个树形结构&#xff0c;其中每个节点都可以包含一个值…

MongoDB自学笔记(四)

一、前文回顾 上一篇文章中我们学习了MongoDB中的更新方法&#xff0c;也学了一部分操作符。今天我们将学习最后一个操作“删除”。 二、删除 原始数据如下&#xff1a; 1、deleteOne 语法&#xff1a;db.collection.deleteOne(< query >,< options >) 具体参…

OpenCV 像素操作—证件照换底色详细原理 C++纯手写实现

文章目录 总体步骤1.RGB转HSV2.找出要换的底色3.取反&#xff0c;黑白颠倒4.将原图像的非背景部分复制到新背景上 完整代码1.C纯手写版2.官方API版本 总体步骤 1.RGB转HSV 为什么一定要转为HSV 颜色空间&#xff1f; 将图像从BGR颜色空间转换为HSV颜色空间是因为HSV颜色空间更…

vscode 文件颜色变绿色

解决&#xff1a;关闭git功能 在设置中搜索Git:Enabled&#xff0c;取消Decorations: Enabled的勾选