欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  Java

java中三目运算符和数组方法以及整数比较大小的代码

程序员文章站 2022-03-10 20:17:14
...

本篇文章给大家带来的内容是关于java中三目运算符和数组方法以及整数比较大小的代码,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

代码块

代码如下,例如:

//class前,导入的java包import java.util.Scanner;

//我只把主方法列出来了
public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // 接收用户输入        
        System.out.println("清输入第1个数:");        
        int a = scanner.nextInt();        
        System.out.println("清输入第2个数:");        
        int b = scanner.nextInt();        
        System.out.println("清输入第3个数:");        
        int c = scanner.nextInt();        
        System.out.println("清输入第4个数:");        
        int d = scanner.nextInt();

        // 三目运算解决        
        int m = a > b ? a : b;
        int n = c > d ? c : d;
        int x = m > n ? m : n;
        System.out.println("max=" + x);

        // 分支方法解决
        int t;        
        if (a > b) {
            t = a;  a = b;  b = t;  
            }        
        if (a > c) {
            t = a;  
            a = c;  
            c = t;  
            }  
         if (a > d) {
             t = a;  
             a = d;  
             d = t;  
             }        
         if (b > c) {
             t = b;  
             b = c;  
             c = t;  
             }        
         if (b > d) {
             t = b;  
             b = d;  
             d = t;  
             }        
         if (c > d) {
             t = c;  
             c = d;  
             d = t;  
             }
        System.out.println("max=" + d);

        // 数组方法解决
        int p[] = new int[4];        
        for (int i = 0; i < 4; i++) {
            System.out.println("请输入第" + (i + 1) + "个数字:");
            p[i] = scanner.nextInt();
        }        
        for (int i = 0; i < 3; i++) {            
        if (p[i] > p[i + 1]) {
                // 这里也可以设置一个中间变量t来进行交换
                p[i] = p[i] + p[i + 1];
                p[i + 1] = p[i] - p[i + 1];
                p[i] = p[i] - p[i - 1];
            }
        }
        System.out.println("max=" + p[3]);// 最大的就放在数组最后了
    }

相关推荐:

php中判断数组相等的方法以及数组运算符介绍,数组运算符

以上就是java中三目运算符和数组方法以及整数比较大小的代码的详细内容,更多请关注其它相关文章!