我显然不明白我在这里做什么……我可以肯定的是,我的错误仅在所包含的代码中,但是我也有其他类。如果我可以将其重命名为更好的标题,请告诉我,或者如果我可以包含更多信息,请告诉我。从我在该网站上看到的信息来看,我相信你们会确切地知道编译错误的含义,并且知道我做错了什么。
这是我的代码:
import java.io.PrintStream;
public class Shape
{
public static void init( String args[] )
{
Shape[] shapes = new Shape[ 4 ];
shapes[ 0 ] = new Circle( 22, 88, 4 );
shapes[ 1 ] = new Square( 71, 96, 10 );
shapes[ 2 ] = new Sphere( 8, 89, 2 );
shapes[ 3 ] = new Cube( 79, 61, 8 );
for ( Shape currentShape : shape );
{
System.out.printf( "%s: %s",
currentShape.getName(), currentShape );
Object localObject;
if ( currentShape objectof TwoDimensionalShape )
{
localObject = (TwoDimensionalShape)currentShape;
TwoDimensionalShape twoDimensionalShape =
( TwoDimensionalShape ) currentShape;
System.out.printf( "%s's area is %s\n",
currentShape.getName(), twoDimensionalShape.getArea() );
}
if ( currentShape objectof ThreeDimensionalShape; )
{
ThreeDimensionalShape threeDimensionalShape =
( ThreeDimensionalShape ) currentShape;
System.out.printf( "%s's area is %s\n",
currentShape.getName(), threeDimensionalShape.getArea() );
System.out.printf( "%s's volume is %s\n",
currentShape.getName(),
threeDimensionalShape.getVolume() );
}
System.out.println();
}
}
}
我的编译错误:
ShapeTest.java:21: error: ')' expected
if ( currentShape objectof TwoDimensionalShape )
^
ShapeTest.java:21: error: ';' expected
if ( currentShape objectof TwoDimensionalShape )
^
ShapeTest.java:21: error: variable declaration not allowed here
if ( currentShape objectof TwoDimensionalShape )
^
ShapeTest.java:33: error: ')' expected
if (( currentShape objectof ThreeDimensionalShape; ))
^
ShapeTest.java:33: error: illegal start of expression
if (( currentShape objectof ThreeDimensionalShape; ))
^
ShapeTest.java:33: error: illegal start of expression
if (( currentShape objectof ThreeDimensionalShape; ))
^
6 errors
最佳答案
Java具有instanceof
运算符,而不是objectof
在第21行中,将if (currentShape objectof TwoDimensionalShape)
替换为if(currentShape instanceof TwoDimensionalShape){ //more code }
在第33行中if (currentShape objectof ThreeDimensionalShape;)
与if(currentShape instanceof ThreeDimensionalShape){ //more code }