2015-07-01 21 views
0
package Learning; 

public class MatchScore { 

    private String MatchNumber; 
    private String KillsInMatch; 
    private String DeathsInMatch; 

    public void setMatchNumber(String nameIn){ 
     MatchNumber = nameIn; 
    } 
    public String getName(){ 
     return MatchNumber ; 
    } 

    public void setKillsInMatch(String killsIn){ 
     KillsInMatch = killsIn; 
    } 
    public String getKillsInMatch(){ 
     return KillsInMatch; 
    } 
    public void setDeathsInMatch(String deathsIn){ 
     DeathsInMatch = deathsIn; 
    } 
    public String getDeathsinMatch(){ 
     return DeathsInMatch; 
    } 

    public void totalStatus(double Stats){ 
     System.out.printf("This game is %s ", MatchNumber); 
     System.out.printf("you killed-this many %s", KillsInMatch); 
     System.out.printf("but you died-this many time %s", DeathsInMatch); 
    } 

} 

这是我的构造函数方法。我已经创建了它,以便它设置匹配号码,杀死号码和死亡号码。这些只是我创建的变量,并非来自任何游戏或任何东西。使用构造函数和访问器方法

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(); 
     } 
    } 

这^将存取器方法。我制作了一个包含比赛号码,杀人号码和死亡号码的文件。我得到了错误“线程中的异常”主要“java.util.NoSuchElementException:没有找到线在java.util.Scanner.nextLine(Unknown Source) 012.在学习.MatchScoreS.checkoutscores .MatchScoreS.main(MatchScoreS.java:15)”。 当我删除“aScanner.nextLine();程序犯规给我一个错误,但它不给我的比赛数量,等等。以及

我刚开始学习Java和。 im有关Accessor和构造方法的章节,任何帮助都会很棒!!谢谢

+0

“这是我的构造方法。”不,这是整个类 - 它没有任何声明的构造函数,所以你只需获取编译器为你默认声明的无参数构造函数。但是,你得到的错误基本上是因为你的文件没有足够的行...... –

回答

0

你似乎有点困惑,你声称整个类是一个存取方法,而另一个类是一个构造方法。只是类中的函数,构造函数也是如此。

如果你有一个变量foo,它的访问器通常在fo RM:

void setFoo(<type> value) { 
    foo = value 
} 

<type> getFoo() { 
    return foo; 
} 

因此,在你的代码,setMatchNumber()getName()setKillsInMatch()getKillsInMatch()等都是存取(althoug getName()应该叫getMatchNumber())。

构造函数是一种方法,它声明的名称与它所包含的类名相同,在声明中没有返回类型。例如,对于MatchScore类,你可能有

public MatchScore(String num, String kills, String death) { 
    MatchNumber = num; 
    KillsInMatch = kills; 
    DeathsInMatch = death; 
} 

(顺便说一句,通常领域和局部变量启动非资本化的,所以他们应该是matchNumberkillsInMatchdeathsInMatch代替)。

现在,对于您的特定例外情况:它看起来像您的Matchscoress.txt文件只有3行,因此前三个nextLine()调用成功,第四个引发异常。

相关问题