Java 如何修复方法错误
我只是想确定我在这里是正确的。我正在尝试将方法添加到 改变高度 改变宽度 改变坐标 计算周长 计算面积Java 如何修复方法错误,java,class,methods,rectangles,Java,Class,Methods,Rectangles,我只是想确定我在这里是正确的。我正在尝试将方法添加到 改变高度 改变宽度 改变坐标 计算周长 计算面积 public class MyRectangle { public int width; public int height; public int y; public int x; public MyRectangle() { width=10; height=10; y=10; x=10; public int MyRectangle; public
public class MyRectangle {
public int width;
public int height;
public int y;
public int x;
public MyRectangle()
{
width=10;
height=10;
y=10;
x=10;
public int MyRectangle;
public MyRectangle(int width, int height, int y, int x, int MyRectangle) {
this.width = width;
this.height = height;
this.y = y;
this.x = x;
this.MyRectangle = MyRectangle;
}
}
我的方法也出现了一个非法的表达式开始错误 这是您的问题,一个方法中不能有方法。 但这是因为你没有关闭你的方法括号。 我修复了您的代码并添加了您想要的方法:
public class MyRectangle {
//Best to group your variables up here
public int MyRectangle;
public int width;
public int height;
public int y;
public int x;
public MyRectangle() {
width = 10;
height = 10;
y = 10;
x = 10;
}//Make sure to close this method with the bracket
public MyRectangle(int width, int height, int y, int x, int MyRectangle) {
this.width = width;
this.height = height;
this.y = y;
this.x = x;
this.MyRectangle = MyRectangle;
}
/**
* Changes the current height to the given new height
* @param newHeight
*/
public final void changeHeight(int newHeight) {
height = newHeight;
}
/**
* Changes the current width to the given new width
* @param newWidth
*/
public final void changeWidth (int newWidth) {
width = newWidth;
}
/**
* Calculates the current perimeter based on the width and height
* @return parameter ofd the rectangle
*/
public final int getPerimeter() {
return ((2 * width) + (2 * height));
}
/**
* Calculates the area based on the width and height
* @return area of the rectangle
*/
public final int getArea() {
return (width * height);
}
public final void changesXCoordinate(int newX){
x = newX;
}
public final void changesYCoordinate(int newY){
y = newY;
}
public final void changesCoordinate(int newX, int newY) {
x = newX;
y = newY;
}
}
我很快会解释更多,只是想先发布正确的代码:p
就目前而言,你很难理解你还想要什么
如果这是您要找的,请将此标记为正确答案:D问题是什么?为什么要设置一个与类同名的变量,请先更改该名称,使类看起来更可读,如果您忘记在第一个构造函数上有一个close}。请检查您的代码是否有语法错误。您不能声明public int MyRectangle;在一个方法中,也不能在一个方法中声明一个方法。这里的任何人都可以很容易地为您提供一个带有改变宽度、高度的方法的代码。。。。但是你必须做出一些努力,你甚至没有尝试编译你的代码。我想知道为什么我收到-1,你能解释一下,这样我可以改进我的答案,并供未来的选民参考,但可能是因为你在回答,而你不明白他在找汉克斯·塔里克!但我只是纠正了他问的错误。。。很抱歉,如果我把这个作为一个答案,我认为这会帮助他;我失去了试图帮助他的rep别担心,这不算什么rep:通过正确编辑某人的问题,你可以轻松获得+2 rep;我想我几乎涵盖了他会问的关于这个的任何其他问题,增加了改变高度、宽度、面积和周长的方法