我必须根据实例提问,并使用System.in进行输入。
首先是这样的例子:
我创建了一个实例变量,名为woodenSword,其中包括:
Sword woodenSword=new Sword("Wooden Sword", 2);
public Sword(String nameSword, int damageSword){
this.nameSword=nameSword;
this.damageSword=damageSword;
numberOfSwords++;
}现在,我想访问damageSword,但是如何做到这一点呢?我试过woodenSword.damageSword,但很明显这不管用.我认为这是因为我将变量设置为private,但我不想改变它,因为我在某个地方读到,最好保留变量private。(还有一个附带的问题:为什么保持变量的私有性更好?)
还有另一个问题:如何获得System.in的输入?一定要用System.in.toString()来做吗?
我应该用一个函数来做这个吗?从类中获取私有变量,并将该函数放入类中?我想过这个功能:
public static int getSwordStats(String nameSword){
damageSword=nameSword.damageSword;
}但是,我在nameSword.damageSword上遇到了一个错误,我想它不明白它是一个变量.我怎么才能解决这个问题?
希望你能帮我!
发布于 2013-11-17 16:22:20
看起来你的剑类负责跟踪3件事:
前两个需要是成员变量,而最后两个需要是静态变量。
public class Sword {
// private (so no one can access it but Sword)
// static (so it belongs to the class Sword and not any specific Sword)
private static int numberOfSwords = 0; // initialize to 0
// public accessor method
public static int getNumberOfSwords() {
return numberOfSwords;
}
// notice there's no "setNumberOfSwords" - no one can come along and change
// our data - it's 'encapsulated' in the class
private String name; // private
private int damage; // private
public Sword(String name, int damage) {
this.name = name;
this.damage = damage;
numberOfSwords++; // the only place we change number of swords
}
// this is how people outside Sword access the name
// note that we could add a "setName(String name)" if we want
public String getName() {
return name;
}
// same with name - protect and provide an accessor
public int getDamage() {
return damage;
}
}在以后的课程中,您现在可以这样做:
Sword wood = new Sword("Wooden Sword", 2);
System.out.println("wood's name is " + wood.getName());
System.out.println("wood's damage is " + wood.getDamage());
System.out.println("swords crafted so far: " + Sword.getNumberOfSwords());
Sword mithril = new Sword ("Mithril Sword", 10);
System.out.println("mithril 's name is " + mithril .getName());
System.out.println("mithril 's damage is " + mithril .getDamage());
System.out.println("swords crafted so far: " + Sword.getNumberOfSwords());它将打印
Wooden Sword
2
1
Mithril Sword
10
2关于你的第二个问题,我相信谷歌能帮你找到一些很好的资源。举个例子,下面是我所做的工作:
// assumes you "import java.util.Scanner"
Scanner sc = new Scanner(System.in);
while(sc.hasNextLine()) {
String line = sc.nextLine();
System.out.println("You typed: " + line);
}发布于 2013-11-17 16:21:17
如果您需要从任何地方访问您的剑的伤害,那么您应该有一个返回以下信息的公共方法:
public int getDamage() {
return this.damageSword;
}(请注意,我将方法命名为getDamage(),而不是getDamageSword()。方法在类剑中。把剑放在任何地方都是无用的,只会增加噪音,使代码的可读性降低)。
关于你的第二个问题。是的,System.in是标准输入流。toString()不会返回用户输入的内容。阅读类的javadoc,了解它是如何工作的。还可以阅读Java教程,它有一个关于命令行的部分。
关于最后一部分,您的代码试图获取字符串的损坏。弦没有损伤。剑有伤害。
https://stackoverflow.com/questions/20033036
复制相似问题