2015-07-01 24 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()調用成功,第四個引發異常。

相關問題