有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

?: 在Java中:如何更合理地组合res和resString?

我希望输出(double res和String resString的混合)被分配一个变量

import java.util.Scanner;
public class Lab3Task02_08 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("х = ");
        int x = in.nextInt();
        System.out.print("y = ");
        int y = in.nextInt();
        double arithm = (x+y)/2;
        double geom = Math.sqrt(Math.abs(x*y));
        
        //////////////////////////////////////////////////////////////
        double res = x>y? arithm:geom;
        String resString = x>y? "Arithm.average = ":"Geom.average = ";
        //////////////////////////////////////////////////////////////

        System.out.print(resString + res);
        in.close();
    }
}

共 (2) 个答案

  1. # 1 楼答案

    如果我理解这个问题,这就是你想要的吗

    import java.util.Scanner;
    public class Lab3Task02_08 {
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            System.out.print("х = ");
            int x = in.nextInt();
            System.out.print("y = ");
            int y = in.nextInt();
            double arithm = (x+y)/2;
            double geom = Math.sqrt(Math.abs(x*y));
            
            //////////////////////////////////////////////////////////////
            double res = x>y? arithm:geom;
            String resString = x>y? "Arithm.average = ":"Geom.average = ";
            //////////////////////////////////////////////////////////////
            String combinedRes = resString + res;
            System.out.print(combinedRes);
            in.close();
        }
    }
    
  2. # 2 楼答案

    据我所知,您希望根据相同的条件输出两个不同的值。其中一个选项是,它可以通过String.format()Double.compare()x ? y : x完成

    public static void main(String... args) throws ParseException {
        Scanner scan = new Scanner(System.in);
    
        System.out.print("х = ");
        int x = scan.nextInt();
    
        System.out.print("y = ");
        int y = scan.nextInt();
    
        double arithmetic = (x + y) / 2.;
        double geometric = Math.sqrt(Math.abs(x * y));
        int res = Double.compare(arithmetic, geometric);
    
        System.out.format(Locale.ENGLISH, "%s average = %.2f\n",
                res > 0 ? "Arithmetic" : "Geometric",
                res > 0 ? arithmetic : geometric);
    }
    

    输出:

    х = 3
    y = 5
    Arithmetic average = 4.00
    
    х = -4
    y = 3
    Geometric average = 3.46