21xrx.com
2024-09-17 04:19:32 Tuesday
登录
文章检索 我的文章 写文章
Java编程实例大全
2023-06-10 14:22:43 深夜i     --     --
Java编程 代码实例 基础知识

作为一名Java程序员,编程代码是我的日常工作之一。在我的工作中,我积累了许多有用的Java代码。今天,我将和大家分享一些Java编程代码的实例。这些代码片段涵盖了Java编程的许多方面,包括基本数据类型、循环和条件语句、类和对象、文件处理、网络编程等等。我的目的是让大家能够更好地理解Java编程的基础知识,并为您的Java编程提供帮助。接下来,我会给大家提供一些示例代码。

1. 基本数据类型

int x = 5;

float y = 5.5f;

double z = 10.123;

char c = 'a';

boolean b = true;

2. 循环和条件语句

int i = 0;

while (i < 10) {

  System.out.println(i);

  i++;

}

for (int j = 0; j < 10; j++) {

  System.out.println(j);

}

if (x > y) {

  System.out.println("x is greater than y");

} else if (x < y) {

  System.out.println("x is less than y");

} else {

  System.out.println("x is equal to y");

}

3. 类和对象

public class Person {

  String name;

  int age;

  public Person(String name, int age)

   this.name = name;

   this.age = age;

  public void introduce() {

   System.out.println("My name is " + name + " and I am " + age + " years old.");

  }

}

Person john = new Person("John", 30);

john.introduce();

4. 文件处理

File file = new File("example.txt");

try {

  Scanner scanner = new Scanner(file);

  while (scanner.hasNextLine()) {

   String line = scanner.nextLine();

   System.out.println(line);

  }

  scanner.close();

} catch (FileNotFoundException e) {

  System.out.println("File not found.");

}

5. 网络编程

import java.net.*;

import java.io.*;

public class MyServer {

  public static void main(String[] args) {

   try {

     ServerSocket serverSocket = new ServerSocket(8080);

     Socket socket = serverSocket.accept();

     DataInputStream in = new DataInputStream(socket.getInputStream());

     DataOutputStream out = new DataOutputStream(socket.getOutputStream());

     String message = in.readUTF();

     System.out.println("Message received: " + message);

     out.writeUTF("Hello from server.");

     socket.close();

   } catch (IOException e) {

     System.out.println("IOException occurred.");

   }

  }

}

以上是介绍Java编程代码的实例。通过阅读这些代码片段,希望您能理解Java编程的基础知识,并在进一步的Java编程中获得帮助。三个

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复