21xrx.com
2024-12-22 22:56:12 Sunday
登录
文章检索 我的文章 写文章
Java能写什么?看看这些案例就知道了!
2023-06-11 18:06:30 深夜i     --     --
Java 编程 应用场景

代码案例1:一个简易的计算器


import java.util.Scanner;

public class Calculator {

  public static void main(String[] args) {

    Scanner reader = new Scanner(System.in);

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

    double num1 = reader.nextDouble();

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

    double num2 = reader.nextDouble();

    System.out.print("请选择运算符 (+, -, *, /): ");

    char operator = reader.next().charAt(0);

    double result;

    switch(operator) {

      case '+':

        result = num1 + num2;

        break;

      case '-':

        result = num1 - num2;

        break;

      case '*':

        result = num1 * num2;

        break;

      case '/':

        result = num1 / num2;

        break;

      default:

        System.out.println("请输入正确的运算符。");

        return;

    }

    System.out.println(num1 + " " + operator + " " + num2 + " = " + result);

  }

}

代码案例2:一个简单的出租车计价器


import java.util.Scanner;

public class TaxiFareCalculator {

  public static void main(String[] args) {

    Scanner reader = new Scanner(System.in);

    System.out.print("请输入乘客乘车的距离(公里): ");

    double distance = reader.nextDouble();

    double baseFare = 10.0;

    double distanceFare = distance * 2.0;

    double totalFare = baseFare + distanceFare;

    System.out.println("出租车起步价为:" + baseFare + "元");

    System.out.println("出租车运行距离为:" + distance + "公里");

    System.out.println("出租车费用为:" + totalFare + "元");

  }

}

代码案例3:一个简单的猜数字游戏


import java.util.Scanner;

import java.util.Random;

public class GuessTheNumber {

  public static void main(String[] args) {

    Scanner reader = new Scanner(System.in);

    Random random = new Random();

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

    int guessCount = 0;

    int guessNumber = -1;

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

    while(guessNumber != targetNumber) {

      System.out.print("请输入你猜的数字(1-100之间):");

      guessNumber = reader.nextInt();

      guessCount++;

      if(guessNumber < targetNumber) {

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

      }

      else if(guessNumber > targetNumber) {

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

      }

      else {

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

        System.out.println("你一共猜了" + guessCount + "次。");

      }

    }

  }

}

通过以上的案例,我们可以看到Java的应用场景非常广泛,可以用来编写各种类型的程序,从简单的计算器到复杂的企业应用系统,都可以用Java来实现。

  
  

评论区

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