我对 Java 还很陌生,所以我确信我的代码非常丑陋和基本。我试图了解如何使用构造函数、setter 和 getter。我尝试查看此站点上的其他问题,查看视频,阅读书籍。我很难理解。谁能帮我?
以下是我的完整代码。我必须在项目中使用 setter 和 getter,并且我想确保我非常了解它们。
import javax.swing.JOptionPane;
public class userCar {
private int carYear;
private int speed;
private String make;
public void setCarYear(int carYear){
this.carYear=carYear;
}
public void setCarSpeed(int speed){
this.speed=speed;
}
public void setCarMake(String make){
this.make=make;
}
public int getCarYear(){
return this.carYear;
}
public int getCarSpeed(){
return this.speed;
}
public String getCarMake(){
return this.make;
}
public static void main (String [] args){
userCar ourCar = new userCar();
String userCarInput []= new String[3];
userCarInput= carInfo();
//THIS IS AN ERROR---
//"Cannot make a static reference to the non-static method setCarYear(int) from the type
//userCar"
userCar.setCarYear(Integer.parseInt(userCarInput[0]));
userCar.setCarSpeed(Integer.parseInt(userCarInput[2]));
userCar.setCarMake(userCarInput[1]);
//This would be displaying the the car make, year, and speed (using the get methods) but I am
//currently testing to make sure the values are correct. The array works fine, but not the
//setter/getter
JOptionPane.showMessageDialog(null,ourCar.getCarMake()+".\n"+ userCarInput[1]+".\n" +
userCarInput[2] +".\n");
}
public static String[] carInfo(){
String stringSpeed, stringYear, stringMake ;
String carInformation[] = new String[3];
stringSpeed=JOptionPane.showInputDialog("What is the speed of the car in MPH?");
//Deals with blank or "bad" entries. Follows in stringYear and stringMake as well.
if (stringSpeed == null) {
System.exit(0); }
while (stringSpeed.trim().length()== 0 || Integer.parseInt(stringSpeed) < 0){
stringSpeed= JOptionPane.showInputDialog("You did not enter a valid value.\n" +
"Please enter a valid value for speed.");
if (stringSpeed == null){
System.exit(0);}
}//ends the while
stringMake=JOptionPane.showInputDialog("What is the make of the car? [Toyota, "
+ "Cadillac, etc.] ");
if (stringMake == null) {
System.exit(0); }
while (stringMake.trim().length()== 0){
stringSpeed= JOptionPane.showInputDialog("You did not enter a valid value.\n" +
"Please enter a valid value for the car's make.");
if (stringSpeed == null){
System.exit(0);}
}//ends the while
stringYear=JOptionPane.showInputDialog("What year was the car made?");
if (stringYear == null) {
System.exit(0); }
while (stringYear.trim().length()== 0 || Integer.parseInt(stringYear) < 1769 ||
Integer.parseInt(stringYear) > 2016){
stringYear= JOptionPane.showInputDialog("You entered "+ stringYear + ".\n" +
"The first car was made in 1769, and the latest model is a 2015.\n"
+"Please enter a valid value for the car's year.");
if (stringYear == null){
System.exit(0);}
}//ends the while
carInformation [0] = stringSpeed;
carInformation [1] = stringMake;
carInformation [2] = stringYear;
return carInformation;
}
}