Java 使用构造函数和访问器方法
这是我的构造函数方法。我创建它是为了设置匹配号、杀戮号和死亡号。这些只是我创建的变量,然后不是来自任何游戏或任何东西 这将是访问器方法。我制作了一个文件,里面有匹配号、杀戮号和死亡号。我在线程main java.util.NoSuchElementException中得到错误异常:未找到任何行 位于java.util.Scanner.nextLine未知源 在Learning.MatchScoreS.checkoutscoresmachscores.java:22 在Learning.MatchScoreS.mainMatchScoreS.java:15。 当我删除aScanner.nextLine时;程序没有给我一个错误,但是它没有给我匹配号等等。。还有Java 使用构造函数和访问器方法,java,constructor,accessor,Java,Constructor,Accessor,这是我的构造函数方法。我创建它是为了设置匹配号、杀戮号和死亡号。这些只是我创建的变量,然后不是来自任何游戏或任何东西 这将是访问器方法。我制作了一个文件,里面有匹配号、杀戮号和死亡号。我在线程main java.util.NoSuchElementException中得到错误异常:未找到任何行 位于java.util.Scanner.nextLine未知源 在Learning.MatchScoreS.checkoutscoresmachscores.java:22 在Learning.Match
我刚刚开始学习java,我正在学习访问器和构造函数方法一章。任何帮助都会很棒!!谢谢。你好像有点困惑。您将整个类声明为访问器方法,另一个类声明为构造函数方法。访问器只是类中的函数,构造函数也是 如果您有一个变量foo,它的访问器通常采用以下形式:
package Learning;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class MatchScoreS {
public static void main(String args[])
throws IOException {
Scanner diskScanner =
new Scanner(new File("MatchScoress.txt")); //the file has to be in the package, in this case the Learning folder.
for (int games = 1; games <= 5; games++) {
checkoutscores(diskScanner);
}
diskScanner.close();
}
static void checkoutscores(Scanner aScanner) {
MatchScore aMatch = new MatchScore();
aMatch.setMatchNumber(aScanner.nextLine());
aMatch.setKillsInMatch(aScanner.nextLine());
aMatch.setDeathsInMatch(aScanner.nextLine());
aScanner.nextLine();
}
}
顺便说一句,通常字段和局部变量以非大写开头,所以它们应该是matchNumber、killsInMatch和deathsInMatch
现在,针对您的特定异常:看起来您的Matchscoress.txt文件只有3行,因此前三个nextLine调用成功,第四个抛出异常。这是我的构造函数方法。不,这就是整个类,而且它根本没有任何声明的构造函数,所以您只需要获得编译器默认为您声明的无参数构造函数。但是你得到的错误基本上是因为你的文件没有足够的行。。。
package Learning;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class MatchScoreS {
public static void main(String args[])
throws IOException {
Scanner diskScanner =
new Scanner(new File("MatchScoress.txt")); //the file has to be in the package, in this case the Learning folder.
for (int games = 1; games <= 5; games++) {
checkoutscores(diskScanner);
}
diskScanner.close();
}
static void checkoutscores(Scanner aScanner) {
MatchScore aMatch = new MatchScore();
aMatch.setMatchNumber(aScanner.nextLine());
aMatch.setKillsInMatch(aScanner.nextLine());
aMatch.setDeathsInMatch(aScanner.nextLine());
aScanner.nextLine();
}
}
void setFoo(<type> value) {
foo = value
}
<type> getFoo() {
return foo;
}
public MatchScore(String num, String kills, String death) {
MatchNumber = num;
KillsInMatch = kills;
DeathsInMatch = death;
}