L1-010 比较大小(Java)

2024-01-09 22:55:03

题目

本题要求将输入的任意3个整数从小到大输出。

输入格式:
输入在一行中给出3个整数,其间以空格分隔。
输出格式:
在一行中将3个整数从小到大输出,其间以“->”相连。
输入样例:
4 2 8
输出样例:
2->4->8

解题思路

  1. 输入三个整数:说明输入数据固定死了,有两种解决构造输入的方式:第一种是无脑nextInt()三个变量;还有一种就是String[] str = scanner.nextLine().split(" ");
  2. 排序:因为只有三个整数,也可以简单的int temp然后互相调换值什么的。还有一种方式是:可以将str的值复制进int数组,接着用Arrays.sort排序int数组的值,最后输出。
  3. 如何去掉最后一个"->":循环输出0 -> N-2,最后再去输出最后一个值即可。

解题过程中遇到的问题

暂时没有!!

代码

import java.util.Arrays;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String[] str = scanner.nextLine().split(" ");
        int[] ints = new int[str.length];
        for (int j = 0; j < str.length; j++) {
            ints[j] = Integer.parseInt(str[j]);
        }
        Arrays.sort(ints);
        for (int i = 0; i < ints.length-1; i++) {
            System.out.print(ints[i]+"->");
        }
        System.out.print(ints[ints.length-1]);

    }
}
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int a = in.nextInt();
        int b = in.nextInt();
        int c = in.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);
    }
}

文章来源:https://blog.csdn.net/Gracener/article/details/135490567
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。