21xrx.com
2024-12-23 00:19:57 Monday
登录
文章检索 我的文章 写文章
Java代码实例详解
2023-06-14 16:19:42 深夜i     --     --
Java代码 实例 计算器程序 HTTP请求 冒泡排序

Java作为一门广泛应用的编程语言,其代码编写和实现部分是很多程序员需要深入了解并掌握的。下面,本文将为大家带来一些Java代码例子,通过讲解这些例子帮助读者更深入理解Java编程的实现和基础知识。

1. Java实现简单计算器程序

// Java简单计算器程序,支持加、减、乘、除四则运算

import java.util.Scanner;

public class CalculatorDemo {

  public static void main(String[] args) {

    Scanner scanner = new Scanner(System.in);

    System.out.print("请输入第一个数:");

    double a = scanner.nextDouble();

    System.out.print("请输入第二个数:");

    double b = scanner.nextDouble();

    System.out.print("请输入运算符(+、-、*、/中的一个):");

    String operator = scanner.next();

    double result = 0;

    switch (operator) {

      case "+":

        result = a + b;

        break;

      case "-":

        result = a - b;

        break;

      case "*":

        result = a * b;

        break;

      case "/":

        result = a / b;

        break;

      default:

        System.out.println("输入的运算符错误!");

    }

    System.out.println("运算结果为:" + result);

    scanner.close();

  }

}

2. Java实现简单的HTTP请求

// Java实现HTTP请求

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.URL;

public class HttpDemo {

  public static void main(String[] args) throws Exception {

    String url = "https://www.baidu.com";

    URL obj = new URL(url);

    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    // 设置请求类型和头信息

    con.setRequestMethod("GET");

    con.setRequestProperty("User-Agent", "Mozilla/5.0");

    int responseCode = con.getResponseCode();

    System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(

        new InputStreamReader(con.getInputStream()));

    String inputLine;

    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {

      response.append(inputLine);

    }

    in.close();

    System.out.println(response.toString());

  }

}

3. Java实现冒泡排序

// Java冒泡排序

public class BubbleSortDemo {

  public static void main(String[] args) {

    int[] arr = 12;

    bubbleSort(arr);

    for (int i = 0; i < arr.length; i++) {

      System.out.print(arr[i] + " ");

    }

  }

  public static void bubbleSort(int[] arr) {

    int temp = 0;

    for (int i = 0; i < arr.length - 1; i++) {

      for (int j = 0; j < arr.length - i - 1; j++) {

        if (arr[j] > arr[j + 1]) {

          // 交换位置

          temp = arr[j];

          arr[j] = arr[j + 1];

          arr[j + 1] = temp;

        }

      }

    }

  }

}

  
  

评论区

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