21xrx.com
2024-09-17 04:46:19 Tuesday
登录
文章检索 我的文章 写文章
《Java编程:简单又好玩的代码案例》
2023-06-15 12:54:00 深夜i     --     --
Java编程 代码案例 乐趣

Java是一门广泛使用的计算机编程语言,它的应用领域非常广阔,如网络编程、桌面软件开发等。除此之外,Java也可以编写一些简单而有趣的代码案例,让你体验到编程的乐趣。

下面介绍几个简单好玩的Java代码案例:

1. 让计算机当售货员

这个代码案例可以让计算机当售货员,你可以自己制定售货方案并输入商品名和价格,计算机会自动计算总价并找零。


import java.util.Scanner;

public class VendingMachine {

  public static void main(String[] args) {

    Scanner scanner = new Scanner(System.in);

    int sum = 0;

    String name, choice = "y";

    int price, money;

    System.out.println("欢迎使用自动售货机!");

    while (choice.equalsIgnoreCase("y")) {

      System.out.print("请输入商品名称:");

      name = scanner.next();

      System.out.print("请输入商品价格:");

      price = scanner.nextInt();

      sum += price;

      System.out.print("是否继续购买?(y/n)");

      choice = scanner.next();

    }

    System.out.println("总金额:" + sum);

    System.out.print("请输入支付金额:");

    money = scanner.nextInt();

    System.out.println("找零:" + (money - sum));

    System.out.println("谢谢光顾!");

  }

}

2. 在控制台打出任意字符画

这个代码案例可以让你在控制台上打出任意的字符画,只需根据你喜欢的图案在代码中填写对应的字符并设置其大小即可。


public class AsciiArt {

  public static void main(String[] args) {

    String[][] art = {

        {" ", " ", "*", " ", " "},

        {" ", "*", "*", "*", " "},

        {"*", " ", "*", " ", "*"},

        {" ", "*", "*", "*", " "},

        {" ", " ", "*", " ", " "}

    };

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

      for (int j = 0; j < art[i].length; j++) {

        System.out.print(art[i][j]);

      }

      System.out.println();

    }

  }

}

3. 实现猜数字小游戏

这个代码案例是实现一个简单的猜数字小游戏,计算机随机生成一个数字,你需要猜测这个数字是多少,每次猜测后计算机都会告诉你猜的数字是大了还是小了,直到你猜对为止。


import java.util.Scanner;

import java.util.Random;

public class GuessNumber {

  public static void main(String[] args) {

    Scanner scanner = new Scanner(System.in);

    Random random = new Random();

    int num = random.nextInt(100) + 1;

    int guess;

    System.out.println("游戏开始!");

    do {

      System.out.print("请猜一个1~100的整数:");

      guess = scanner.nextInt();

      if (guess < num) {

        System.out.println("你猜的数字太小了!");

      } else if (guess > num) {

        System.out.println("你猜的数字太大了!");

      } else {

        System.out.println("恭喜你,猜对了!");

      }

    } while (guess != num);

  }

}

  
  

评论区

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