为了账号安全,请及时绑定邮箱和手机立即绑定

JavaSE学习:从零开始的入门指南

标签:
杂七杂八

这篇全面指南旨在帮助初学者掌握JavaSE核心技能。从基础语法到面向对象编程,再到集合框架与异常处理,我们将逐步深入,助力你建立坚实的Java编程基础。

入门基础知识

Java基础语法

public class HelloWorld {
    public static void main(String[] args) {
        int age = 25; // 整型变量
        String name = "John Doe"; // 字符串类型变量
        double price = 99.99; // 浮点型变量
        boolean isStudent = true; // 布尔型变量
        System.out.println("My name is " + name + ", I am " + age + " years old.");
    }
}
public class MathOperations {
    public static void main(String[] args) {
        int x = 10;
        int y = 5;
        int sum = x + y;
        int difference = x - y;
        int product = x * y;
        int quotient = x / y;
        int remainder = x % y;
        System.out.println("Sum: " + sum);
        System.out.println("Difference: " + difference);
        System.out.println("Product: " + product);
        System.out.println("Quotient: " + quotient);
        System.out.println("Remainder: " + remainder);
    }
}
public class ConditionalStatements {
    public static void main(String[] args) {
        int score = 85;
        if (score >= 90) {
            System.out.println("Excellent!");
        } else if (score >= 70) {
            System.out.println("Good");
        } else {
            System.out.println("Needs improvement");
        }
    }
}

面向对象编程基础

接下来,我们将探索面向对象编程的基石。

public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public void introduce() {
        System.out.println("Hi, I'm " + name + ", I'm " + age + " years old.");
    }
}

public class Main {
    public static void main(String[] args) {
        Person person = new Person("Jane Doe", 30);
        person.introduce();
    }
}
public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
public class Student extends Person {
    private String studentID;

    public Student(String name, int age, String studentID) {
        super(name, age);
        this.studentID = studentID;
    }

    public void printStudentDetails() {
        super.introduce();
        System.out.println("Student ID: " + studentID);
    }
}

public class Main {
    public static void main(String[] args) {
        Student student = new Student("Alice", 18, "123456");
        student.printStudentDetails();
    }
}
public class Animal {
    public void makeSound() {
        System.out.println("Animal makes a sound.");
    }
}

public class Dog extends Animal {
    public void makeSound() {
        System.out.println("Dog barks.");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal animal = new Dog();
        animal.makeSound();
    }
}

集合框架

Java的集合框架提供了强大的数据存储与操作能力。

import java.util.*;
import java.util.stream.Collectors;

public class CollectionExamples {
    public static void main(String[] args) {
        List<String> fruits = Arrays.asList("apple", "banana", "cherry");
        System.out.println("Original Fruits: " + fruits);
        fruits.add("orange");
        System.out.println("Fruits after adding orange: " + fruits);
        fruits.remove("banana");
        System.out.println("Fruits after removing banana: " + fruits);
        System.out.println("First fruit: " + fruits.get(0));
        System.out.println("Fruits size: " + fruits.size());

        Map<String, Integer> items = new HashMap<>();
        items.put("apple", 1);
        items.put("banana", 2);
        items.put("cherry", 3);
        System.out.println("Items: " + items);
        items.put("apple", 10);
        System.out.println("Items after updating apple: " + items);
        System.out.println("Banana exists in the map: " + items.containsKey("banana"));
        System.out.println("Banana value: " + items.get("banana"));
    }
}

异常处理

正确处理异常是编程中确保应用稳定性的关键。

public class ExceptionHandling {
    public static void main(String[] args) {
        try {
            int result = divide(10, 0);
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero.");
        } finally {
            System.out.println("End of try-catch block.");
        }
    }

    public static int divide(int a, int b) {
        return a / b;
    }
}

输入输出流

文件操作是Java编程中常用的功能。

import java.io.*;
import java.util.*;

public class FileOperations {
    public static void main(String[] args) {
        try (BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
             BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println("Reading: " + line);
                writer.write(line);
                writer.newLine();
            }
        } catch (IOException e) {
            System.out.println("Error reading or writing file.");
        }
    }
}
import java.io.*;

public class BinaryFileOperations {
    public static void main(String[] args) {
        try (FileInputStream fis = new FileInputStream("binaryfile.dat");
             FileOutputStream fos = new FileOutputStream("binaryfilecopied.dat")) {
            byte[] buffer = new byte[1024];
            int numRead;
            while ((numRead = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, numRead);
            }
        } catch (IOException e) {
            System.out.println("Error reading or writing binary file.");
        }
    }
}

实战项目:待办事项应用

在本节中,我们将构建一个简单的待办事项应用。

import java.util.ArrayList;
import java.util.Scanner;

public class TodoApp {
    public static void main(String[] args) {
        ArrayList<TodoItem> todos = new ArrayList<>();
        Scanner scanner = new Scanner(System.in);

        while (true) {
            System.out.println("\nTodo App");
            System.out.println("1. Add Todo");
            System.out.println("2. Mark as Completed");
            System.out.println("3. Delete Todo");
            System.out.println("4. View Todos");
            System.out.println("5. Exit");
            System.out.print("Enter your choice: ");
            int choice = scanner.nextInt();

            switch (choice) {
                case 1:
                    System.out.print("Enter Todo description: ");
                    String description = scanner.nextLine();
                    todos.add(new TodoItem(description));
                    System.out.println("Todo added successfully.");
                    break;
                case 2:
                    System.out.print("Enter Todo index to mark as completed: ");
                    int index = scanner.nextInt();
                    if (index < todos.size()) {
                        todos.get(index).markAsCompleted();
                    } else {
                        System.out.println("Invalid index.");
                    }
                    break;
                case 3:
                    System.out.print("Enter Todo index to delete: ");
                    index = scanner.nextInt();
                    if (index < todos.size()) {
                        todos.remove(index);
                        System.out.println("Todo deleted successfully.");
                    } else {
                        System.out.println("Invalid index.");
                    }
                    break;
                case 4:
                    for (TodoItem item : todos) {
                        item.printItem();
                    }
                    break;
                case 5:
                    System.out.println("Exiting Todo App.");
                    scanner.close();
                    return;
                default:
                    System.out.println("Invalid choice. Please try again.");
            }
        }
    }
}

通过上述示例,你已掌握了JavaSE的基础知识,包括基本语法、面向对象编程、集合框架、异常处理和文件操作。结合实战项目,你将能够将理论知识应用于实际场景,进一步巩固和提升编程技能。若需更多高级概念或实例,可参阅相关在线资源。

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
JAVA开发工程师
手记
粉丝
205
获赞与收藏
1008

关注作者,订阅最新文章

阅读免费教程

  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消