21xrx.com
2025-03-15 11:26:11 Saturday
文章检索 我的文章 写文章
Java编程实现输入三个数,把这三个数由小到大排列
2023-06-11 06:42:02 深夜i     11     0
输入 排序 Java编程

在编程中,输入和排序是重要的基础知识点。我们需要对输入的数据进行排序的操作,以达到更好的数据展示效果。这篇文章将会介绍Java编程中如何对输入的三个数进行排序,以从小到大的方式输出。

首先,我们需要使用Java中的Scanner类来进行数据的输入。Scanner类有多种构造函数,可以根据需要进行选择。在这里,我们使用默认的构造函数,即使用System.in作为源进行输入。

import java.util.Scanner;
public class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("请输入三个整数:");
    int a = sc.nextInt();
    int b = sc.nextInt();
    int c = sc.nextInt();
    // 在这里填写排序代码
  }
}

接下来,我们需要进行排序的操作。一般来说,排列算法分为冒泡排序、选择排序和快速排序等。在这里,我们选择最简单的冒泡排序算法。

import java.util.Scanner;
public class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("请输入三个整数:");
    int a = sc.nextInt();
    int b = sc.nextInt();
    int c = sc.nextInt();
    // 排序部分
    if (a > b)
      int temp = a;
      a = b;
      b = temp;
    
    if (a > c)
      int temp = a;
      a = c;
      c = temp;
    
    if (b > c)
      int temp = b;
      b = c;
      c = temp;
    
    System.out.println("排序结果为:" + a + " " + b + " " + c);
  }
}

以上就是Java编程实现输入三个数,并对其从小到大进行排序的代码示例。在排序部分,我们通过比较大小,进行数组元素之间的交换位置,以达到排序的目的。

  
  

评论区

请求出错了