• 締切済み

Java: NullPointerException が発生する

Java: NullPointerException が発生する 今日Javaを始め, ボウリングスコアプログラムを作成しています. ある程度コーディングしたのですが, 例外が発生して進めません. 原因と解決法がわからず困っています.どなたか回答お願いします ソース(一部省略): Game.java ---------- public class Game { public static void main(String[] args) { Frame[] frame = new Frame[10]; NullFrame nulframe = new NullFrame(); LastFrame frame10 = new LastFrame(); ArrayList<Frame> frames = new ArrayList<Frame>(); frames.add(nulframe); for (int i = 1 ; i < 10 ; i++) { frames.add(frame[i]); } frames.add(frame10); if(args.length >= 1) { System.out.println("Input Score From: "+args[0]); fin.makeScoreArray(args[0]); } else { for(int i = 1; i < 10 ; i++) { if (i == 1) { frame[i].setPrevFrame(nulframe); // エラー発生 } else { frame[i].setPrevFrame(frame[i-1]); } if (i >= 9) { frame[i].setNextFrame(frame10); } else { frame[i].setNextFrame(frame[i+1]); // エラー発生 } int m = frame[i].getThrowableNum(); // エラー発生 for(int j = 0 ; j < m ; j++) { if((frame[i].getThrowScore(j)) >= 10) break; // エラー発生 board.display(); } } } } } ---- Frame.java ---- public class Frame implements FrameScore{ private static final int ONE_MORE = 1; private static final int TWO_MORE = 2; private static final int CLOSED = 0; private static final int THROWNUM = 2; private int[] score_; private int ftotal_; public int total_; private int status_; Frame prev_; Frame next_; public Frame () { score_ = new int[2]; score_[0] = -1; score_[1] = -1; prev_ = null; next_ = null; } public Frame(int[] score_, int total_, int status_) { this.score_[0] = score_[0]; this.score_[1] = score_[1]; this.status_ = status_; this.prev_ = prev_; this.next_ = next_; } public void setPrevFrame(Frame f){ prev_ = f; } public void setNextFrame(Frame f){ next_ = f; } public int getThrowableNum() { return THROWNUM; }

  • Java
  • 回答数1
  • ありがとう数1

みんなの回答

  • LancerVII
  • ベストアンサー率51% (1060/2054)
回答No.1

こんにちは。 Frame[] frame = new Frame[10]; でFrame型の配列を宣言していますが、 宣言のみ(箱だけ用意)しかしていないのでframe[i].・・・とメソッドにアクセスするとNullPointerが発生しているのだと思います。 for (int i = 1 ; i < 10 ; i++) { frames.add(frame[i]); } ここでリストに追加しているframe[i]も全て初期状態ですのでframes.get(1)とかで取り出したFrameクラスもnullになっているはずです。 箱を用意したら実体を格納してあげて下さい。 frame[i] = new Frame();

関連するQ&A

  • [Java]Javaの文法が間違っているのでしょうか・・・?

    6人分の小テストの点数を記録し,平均点,最高点,平均点以下の人の一覧を計算するプログラムを作成したいのです。 入力はコマンドラインから行います。 しかし,TEST配列がうまく初期化がうまく記述できないため,コンパイル時点で”シンボルが見つけられません”というエラーが出てしまいます。 Javaの経験が浅いので、文法そのものが間違っているか心配です。C言語についてはある程度知識がありますから、C言語と対比して教えて頂けたりすると大変たすかります。 宜しくお願い致します。 class Lecture { static Lecture[] TEST; static double avg=0; static int max=0; static int i = 0; static String kamoku; int scorebox; String name; String student_number; Lecture(int size){ TEST = new Lecture[size]; for (int i = 0; i < size; i++) { Exercise a = new Exercise(); Student b = new Student(); TEST[i] = new Lecture(a,b); } } static void add(Exercise score, Student aStudent) { TEST[i].name = aStudent.name; TEST[i].student_number = aStudent.student_number; TEST[i].scorebox = score.score; i++; } static void avg() { int sum=0; for (int i = 0; i < 6; i++) { sum += TEST[i].scorebox; } avg = sum / 6; } static void max() { int max = 0; int temp = 0; for (int i = 0; i < 6; i++) { if (max < TEST[i].scorebox) { temp = i; max = TEST[i].scorebox; } } max = i; } static void show_kamoku(){ System.out.println("科目:"+kamoku); } static void show(){ Lecture.max(); System.out.println("平均点:"+avg); System.out.println("最高得点者:"+TEST[max]); } static void under_avg(){ Lecture.avg(); System.out.println("平均点を下回った者"); for(int i=0 ; i<6 ; i++){ if(avg > TEST[i].scorebox){ System.out.println(TEST[i]); } } } } class Exercise { int score; Exercise(int score) { this.score = score; } Exercise() { } public String toString() { return " 得点:" + score; } } class Student { String name; String student_number; Student(String student_number,String name ) { this.name = name; this.student_number = student_number; } Student() { } public String toString() { return "学籍番号:" + student_number + " 名前:" + name; } } class ExerciseEvaluation { public static void main(String args[]){ Lecture.kamoku=args[0]; Lecture[] lec = new Lecture[6]; Student Y0 = new Student(args[1],args[2]); Exercise X0 = new Exercise(Integer.parseInt(args[3])); lec[0].add(X0, Y0); Student Y1 = new Student(args[4], args[5]); Exercise X1 = new Exercise(Integer.parseInt(args[6])); lec[1].add(X1, Y1); Student Y2 = new Student(args[7], args[8]); Exercise X2 = new Exercise(Integer.parseInt(args[9])); lec[2].add(X2, Y2); Student Y3 = new Student(args[10], args[11]); Exercise X3 = new Exercise(Integer.parseInt(args[12])); lec[3].add(X3, Y3); Student Y4 = new Student(args[13], args[14]); Exercise X4 = new Exercise(Integer.parseInt(args[15])); lec[4].add(X4, Y4); Student Y5 = new Student(args[16], args[17]); Exercise X5 = new Exercise(Integer.parseInt(args[18])); lec[5].add(X5, Y5); Lecture.show_kamoku(); Lecture.show(); Lecture.under_avg(); } }

  • NullPointerExceptionがでてしまいます(TT

    Javaを初めて、数日です。 プログラムを作成していたところ、NullpointerExceptionが出てしまい解決策が見つからず前進できません。 よろしければ、お手をお貸しください。よろしくお願いいたします。 class Book { String name;//書名 String author;//著者名 String publisher;//出版社 /*コンストラクタ*/ Book(String name, String author, String publisher) { this.name = name; this.author = author; this.publisher = publisher; } /*文の文字列化*/ public String toString() { return ("書名" + this.name + ",著者名" + this.author + ",出版社" + this.publisher); } } class BookShelf { static Book[] bookShelf;//本棚のデータ構造 ここでは本の配列 static int index = 0;//本が次に入る本棚の位置(配列の添え字) static int i; static int maxsize; /*コンストラクタ*/ BookShelf(int maxsize) { bookShelf = new Book[maxsize]; } /*本棚に本abookを入れる*/ static void add(Book aBook) { bookShelf[index].name = aBook.name; bookShelf[index].author = aBook.author; bookShelf[index].publisher = aBook.publisher; index++; } /*本棚の本の一覧を標準出力に出力する*/ static void show() { for (i = 0; i < maxsize; i++) { System.out.println(bookShelf[i]); } } /*本棚の文字列化*/ public String toString() { return "書名:" + bookShelf[i].name + ",著者名" + bookShelf[i].author + ",出版社:" + bookShelf[i].publisher; } } class TestBookShelf { public static void main(String args[]) { BookShelf bookshlef1 = new BookShelf(2); Book X = new Book("book1", "tanaka", "SIT1"); BookShelf.add(X); Book Y = new Book("book1", "suzuki", "SIT2"); BookShelf.add(Y); BookShelf.show(); } }

    • ベストアンサー
    • Java
  • 式の型は配列型で int に解決済み。が解けませ。

    こんにちは、学校の課題で重力3目並べを作っていますが、式の型、int型、配列型というところでまったくつまずいてしまっています。どうか課題提出できますようお助けいただけますでしょうか。お願いいたします。私はJUNO eclipsをつかっております。 エラーは、34,50,53,66,118行目で”式の型は配列方でINTに解決済みである必要があります”です。 (申し訳ありません。文字数ぎりぎりで詰めて質問させていただきした。読みづらですがご容赦ください。 package Colonne5; public class Colonne5 { final static int jouer1 = 0; final static int jouer2 = 1; final static char [] pion = new char [] {'*','0', ' '}; final static int vide = 2; static final int PionEtoile = 1; static final int PionRond = -1; final static int Dwidth = 5; final static int Dheight = 5; final static int PreCOL = 0; final static int DerCOL = Dwidth - 1; final static int Hautligne = Dheight - 1; static int Basligne = 0; final static int H = 0 ; final static int V = 1 ; final static int[] HOR = new int[] {1, 0} ; final static int[] VER = new int[] {0, 1} ; final static int[] UP = new int[] {1, 1} ; final static int[] DOWN = new int[] {1, -1} ; final static int[][] DIRECTION = new int[][] {HOR, VER, UP, DOWN} ; private static int[][] damier ; // grid private static int name ; // player name private static char player ; // turn of gamer private static int result ; private static int impactLine ; public Colonne5 (int john){ damier = new int[Dwidth][Dheight]; for (int i = 0 ; i < Dwidth; i++) { for (int j = 0; j < Dheight; j++) { damier[i][j] = vide; } } this.name = john; player = jouer1; result = vide; } private boolean Libre(int column){ //グリッドが空いているか判断 return damier[column][Hautligne]==vide; } private boolean damierRempli() { int column = PreCOL; while (column <= DerCOL) { if (Libre(column)) return true ; column++ ; } return false ; } private void jouerCoup() throws IOException { //ゲーム開始 while (result == vide && damierRempli()) { afficher() ; int column =name[player]; System.out.print("Enter " + (PreCOL + 1) + " to " +(DerCOL +1) + " ?") ; System.in.read(); sommetColonne(column) ; if (coupGagnant(player, impactLine)) result = player ; else demanderCoup() ; } afficher() ; if (result == vide) System.out.print(" partie nulle ") ; else System.out.println(name[result] + " gagne") ; } private boolean coupGagnant (int column, int ligne) { //勝者判断 int i = 0 ; while (i < DIRECTION.length) { if (coupGagnant(column, ligne, DIRECTION[i])) return true ; i++ ; } return false ; } private static boolean coupGagnant(int column, int ligne ,int[] dir) { int nextColumn = column + dir[H] ; int nextLine = ligne + dir[V] ; int forward = 0 ; while (damier[nextColumn][nextLine] == player) { nextColumn += dir[H] ; nextLine += dir[V] ; forward++ ; } nextColumn = column - dir[H] ; nextLine = ligne - dir[V] ; int backward = 0 ; while (damier[nextColumn][nextLine] == player) { nextColumn -= dir[H] ; nextLine -= dir[V] ; backward++ ; } return backward + 1 + forward >= 3 ; } private static int demanderCoup() { //どちらのプレイヤーの順番か判断 if(player==jouer1){ player = jouer2; } else player = jouer1; return player; } private void sommetColonne(int column) { //現在の駒の一番上を取得判断 if(!Libre(impactLine)) throw new RuntimeException(" colonne pleine ") ; impactLine = Hautligne ; while (impactLine > Basligne && damier[Dheight-1][impactLine-1] == vide) impactLine-- ; damier[Basligne][impactLine] = player ; } private void afficher() { //ゲームの表示 for (int column = PreCOL ; column <= DerCOL ; column++) System.out.print("| " + (column + 1) + " "); System.out.println("|"); for (int line = Hautligne ; line >= Basligne ; line--) { for (int column = PreCOL ; column <= DerCOL ; column++) System.out.print("| " + pion[damier[column][line]] + " ") ; System.out.println("|"); } } public static void main(String[] args) { Colonne5 joue = new Colonne5(name) ; joue.jouerCoup(); } }

  • javaの同期について

    javaの同期について package rwlock; public class App1 extends Thread { static private final int REFER = 0; static private final int UPDATE = 1; static private final int[] conf1 = { REFER, REFER, REFER, UPDATE }; static private final int[] conf2 = { REFER, UPDATE, REFER, REFER }; static private MyObj0 mo = new MyObj0(); // App1 + MyObj0 int id; private int[] conf; public App1(int id, int[] conf) { this.id = id; this.conf = conf; } public void run() { long tStart = Time.current(); for (int i = 0; i < conf.length; i++) { switch(conf[i]) { case REFER: mo.refer(); break; case UPDATE: mo.update(); break; default: assert false : "internal error"; } } if (id == 1) { Time.printElapsed(tStart); } } public static void main(String[] args) { App1 th1 = new App1(1, conf1); App1 th2 = new App1(2, conf2); th1.start(); th2.start(); } } public class MyObj0 { private Object countLock = new Object(); private int count; private void enter() { synchronized(countLock) { count++; } } private void leave() { synchronized(countLock) { count--; } } public MyObj0() { count = 0; } public void refer() { enter(); Time.sleep(300); leave(); } public void update() { enter(); synchronized(countLock) { assert count == 1; } Time.sleep(500); leave(); } において、updateの実行中は、他のスレッドでもupdateもreferも実行されないが、二つのスレッドで同時にreferは実行されうるという条件を満たすにはどうしたらよいでしょうか?updateにsynchronizedをつけてみましたが、referが同時に実行されてしまいました

    • ベストアンサー
    • Java
  • javaの同期について

    javaの同期について package rwlock; public class App1 extends Thread { static private final int REFER = 0; static private final int UPDATE = 1; static private final int[] conf1 = { REFER, REFER, REFER, UPDATE }; static private final int[] conf2 = { REFER, UPDATE, REFER, REFER }; static private MyObj0 mo = new MyObj0(); // App1 + MyObj0 int id; private int[] conf; public App1(int id, int[] conf) { this.id = id; this.conf = conf; } public void run() { long tStart = Time.current(); for (int i = 0; i < conf.length; i++) { switch(conf[i]) { case REFER: mo.refer(); break; case UPDATE: mo.update(); break; default: assert false : "internal error"; } } if (id == 1) { Time.printElapsed(tStart); } } public static void main(String[] args) { App1 th1 = new App1(1, conf1); App1 th2 = new App1(2, conf2); th1.start(); th2.start(); } } public class MyObj0 { private Object countLock = new Object(); private int count; private void enter() { synchronized(countLock) { count++; } } private void leave() { synchronized(countLock) { count--; } } public MyObj0() { count = 0; } public void refer() { enter(); Time.sleep(300); leave(); } public void update() { enter(); synchronized(countLock) { assert count == 1; } Time.sleep(500); leave(); } において、updateの実行中は、他のスレッドでもupdateもreferも実行されないが、二つのスレッドで同時にreferは実行されうるという条件を満たすにはどうしたらよいでしょうか?updateにsynchronizedをつけてみましたが、referが同時に実行されてしまいました。

    • ベストアンサー
    • Java
  • 空白にはなにを入れればいいのでしょうか?

    [A君,50,60,70] -> 180 [Bさん,90,70,80] -> 240 [C君,30,40,45] -> 115 という3教科の試験の合計点を学生毎に表示するものですが、<?>の部分になんと書けばいいのかわかりません。。教えてください。 import java.lang.*; import java.io.*; import java.util.*; class Student { private String name; private int[] score; public Student (String name, int[] score){ this.name = name; this.score = score; } public Student(String name, int x, int y, int z){ this.score = new int[3]; } public String toString(){ String s = "[" + name; for (int i=0; i < score.length; i++){ s += “ , “ + score[1]; } s += "]"; return s; } public int total(){ int sum = 0; for (int i=0; i<<?>; i++){ <?> } return sum; } } class StudentTest { public static void main(String[] args){ Student[] data = { new Student("A君",50,60,70), new Student("Bさん",90,70,80), new Student("C君",30,40,45), }; for (int i=0; i<data.length; i++){ System.out.println("" + data[i] + "\t-> " + data[i].total()); } } }  

    • ベストアンサー
    • Java
  • javaのことで

    ---MainPanel.java--- import java.awt.Dimension; import java.awt.Graphics; import java.event.MouseEvent; import java.event.MouseListener; import javax.swing.JPanel; import java.util.Random; public class MainPanel extends JPanel implements MouseListener { public static final int WIDTH = 640; public static final int HEIGHT = 480; private static final int NUM_FILE = 4; private File[] file; private int prev; public MainPanel() { setPreferredSize(new Dimension(WIDTH, HEIGHT)); file = new File[NUM_FILE]; for (int i = 0; i < NUM_FILE; i++) { file[i] = new File(i, this); } select(); addMouseListener(this); } private void clear() { for (int i = 0; i < NUM_FILE; i++) { file[i].delete(); } } private boolean check(int a, int b) { return a == b || a == prev || b == prev; } private void select() { Random rand = new Random(); int a, b; do { a = rand.nextInt(NUM_FILE); b = rand.nextInt(NUM_FILE); } while (check(a, b)); file[a].set(0, 0); file[b].set(file[a].getX() + file[a].getWith() + File.SPACE, 0); } public void paintComponent(Graphics g) { super.paintComponent(g); for (int i = 0; i < NUM_FILE; i++) { if (file[i].isSelected()) { file[i].draw(g); } g.drawString("ファイル" + (i + 1) + " … " + file[i].getCnt(), 0, HEIGHT * 3 / 4 + i * 15); } } public void mouseClicked(MouseEvent e) { int x = e.getX(); int y = e.getY(); for (int i = 0; i < NUM_FILE; i++) { if (file[i].isSelected()) { // 表示されていて // 画像内なら if (x > file[i].getX() && x < file[i].getX() + file[i].getWidth() && y < file[i].getY() && y > file[i].getY() + file[i].getHeight()) { file[i].count(); prev = i; clear(); select(); break; } } } repaint(); } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } } フレームを用意してMainPanelを付加し,pack();してください.

  • ローカル変数にアクセスする複数のスレッドの振る舞いについて

    早速ではございますが、質問をさせていただきます。 以下のコード中のMonitorクラスを複数のスレッドが 共有して自由に入り込んでいるにも関わらす、 排他制御をしていないのにBROKENと表示されません。 final class Main { private final static int NUM = 10; public static void main(String[] args) { Monitor m = new Monitor(); UserThread[] ut = new UserThread[NUM]; Thread[] t = new Thread[NUM]; for(int i=0;i<NUM;i++) { ut[i] = new UserThread(m); t[i] = new Thread(ut[i]); t[i].start(); } } } final class UserThread implements Runnable { private final Monitor m; public UserThread(Monitor m) { this.m = m; } public void run() { System.out.println (Thread.currentThread().getName()+" BEGIN"); while(true) { this.m.func(); } } } final class Monitor { public void func() { int i1 = 0; int i2 = 0; i1++; i2++; if(i1 != i2) { System.out.println ("***** BROKEN ***** " +i1+"と"+i2); } } } 動作確認を2日間くらい行っているのですが、それでも BROKENと表示してくれません。javaの処理系によって 振る舞いがことなるかもしれませんので一概には言えませ んが、いったいなぜBROKENと表示しないのでしょうか? どうかご教授のほどよろしくお願いします。

    • ベストアンサー
    • Java
  • for文について【ID3タグ取得のプログラム】

    ID3タグ取得のプログラムなのですがちゃんと動いたのは良いんですが解らないプログラム部分がありました。 ググったり過去の質問探したりしたのですが解答が見つかりません。 お手数ではありますがご教授願います。 以下はプログラムです。 /*ID3タグ取得プログラム*/ import java.io.*; import java.nio.channels.*; import java.util.Arrays; class TagInfo{ final private String name; final private int pos; final private int len; public TagInfo(String name,int pos,int len){ this.name=name; this.pos=pos; this.len=len; } public String getName() { return name; } public int getPos() { return pos; } public int getLen() { return len; } } public class M_data { private static byte[] copyOfRange(byte b[],int pos, int len){ byte[] a=new byte[len]; System.arraycopy(b,pos,a,0,len); return a; // return java.util.Arrays.copyOfRange(b,pos,pos+len); } static void music() throws IOException{ File file = new File("C:/music/music4.mp3"); FileInputStream fis=new FileInputStream(file); String charsetName="Shift_JIS"; //if(1<args.length) charsetName=args[1]; FileChannel fc=fis.getChannel(); fc.position(fc.size()-128); byte[] b=new byte[128]; if(fis.read(b)==128 && b[0]=='T' && b[1]=='A' && b[2]=='G'){ TagInfo[] infos={new TagInfo("Song title:",3,30),new TagInfo("Artist:",33,30), new TagInfo("Album:",63,30),new TagInfo("Year:",93,4), new TagInfo("Comment:",97,30),new TagInfo("Genre:",127,1) }; int i=0; /*以下のfor文です*/ for(TagInfo info: infos){ System.out.print(i + info.getName()); System.out.println(new String(copyOfRange(b,info.getPos(),info.getLen()),charsetName)); i++; } } } public static void main(String[] args) throws IOException{ music(); } }

    • ベストアンサー
    • Java
  • カスタムコンポーネントのプロパティ

    いつもお世話になっております。 Java(swing)でカスタムコンポーネントを作成する 勉強をしています。 以下のようなラベルを敬称するコントロールを作成しました。 作成したラベルのプロパティにて fontSizeに0または1または2を入力するとフォントサイズが 変更するようにしましが、 プロパティで0,1,2のように数字を入力するのではなく リスト選択(SMALL,MEDIUM,LARGE)にて選択させるには どのようにしたらよいでしょうか? よろしくお願いします。 public class TestJLabel extends JLabel { public static final int SMALL = 0; public static final int MEDIUM = 1; public static final int LARGE = 2; private int size = SMALL; public int getFontSize() { return this.size; } public void setFontSize(int size) { this.size = size; if (size == SMALL){ this.setFont(new Font("MS ゴシック", Font.PLAIN, 10)); } else if (size == MEDIUM){ this.setFont(new Font("MS ゴシック", Font.PLAIN, 18)); } else { this.setFont(new Font("MS ゴシック", Font.PLAIN, 36)); } } }