简体   繁体   English

为什么输出显示“null”?

[英]Why does the output show "null"?

import java.lang.*;

public class TriangleType {
    int side1, side2, side3;  
    String kind;

    public TriangleType(int a, int b, int c) {
        side1 = a;
        side2 = b;
        side3 = c;

        if (a==b || b==c)
            kind = "Equilateral";
    }

    public static void main (String[]args)  {
        TriangleType triangle1 = new TriangleType(12, 13, 14);

        System.out.println("The sides are " + triangle1.side1 + " " +triangle1.side2 + " " +triangle1.side3);
        System.out.println("Triangle type: " + triangle1.kind );

        System.exit(0);
    }
}

The output is:输出是:

The sides are 12 13 14
Triangle type: null

How can I make the triangle type output to show "equilateral"?如何使三角形类型输出显示“等边”?

First of all, your equilateral formula is wrong:首先,你的等边公式是错误的:

if (a==b || b==c)
kind = "Equilateral";

Should be应该

if (a==b && b==c)
kind = "Equilateral";

Second, the triangle you are creating needs equal sides to be equilateral其次,您正在创建的三角形需要等边才能等边

   TriangleType triangle1 = new TriangleType(12, 12, 12);

Also, IMO if the triangle is not equilateral, you should set it kind to something else ("not equilateral"?)另外,IMO 如果三角形不是等边的,您应该将其设置为其他类型(“非等边”?)

You also might want to think of getting rid of the kind member variable, as your equilateral function can be calculated when needed您可能还想考虑摆脱kind成员变量,因为可以在需要时计算您的等边函数

The reason is that this triangle (12 13 14) is not equilateral.原因是这个三角形(12 13 14)不是等边的。 If you make it equilateral, say (a = b = c = 12), then the output of the triangle type will be "equilateral"如果将其设为等边,例如 (a = b = c = 12),则三角形类型的输出将是“等边”

    public class TriangleType {


int side1, side2, side3;
String kind;


public TriangleType(int a, int b, int c) {

    side1 = a;
    side2 = b;
    side3 = c;

    if (a==b || b==c)
        kind = "Equilateral";

}


public static void main (String[]args)  {



    TriangleType triangle1 = new TriangleType(12, 12, 12);

    System.out.println("The sides are " + triangle1.side1 + " " +triangle1.side2 + " " +triangle1.side3);
    System.out.println("Triangle type: " + triangle1.kind );

    System.exit(0);

}

} }

Because no one of this condition in if-statement is not true.因为 if 语句中的这个条件没有一个是不正确的。 You are set a sides of triangle, but each of this side is not equal.你设置了三角形的一条边,但这条边的每条边都不相等。 Seems like you should set default value for kind似乎您应该为kind设置默认值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM