Java でコインのプログラムを作っています。
###発生している問題・エラーメッセージ
Exception in thread "main" java.lang.NullPointerException
at week02.Coins.<init>(Coins.java:51)
at week02.Coins.main(Coins.java:27)
やろうとしていることはString "HHHHTT" などからHならHEADS として、TならTAILとして配列に入れていき新しいCoins オブジェクトを作ろうとしていますが、上記のエラーが出てしまいます。どうしてでしょうか?
###該当のソースコード
package week02;
/**
Coin tossess.
@author Tomofumi Kimura
/
public class Coins{
/*
Coins tosses.
*/ public static final boolean HEADS = true; public static final boolean TAILS = false; private boolean[] coins; public static void main(String [] args){ /** @param none */ //boolean [] b = {HEADS, TAILS,HEADS, HEADS, TAILS}; //Coins c = new Coins(b); //System.out.println(c.countHeads()); //System.out.println(c.toString()); //String result = c.toString(); Coins c2 = new Coins("HHHH"); System.out.println(c2); } public Coins(boolean[] coins){ this.coins = coins; } public Coins(String c){ /** read String consisting H and T and make boolean coins 1. read H and T and put HEADS and TAILS into coins array */ for (int i=0;i<c.length();i++){ if (c.charAt(i)=='H'){ this.coins[i] = HEADS; }else if (c.charAt(i)== 'T'){ this.coins[i] = TAILS; } } } public int countHeads(){ /** @param none @return the number of occurrences of heads */ int count=0; for (boolean s:this.coins){ if(s== true){ count++; } } return count; } public String toString(){ /** @param none @return String */ String result = ""; for (boolean s:this.coins){ if (s== true){ result+= "H"; }else{ result+= "T"; } } return result; }
}
###試したこと
###補足情報(言語/FW/ツール等のバージョンなど)
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。