gpt4 book ai didi

Java自行车和自行车测试

转载 作者:行者123 更新时间:2023-12-01 12:32:55 25 4
gpt4 key购买 nike

我在编写代码时遇到问题。在这段代码中,我必须创建一个对象类并使用另一个类对象运行它。该程序称为自行车和自行车测试。我得到了自行车程序(它已经写好了),我需要编写自行车测试来使用自行车。现在的问题是,我创建了 2 个对象,分别称为 NiceBicycle 和 CoolBicycle。我需要将 NiceBicycle 名称更改为“Kenny McCormick”,但我做不到。我不断收到错误消息对于我编写的这行命令,“错误:变量 NiceBicycle 可能尚未初始化”。

//使用 setOwnerName 将所有者名称更改为 Kenny McCormick NiceBicycle.setOwnerName("肯尼·麦考密克");

我该怎么办?

无论如何,这是我根据教练命令编写的自行车代码和自行车测试。谢谢您的回复

自行车.java

public class Bicycle
{

// Instance field
private String ownerName;
private int licenseNumber;

// Constructor
public Bicycle( String name, int license )
{
ownerName = name;
licenseNumber = license;
}

// Returns the name of this bicycle's owner
public String getOwnerName()
{
return ownerName;
}

// Assigns the name of this bicycle's owner
public void setOwnerName( String name )
{
ownerName = name;
}

// Returns the license number of this bicycle
public int getLicenseNumber()
{
return licenseNumber;
}

// Assigns the license number of this bicycle
public void setLicenseNumber( int license )
{
licenseNumber = license;
}

}

这是我编写的 biketest.java。

  public class BicycleTest 
{

public static void main( String[] args )
{

// Create 1 Bicycle reference variable. For example: myBike
Bicycle NiceBicycle;

// Create 1 String reference variable for the owner's name
String name;

// Create 1 integer variable for license number
int licenceNumber;

// Assign your full name and a license number to the String and
// integer variables
name = "Boo Yeah";
int licenseNumber = 9972;

// Create a Bicycle object with the Bicycle class constructor
// Use the variables you created as arguments to the constructor
Bicycle CoolBicycle = new Bicycle( "Boo Yeah", 9972 );

// Output the owner's name and license number in printf statements
// using the object reference and the get methods.
// For example: bike.getOwnerName()
System.out.printf ("The CoolBicycle owner's name is %s\nThe license number is %d\n", CoolBicycle.getOwnerName(), CoolBicycle.getLicenseNumber());

// Change the owner's name to Kenny McCormick using setOwnerName
NiceBicycle.setOwnerName("Kenny McCormick");

// Output the owner's name and license number in printf statements
// using the Bicycle object reference variable and the get methods.
System.out.printf ("The NiceBicycle owner's name is %s\n", NiceBicycle.getOwnerName());
}

}

最佳答案

您需要实例化 Bicycle 并将其分配给测试中的 NiceBicycle,方法是更改​​:

Bicycle NiceBicycle;

至:

Bicycle NiceBicycle = new Bicycle("", 0);

然后你可以对其进行 setOwnerName() :

NiceBicycle.setOwnerName("Kenny McCormick");

另请注意,Java 约定建议变量名称以小写字母开头,因此如果您想遵循 Java 约定,NiceBicycle 应该是 niceBicycle

关于Java自行车和自行车测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25801666/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com