java 示例_最佳Java示例

 2023-09-06 阅读 31 评论 0

摘要:java 示例 什么是Java? (What is Java?) Java is a programming language developed by Sun Microsystems in 1995, which later got acquired by Oracle. It’s now a full platform with lots of standard APIs, open source APIs, tools, and a huge developer comm

java 示例

什么是Java? (What is Java?)

Java is a programming language developed by Sun Microsystems in 1995, which later got acquired by Oracle. It’s now a full platform with lots of standard APIs, open source APIs, tools, and a huge developer community.

Java是Sun Microsystems在1995年开发的一种编程语言,后来被Oracle收购。 现在,它是一个完整的平台,具有许多标准API,开源API,工具和庞大的开发人员社区。

It is used to build the most trusted enterprise solutions by big and small companies alike. Android application development is done fully with Java and its ecosystem.

大小公司都使用它来构建最受信任的企业解决方案。 Android应用程序开发完全使用Java及其生态系统完成。

To learn more about Java basics, read this and this.

要了解有关Java基础的更多信息,请阅读this和this 。

(Version)

The latest version is Java 11, which was released in 2018 with various improvements over the previous version, Java 10. But for all intents and purposes, we will use Java 8 in this wiki for all tutorials.

最新版本是Java 11 ,该版本于2018年发布,对先前版本Java 10进行了各种改进 。但是出于所有意图和目的,我们将在此Wiki中将Java 8用于所有教程。

Java is also divided into several “Editions” :

Java也分为几个“版本”:

  • SE - Standard Edition - for desktop and standalone server applications

    SE-标准版-适用于台式机和独立服务器应用程序

  • EE - Enterprise Edition - for developing and executing Java components that run embedded in a Java server

    EE-企业版-用于开发和执行运行在Java服务器中的Java组件

  • ME - Micro Edition - for developing and executing Java applications on mobile phones and embedded devices

    ME -Micro Edition-用于在手机和嵌入式设备上开发和执行Java应用程序

安装:JDK或JRE? (Installation : JDK or JRE ?)

Download the latest Java binaries from the official website. Here you may face a question, which one to download, JDK or JRE? JRE stands for Java Runtime Environment, which is the platform dependent Java Virtual Machine to run Java codes, and JDK stands for Java Development Kit, which consists of most of the development tools, most importantly the compiler javac, and also the JRE. So, for an average user JRE would be sufficient, but since we would be developing with Java, we would download the JDK.

从官方网站下载最新的Java二进制文件。 在这里,您可能会遇到一个问题,要下载的是JDK还是JRE? JRE代表Java Runtime Environment,它是运行Java代码的依赖于平台的Java虚拟机,而JDK代表Java Development Kit,它由大多数开发工具(最重要的是编译器javac )和JRE组成。 因此,对于普通用户而言,JRE就足够了,但是由于我们将使用Java进行开发,因此我们将下载JDK。

平台特定的安装说明 (Platform specific installation instructions)

视窗 (Windows)

  • Download the relevant .msi file (x86 / i586 for 32bits, x64 for 64bits)

    下载相关的.msi文件(x86 / i586为32位,x64为64位)

  • Run the .msi file. Its a self extracting executable file which will install Java in your system!

    运行.msi文件。 它是一个自解压的可执行文件,它将在您的系统中安装Java!

的Linux (Linux)

  • Download the relevant tar.gz file for your system and install :

    下载适用于您系统的tar.gz文件并安装:

bash $ tar zxvf jdk-8uversion-linux-x64.tar.gz

bash $ tar zxvf jdk-8uversion-linux-x64.tar.gz

  • RPM based Linux platforms download the relevant .rpm file and install :

    基于RPM的Linux平台下载相关的.rpm文件并安装:

bash $ rpm -ivh jdk-8uversion-linux-x64.rpm

bash $ rpm -ivh jdk-8uversion-linux-x64.rpm

  • Users have the choice to install an open source version of Java, OpenJDK or the Oracle JDK. While OpenJDK is in active development and in sync with Oracle JDK, they just differ in licensing stuff. However few developers complain of the stability of Open JDK.

    用户可以选择安装Java,OpenJDK或Oracle JDK的开源版本。 尽管OpenJDK正在进行积极的开发并与Oracle JDK同步,但是它们在许可方面有所不同。 但是,很少有开发人员抱怨Open JDK的稳定性。

有关Ubuntu的说明: (Instructions for Ubuntu :)

Open JDK installation :bash sudo apt-get install openjdk-8-jdk

打开JDK安装: bash sudo apt-get install openjdk-8-jdk

Oracle JDK installation :bash sudo add-apt-repository ppa:webupd8team/java sudo apt-get update sudo apt-get install oracle-java8-installer

Oracle JDK安装: bash sudo add-apt-repository ppa:webupd8team/java sudo apt-get update sudo apt-get install oracle-java8-installer

苹果电脑 (Mac)

  • Either download Mac OSX .dmg executable from Oracle Downloads

    从Oracle下载中心下载Mac OSX .dmg可执行文件
  • Or use Homebrew to install :

    或使用Homebrew 安装 :

brew tap caskroom/cask  
brew install brew-cask  
brew cask install java

验证安装 (Verify Installation)

Verify Java has been properly installed in your system by opening Command Prompt (Windows) / Windows Powershell / Terminal (Mac OS and *Unix) and checking the versions of Java runtime and compiler :

通过打开命令提示符(Windows)/ Windows Powershell / Terminal(Mac OS和* Unix)并检查Java运行时和编译器的版本,验证Java是否已正确安装在系统中:

$ java -version
java version "1.8.0_66"
Java(TM) SE Runtime Environment (build 1.8.0_66-b17)
Java HotSpot(TM) 64-Bit Server VM (build 25.66-b17, mixed mode)$ javac -version
javac 1.8.0_66

Tip : If you get an error such as “Command Not Found” on either java or javac or both, dont panic, its just your system PATH is not properly set. For Windows, see this StackOverflow answer or this article on how to do it. Also there are guides for Ubuntu and Mac as well. If you still can’t figure it out, dont worry, just ask us in our Gitter room!

提示 :如果在javajavac或两者上都出现诸如“找不到命令”之类的错误,请不要恐慌,只是系统PATH设置不正确。 对于Windows,请参阅此StackOverflow答案或有关如何执行此操作的文章 。 也有针对Ubuntu和Mac的指南。 如果您仍然无法解决问题,请不要担心,只需在我们的Gitter室中问我们!

虚拟机 (JVM)

Ok now since we are done with the installations, let’s begin to understand first the nitty gritty of the Java ecosystem. Java is an interpreted and compiled language, that is the code we write gets compiled to bytecode and interpreted to run . We write the code in .java files, Java compiles them into bytecodes which are run on a Java Virtual Machine or JVM for execution. These bytecodes typically has a .class extension.

好了,既然我们已经完成了安装,那么让我们首先开始了解Java生态系统的本质。 Java是一种解释和编译语言,这就是我们编写的代码被编译为字节码并解释为运行。 我们将代码写入.java文件中,Java将它们编译为字节码 ,这些字节码在Java虚拟机或JVM上运行以执行。 这些字节码通常具有.class扩展名。

Java is a pretty secure language as it doesn’t let your program run directly on the machine. Instead, your program runs on a Virtual Machine called JVM. This Virtual Machine exposes several APIs for low level machine interactions you can make, but other than that you cannot play with machine instructions explicitely. This adds a huge bonus of security.

Java是一种非常安全的语言,因为它不允许您的程序直接在计算机上运行。 而是,您的程序在称为JVM的虚拟机上运行。 该虚拟机公开了几个API,用于您可以进行的低级机器交互,但除此之外,您不能明确地使用机器指令。 这增加了巨大的安全性。

Also, once your bytecode is compiled it can run on any Java VM. This Virtual Machine is machine dependent, i.e it has different implementations for Windows, Linux and Mac. But your program is guranteed to run in any system thanks to this VM. This philosophy is called “Write Once, Run Anywhere”.

同样,一旦编译完字节码,它就可以在任何Java VM上运行。 该虚拟机取决于计算机,即,对于Windows,Linux和Mac具有不同的实现。 但是由于有了此VM,您的程序可以在任何系统上运行。 这种理念称为“一次编写,随处运行” 。

你好,世界! (Hello World!)

Let’s write a sample Hello World application. Open any editor / IDE of choice and create a file HelloWorld.java.

让我们编写一个示例Hello World应用程序。 打开任何选择的编辑器/ IDE并创建文件HelloWorld.java

public class HelloWorld {public static void main(String[] args) {// Prints "Hello, World" to the terminal window.System.out.println("Hello, World");}}

N.B. Keep in mind in Java file name should be the exact same name of the public class in order to compile!

注意:请记住,Java文件名应与public类完全相同 ,以便进行编译!

Now open the terminal / Command Prompt. Change your current directory in the terminal / Command Prompt to the directory where your file is located. And compile the file :

现在打开终端/命令提示符。 在终端/命令提示符中将当前目录更改为文件所在的目录。 并编译文件:

$ javac HelloWorld.java

Now run the file using java command!

现在使用java命令运行文件!

$ java HelloWorld
Hello, World

Congrats! Your first Java program has run successfully. Here we are just printing a string passing it to the API System.out.println. We will cover all the concepts in the code, but you are welcome to take a closer look! If you have any doubt or need additional help, feel free to contact us anytime in our Gitter Chatroom!

恭喜! 您的第一个Java程序已成功运行。 在这里,我们只是打印一个将其传递给API System.out.println的字符串。 我们将涵盖代码中的所有概念,但是欢迎您仔细阅读 ! 如果您有任何疑问或需要其他帮助,请随时在我们的Gitter Chatroom中与我们联系!

文献资料 (Documentation)

Java is heavily documented, as it supports huge amounts of API’s. If you are using any major IDE such as Eclipse or IntelliJ IDEA, you would find the Java Documentation included within.

Java已有大量文献记录 ,因为它支持大量的API。 如果您使用的是任何主要的IDE(例如Eclipse或IntelliJ IDEA),那么您会发现其中包含Java文档。

Also, here is a list of free IDEs for Java coding:

另外,这是用于Java编码的免费IDE的列表:

  • NetBeans

    NetBeans

  • Eclipse

  • IntelliJ IDEA

    IntelliJ IDEA

  • Android Studio

    Android Studio

  • BlueJ

    蓝J

  • jEdit

    编辑

  • Oracle JDeveloper

    Oracle JDeveloper

基本操作 (Basic Operations)

Java supports the following operations on variables:

Java支持对变量执行以下操作:

  • Arithmetic : Addition (+), Subtraction (-), Multiplication (*), Division (/), Modulus (%),Increment (++),Decrement (--).

    算术Addition (+)Subtraction (-)Multiplication (*)Division (/)Modulus (%)Increment (++)Decrement (--)

  • String concatenation: + can be used for String concatenation, but subtraction - on a String is not a valid operation.

    字符串串联+可以用于字符串串联,但是减法-对字符串无效。

  • Relational: Equal to (==), Not Equal to (!=), Greater than (>), Less than (<), Greater than or equal to (>=), Less than or equal to (<=)

    关系型Equal to (==)Not Equal to (!=)Greater than (>)Less than (<)Greater than or equal to (>=)Less than or equal to (<=)

  • Bitwise: Bitwise And (&), Bitwise Or (|), Bitwise XOR (^), Bitwise Compliment (~), Left shift (<<), Right Shift (>>), Zero fill right shift (>>>)

    按位Bitwise And (&)Bitwise Or (|)Bitwise XOR (^)Bitwise Compliment (~) Zero fill right shift (>>>) Bitwise Compliment (~)Left shift (<<)Right Shift (>>)Zero fill right shift (>>>)

  • Logical: Logical And (&&), Logical Or (||), Logical Not (!)

    逻辑Logical And (&&)Logical Or (||)Logical Not (!)

  • Assignment: =, +=, -=, *=, /=, %=, <<=, >>=, &=, ^=, |=

    分配=+=-=*=/=%=<<=>>=&=^=|=

  • Others: Conditional/Ternary(?:), instanceof

    其他Conditional/Ternary(?:)instanceof

While most of the operations are self-explanatory, the Conditional (Ternary) Operator works as follows:

尽管大多数操作是不言自明的,但条件(三元)运算符的工作方式如下:

expression that results in boolean output ? return this value if true : return this value if false;

expression that results in boolean output ? return this value if true : return this value if false;

Example: True Condition:

示例:真实条件:

int x = 10;int y = (x == 10) ? 5 : 9; // y will equal 5 since the expression x == 10 evaluates to true

False Condition:

错误条件:

int x = 25;int y = (x == 10) ? 5 : 9; // y will equal 9 since the expression x == 10 evaluates to false

The instance of operator is used for type checking. It can be used to test if an object is an instance of a class, a subclass or an interface. General format- *object instance of class/subclass/interface*

运算符的实例用于类型检查。 它可用于测试对象是否是类,子类或接口的实例。 通用格式-*类/子类/接口的对象实例 *

Here is a program to illustrate instanceof operator:

这是一个说明instanceof运算符的程序:

Person obj1 = new Person();Person obj2 = new Boy();// As obj is of type person, it is not an// instance of Boy or interfaceSystem.out.println("obj1 instanceof Person: " +  (obj1 instanceof Person)); /*it returns true since obj1 is an instance of person */

可变的例子 (Variable Examples)

Variables store values. They are the most basic entity used to store data such as text, numbers, etc. in a program.

变量存储值。 它们是用于在程序中存储文本,数字等数据的最基本实体。

In Java, variables are strongly typed, which means you have to define the type for each variable whenever you declare it. Otherwise, the compiler will throw an error at compile time. Therefore, each variable has an associated ’data-type’ of one of the following:

在Java中,变量是强类型的,这意味着必须在声明每个变量时都为它定义类型。 否则,编译器将在编译时引发错误。 因此,每个变量都具有以下之一的关联“数据类型”:

Primitive Type: int, short, char, long, boolean, byte, float, double

基本类型:int,short,char,long,boolean,byte,float,double

Wrapper Type: Integer, Short, Char, Long, Boolean, Byte, Float, Double

包装类型:整数,短型,字符,长型,布尔型,字节,浮点型,双精度

Reference Type: String, StringBuilder, Calendar, ArrayList, etc.

引用类型:字符串,StringBuilder,日历,ArrayList等。

You may have noticed that the Wrapper Type consists of types spelled exactly like the Primitive Type, except for the capitalised alphabet in the begining (like the Reference Type). This is because the Wrapper Types are actually a part of the more general Reference Types, but closely linked with their primitive counterparts via autoboxing and unboxing. For now, you just need to know that such a ‘Wrapper Type’ exists.

您可能已经注意到,包装类型由拼写与原始类型完全相同的类型组成,除了开头的大写字母(如引用类型)外。 这是因为包装器类型实际上是更通用的引用类型的一部分,但通过自动装箱和拆箱与它们的原始对等类型紧密联系。 现在,您只需要知道存在这样的“包装类型”即可。

Typically, you can declare (i.e., create) variables as per the following syntax: <data-type> <variableName>;

通常,您可以按照以下语法声明(即创建)变量:<data-type> <variableName>;

// Primitive Data Type
int i;// Reference Data Type
Float myFloat;

You can assign a value to the variable either simultaneously when you are declaring it (which is called initialisation), or anywhere in the code after you have declared it. The symbol = is used for the same.

您可以在声明变量时将其赋值(称为初始化),也可以在声明后的代码中的任何位置赋值。 符号=表示相同。

// Initialise the variable of Primitive Data Type 'int' to store the value 10
int i = 10;
double amount = 10.0;
boolean isOpen = false;
char c = 'a'; // Note the single quotes//Variables can also be declared in one statement, and assigned values later.
int j;
j = 10;// initiates an Float object with value 1.0
// variable myFloat now points to the object
Float myFloat = new Float(1.0);//Bytes are one of types in Java and can be
//represented with this code
int byteValue = 0B101;
byte anotherByte = (byte)0b00100001;

As evident from the above example, variables of Primitive type behave slightly differently from variables of Reference (& Wrapper) type - while Primitive variables store the actual value, Reference variables refer to an ‘object’ containing the actual value. You can find out more in the sections linked below.

从上面的示例可以明显看出,基本类型的变量的行为与引用(&Wrapper)类型的变量略有不同-虽然基本变量存储实际值,但参考变量引用的是包含实际值的“对象”。 您可以在下面链接的各节中找到更多信息。

数组 (Array)

An Array is a collection of values (or objects) of similar datatypes (primitive and reference both form of datatypes are allowed) held in sequencial memory addresses. An Array is used to store a collection of similar data types. Arrays always start with the index of 0 and are instantiated to a set number of indexes. All the variables in the array must be of the same type, declared at instantiation.

数组是保存在顺序内存地址中的相似数据类型(允许原始类型和引用形式的两种数据类型)的值(或对象)的集合。 数组用于存储相似数据类型的集合。 数组始终以索引0开头,并实例化为一定数量的索引。 数组中的所有变量必须具有相同的类型,并在实例化时声明。

Syntax:

句法:

dataType[] arrayName;   // preferred way

Here, java datatype[] describes that all the variables stated after it will be instantiated as arrays of the specified datatype. So, if we want to instantiate more arrays of the similar datatype, we just have to add them after the specified java arrayName(Don’t forget to separate them through commas only). An example is given below in the next section for reference.

在这里, java datatype[]描述了在它之后声明的所有变量将被实例化为指定数据类型的数组。 因此,如果我们要实例化更多类似数据类型的数组,我们只需要在指定的java arrayName之后添加它们(别忘了仅通过逗号分隔它们)。 下一节给出了一个示例供参考。

dataType arrayName[];  //  works but not preferred way

Here, java datatype describes only that the variables stated after it belong to that datatype. Besides, java [] after the variable name describes that the variable is an array of the specified datatype (not just a value or object of that datatype). So, if we want to instantiate more arrays of the similar datatype, we will add the variables names just after the one already specified, separated by commas and each time we will have to add java [] after the variable name otherwise the variable will be instantiated as an ordinary value-storing variable (not an array). For better understanding an example is given in the next section.

在这里, java datatype仅描述其后声明的变量属于该数据类型。 此外,变量名后的java []描述变量是指定数据类型的数组(而不仅仅是该数据类型的值或对象)。 因此,如果我们要实例化更多类似数据类型的数组,我们将在已指定的变量名之后添加变量名,并用逗号分隔,并且每次我们都必须在变量名后添加java [] ,否则变量将是实例化为普通的值存储变量(而不是数组)。 为了更好地理解,下一节将给出一个示例。

上面语法的代码片段: (Code snippets of above syntax:)

double[] list1, list2; // preferred way

Above code snippet instantiates 2 arrays of double type names list1 and list2.

上面的代码片段实例化了两个双精度类型名称为list1和list2的数组。

double list1[], list2; // works but not preferred way

Above code snippet an array of datatype double named list1 and a simple variable of datatype double named list2 (Don’t be confused with the name list2. Variables names have nothing to do with the type of variable).

上面的代码片段是一个名为list1的数据类型为double的数组和一个名为list2的数据类型为double的简单变量(不要与名称list2混淆。变量名称与变量的类型无关)。

Note: The style double list[] is not preferred as it comes from the C/C++ language and was adopted in Java to accommodate C/C++ programmers. Additionally it’s more readable: you can read that it’s a “double array named list” other than “a double called list that is an array”

注意:不推荐使用double list[]样式,因为它来自C / C ++语言,并且在Java中被采用来容纳C / C ++程序员。 此外,它更具可读性:您可以看到它是“名为list的双数组”,而不是“作为数组的double列表”

创建数组: (Creating Arrays:)

dataType[] arrayName = new dataType[arraySize];

上面语法的代码片段: (Code snippets of the above syntax:)

double[] List = new double[10];

创建数组的另一种方法: (Another way to create an Array:)

dataType[] arrayName = {value_0, value_1, ..., value_k};

上面语法的代码片段: (Code snippets of above syntax:)

double[] list = {1, 2, 3, 4};The code above is equivalent to:
double[] list = new double[4];
*IMPORTANT NOTE: Please note the difference between the types of brackets
that are used to represent arrays in two different ways.

访问数组: (Accessing Arrays:)

arrayName[index]; // gives you the value at the specified index

上面语法的代码片段: (Code snippets of above syntax:)

System.out.println(list[1]);

Output:

输出:

2.0

修改数组: (Modifying Arrays:)

arrayName[index] = value;

Note: You cannot change the size or type of an array after initialising it. Note: You can however reset the array like so

注意:初始化数组后,无法更改其大小或类型。 注意:不过,您可以像这样重置阵列

arrayName = new dataType[] {value1, value2, value3};

数组大小: (Size of Arrays:)

It’s possible to find the number of elements in an array using the “length attribute”. It should be noticed here that java length is an attribute of every array i.e. a variable name storing the length of the variable. It must not be confused for a method of array since the name is same as the java length() method corresponding to String classes.

使用“长度属性”可以找到数组中元素的数量。 在这里应该注意的是, java length是每个数组的属性 ,即存储变量长度的变量名称。 请勿将其与数组方法混淆,因为其名称与对应于String类的java length()方法相同。

int[] a = {4, 5, 6, 7, 8}; // declare array
System.out.println(a.length); //prints 5

上面语法的代码片段: (Code snippets of above syntax:)

list[1] = 3; // now, if you access the array like above, it will output 3 rather than 2

Example of code:

代码示例:

int[] a = {4, 5, 6, 7, 8}; // declare array
for (int i = 0; i < a.length; i++){ // loop goes through each indexSystem.out.println(a[i]); // prints the array
}

Output:

输出:

45678

多维数组 (Multi-dimensional Arrays)

Two-dimensional arrays (2D arrays) can be thought of as a table with rows and columns. Though this representation is only a way to visualize the array for better problem-solving. The values are actually stored in sequential memory addresses only.

可以将二维数组(2D数组)视为具有行和列的表。 尽管此表示形式只是可视化阵列以更好地解决问题的一种方法。 这些值实际上仅存储在顺序存储器地址中。

int M = 5;
int N = 5;
double[][] a = new double [M][N]; //M = rows N = columns
for(int i = 0; i < M; i++) {for (int j = 0; j < N; j++) {//Do something here at index }
}

This loop will execute M ^ N times and will build this:

此循环将执行M ^ N次,并将构建此循环:

0 | 1 | 2 | 3 | 4 0 | 1 | 2 | 3 | 4 [ 0 | 1 | 2 | 3 | 4 ]

0 | 1 | 2 | 3 | 4 0 | 1 | 2 | 3 | 4 [0 | 1 | 2 | 3 | 4]

Similarly a 3D array can also be made. It can be visualised as a cuboid instead of a rectangle(as above), divided into smaller cubes with each cube storing some value. It can be initialised follows:

类似地,也可以制作3D阵列。 可以将其显示为长方体而不是矩形(如上所述),分为较小的多维数据集,每个多维数据集都存储一些值。 可以初始化如下:

int a=2, b=3, c=4;
int[][][] a=new int[a][b][c];

In a similar manner, one can an array of as many dimensions as he/she wishes to but visualizing an array of more than 3 dimensions is difficult to visualize in a particular way.

以类似的方式,可以按照他/她希望的那样排列尽可能多的尺寸,但是很难以一种特定的方式来可视化超过3个尺寸的阵列。

锯齿状阵列 (Jagged Arrays)

Jagged arrays are multi-dimensional arrays that have a set number of rows but a varying number of columns. Jagged arrays are used to conserve memory use of the array. Here is a code example:

锯齿状数组是多维数组,具有固定的行数但具有可变的列数。 锯齿状数组用于节省数组的内存使用量。 这是一个代码示例:

int[][] array = new int[5][]; //initialize a 2D array with 5 rows
array[0] = new int[1]; //creates 1 column for first row
array[1] = new int[2]; //creates 2 columns for second row
array[2] = new int[5]; //creates 5 columns for third row
array[3] = new int[5]; //creates 5 columns for fourth row
array[4] = new int[5]; //creates 5 columns for fifth row

Output:

输出:

0 0 | 1 | 2 | 3 | 4 [ 0 | 1 | 2 | 3 | 4 ]

0 0 | 1 | 2 | 3 | 4 [0 | 1 | 2 | 3 | 4]

控制流 (Control Flow)

Control flow statements are exactly what the term means. They are statements that alter execution flow based on decisions, loops and branching so that the program can conditionally execute blocks of code.

控制流语句正是该术语的含义。 它们是根据决策,循环和分支更改执行流程的语句,以便程序可以有条件地执行代码块。

Primarily, Java has the following constructs for flow control:

首先,Java具有以下用于流量控制的构造:

  • if

    if

  • if...else

    if...else

if( <expression that results in a boolean> ){//code enters this block if the above expression is 'true'
}
if( <expression that results in a boolean> ){//execute this block if the expression is 'true'
} else{//execute this block if the expression is 'false'
}

switch

switch

Switch is an alternative for the if...else construct when there are multiple values and cases to check against.

当要检查多个值和if...else时,使用switch if...else作为if...else构造的替代方法。

switch( <integer / String / Enum > ){case <int/String/Enum>: <statements>break;case <int/String/Enum>:<statements>break;default:<statements>
}

Note: The program flow falls through the next case if the break statement is missing. e.g. Let’s say you say the standard ‘Hello’ to everyone at office, but you are extra nice to the girl who sits next to you and sound grumpy to your boss. The way to represent would be something like:

注:程序流程falls through下一case ,如果break语句丢失。 例如,假设您对办公室中的每个人说标准的“ Hello”,但是对坐在您旁边并且对老板发脾气的女孩来说,您特别友善。 表示方式将类似于:

switch(person){case 'boss': soundGrumpy();break;case 'neighbour': soundExtraNice();break;case 'colleague':soundNormal();break;default:soundNormal();
}
Note: The `default` case runs when none of the `case` matches. Remember that when a case has no `break` statement, it `falls through` to the next case and will continue to the subsequent `cases` till a `break` is encountered. Because of this, make sure that each case has a `break` statement. The `default` case does not require a `break` statement.
  • nested statements

    nested statements

Any of the previous control flows can be nested. Which means you can have nested if,if..elseandswitch..casestatements. i.e., you can have any combination of these statements within the other and there is no limitation to the depth ofnesting.

任何先前的控制流都可以嵌套。 这意味着您可以嵌套ifif..elseswitch..case语句。 也就是说,您可以在其他语句之间组合使用这些语句,并且对nesting的深度没有限制。

For example, let’s consider the following scenario:

例如,让我们考虑以下情形:

  • If you have less than 25 bucks, you get yourself a cup of coffee.

    如果您的钱少于25美元,您可以自己喝杯咖啡。
  • If you have more than 25 bucks but less than 60 bucks, you get yourself a decent meal.

    如果您有超过25美元但少于60美元,您将获得一份体面的饭菜。
  • If you have more than 60 bucks but less than a 100, you get yourself a decent meal along with a glass of wine.

    如果您有超过60美元但不到100美元,那么您将获得一杯美味的饭菜和一杯葡萄酒。
  • However, when you have more than a 100 bucks, depending on who you are with, you either go for a candle lit dinner (with your wife) or you go to a sports bar (with your friends).

    但是,当您的收入超过100美元时(取决于与您在一起的人),您可以去烛光晚餐(与您的妻子)或去体育酒吧(与您的朋友)。

One of the ways to represent this will be:

表示这种情况的方法之一是:

int cash = 150;
String company = "friends";if( cash < 25 ){getCoffee();
} else if( cash < 60 ){getDecentMeal();
} else if( cash < 100 ){getDecentMeal();getGlassOfWine();
} else {switch(company){case "wife":candleLitDinner();break;case "friends": meetFriendsAtSportsBar();break;default:getDecentMeal();}
}

In this example, meetFriendsAtSportsBar() will be executed.

在此示例中,将执行meetFriendsAtSportsBar()

循环 (Loops)

Whenever you need to execute a block of code multiple times, a loop will often come in handy.

每当您需要多次执行一个代码块时,循环通常会派上用场。

Java has 4 types of loops:

Java有4种循环类型:

While循环 (While Loop)

The while loop repeatedly executes the block of statements until the condition specified within the parentheses evaluates to false. For instance:

while循环重复执行语句块,直到括号中指定的条件计算为false为止。 例如:

while (some_condition_is_true)
{// do something
}

Each ‘iteration’ (of executing the block of statements) is preceeded by the evaluation of the condition specified within the parentheses - The statements are executed only if the condition evaluates to true. If it evaluates to false, the execution of the program resumes from the the statement just after the whileblock.

(执行语句块的)每个“迭代”都以对括号内指定条件的评估为准-仅当条件评估为true才执行这些语句。 如果计算结果为false ,则在while块之后,从语句重新开始执行程序。

Note: For the while loop to start executing, you’d require the condition to be true initially. However, to exit the loop, you must do something within the block of statements to eventually reach an iteration when the condition evaluates to false (as done below). Otherwise the loop will execute forever. (In practice, it will run until the JVM runs out of memory.)

注意 :要开始执行while循环,您首先需要条件为true 。 但是,要退出循环,必须在语句块内执行某些操作,以在条件评估为false时最终达到迭代(如下所述)。 否则,循环将永远执行。 (实际上,它将运行到JVM内存耗尽为止。)

(Example)

In the following example, the expression is given by iter_While < 10. We increment iter_While by 1each time the loop is executed. The whileloop breaks wheniter_Whilevalue reaches 10.

在以下示例中, expressioniter_While < 10给出。 每次执行循环时,我们将iter_While1 。 当iter_While值达到10时, while循环中断。

int iter_While = 0;
while (iter_While < 10)
{System.out.print(iter_While + " ");// Increment the counter// Iterated 10 times, iter_While 0,1,2...9iter_While++;
}
System.out.println("iter_While Value: " + iter_While);

Output:

输出:

1 2 3 4 5 6 7 8 9
iter_While Value: 10

翻译自: https://www.freecodecamp.org/news/java-example/

java 示例

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/2/7133.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息