• 締切済み

javaの課題でjava.lang.NullPointerExcept

javaの課題でjava.lang.NullPointerException というエラーが出て困っています いろいろ調べてやってみたのですがどうしても解決しないのでお願いします class ShoppingBag { private ShoppingBag[] Bag; private String name; private int price; private int sum; private int iLength; public ShoppingBag() { this.Bag = new ShoppingBag[20]; this.iLength = 0; } public void add(Shampoo bag) { this.Bag[iLength].price = bag.getPrice(); this.Bag[iLength].name = bag.getName(); sum += bag.getPrice(); iLength++; } public void add(Pc bag) { this.Bag[iLength].price = bag.getPrice(); this.Bag[iLength].name = bag.getName(); sum += bag.getPrice(); iLength++; } public void add(Book bag) { Bag[iLength].price = bag.getPrice(); this.Bag[iLength].name = bag.getName(); sum += bag.getPrice(); iLength++; } public int getSumPrice() { return sum; } public void printList() { for(int i = 0; i <iLength; i++){ } } } でthis.Bag[iLength].price =で代入するところでエラーが出ます

みんなの回答

  • askaaska
  • ベストアンサー率35% (1455/4149)
回答No.1

変数がnullだからよ。 this.Bag = new ShoppingBag[20]; この時点では ShoppingBag のインスタンスは生成していないの。 別途生成してあげないといけないわ。

looln
質問者

お礼

わかりました。 早速やってきます ありがとうございました!

全文を見る
すると、全ての回答が全文表示されます。

関連するQ&A

  • ArrayListを使ったJavaコンパイルがうまくいかない

    題名どおりなのですが、まず以下のようなソースを 書きました。 import java.util.*; class Rab{ private String name; private int number; public Rab(){ name= ""; number=0; } public void setName(String name){ this.name=name; } public void setNumber(int number){ this.number=number; } public String getName(){ return name; } public int getNumber(){ return number; } } public class Rabexc{ public static void main(String[] args){ Rab[] rab=new Rab[5]; for(int i=0; i<5; i++){ rab[i]=new Rab(); } rab[0].setName("Owner"); rab[1].setName("Adminstrator"); rab[0].setNumber(1); rab[1].setNumber(2); ArrayList al=new ArrayList(); al.add(rab[0]); al.add(rab[1]); for(int i=0; i<al.size(); i++){ rab[i]=(Rab)al.get(i); System.out.println("name: "+rab[i].getName()+"number: "+rab[i].getNumber()); } } } これを実行してみたところ、 Rabexc.java:41: 警告:[unchecked] raw 型 java.util.ArrayList のメンバとしての add (E) への無検査呼び出しです。 al.add(rab[0]); ^ Rabexc.java:42: 警告:[unchecked] raw 型 java.util.ArrayList のメンバとしての add (E) への無検査呼び出しです。 al.add(rab[1]); ^ 警告 2 個 という警告が出てコンパイルできません。 サイト・参考書なども調べて考えていたのですが、いまいち問題の解決法が浮かばないため、詳しい方いましたら教えていただけると幸いです。 宜しくお願い致します。

  • List配列の検索

    インスタンス化されているJavaBeanがArrayListに数百~数千入っています。その配列から特定のJavaBeanのメンバーの内容が一致しているオブジェクトだけ取り出したいです。イテレーターを使って1個1個取り出してチェックして・・・というプログラムをゴリゴリ書いても良いのですが、SQLみたいに一致した条件のオブジェクトをまとめて取得するなんて事はできないのでしょうか? --- Goods.java --- import java.io.*; public class Goods implements Serializable{ private String name; private double price; private int stock; public Goods(){ } public Goods( String name, double price, int stock ){ this.name = name; this.price = price; this.stock = stock; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public int getStock() { return stock; } public void setStock(int stock) { this.stock = stock; } } というBeanがあり、仮に下記ロジックでaddし検索 --- mainlogic --- ArrayList<Goods> goodsList = new ArrayList<Goods>(); goodsList.add( new Goods("ABC",123,10) ); goodsList.add( new Goods("DEF",456, 0) ); // ←該当オブジェクト goodsList.add( new Goods("GHI",789,15) ); goodsList.add( new Goods("JKL",987, 0) ); // ←該当オブジェクト ・・・ // ここでgoodsListに入っているGoodsオブジェクトのメンバーstock(在庫数)が0のGoodsオブジェクトを取得したい ・・・ という感じなのですが、SQLなら"SELECT * FROM goodsList WHERE Goods.stock = 0"で簡単に抽出できるのですが、このような事ってできないですよね? やはり、イテレーターで全件検索か、一旦、オブジェクトをDBに書き出して取り出すという事しかできないですよね? 他に何か良い方法などありましたら、ご教授お願い致します。

  • JAVAのComparableについて・・・

    compareto()を使って名前、身長、体重を「身長昇順」拡張for文でだしたいのですが・・・ (1)returnを使って何を返せばいいのか? (2)System.out.println()でなにをすればいいのか? (3)他の文で間違っているのか? この3点が分かりません。JAVAに詳しい方よろしくお願いします。。。 package class; public class NewClass { public static void main(String[] args) { NewClass2 A = new NewClass2("aaa", 160, 40); NewClass2 B = new NewClass2("bbb", 170, 60); NewClass2 C = new NewClass2("ccc", 150, 70); System.out.println("---Comparable---"); Set<Comparable> ts3 = new TreeSet<Comparable>(); ts3.add(A); ts3.add(B); ts3.add(C); for(Comparable cm : ts3) { System.out.println(?????????????); } package class; public class NewClass2 implements Comparable< NewClass2> { private String name; private int Weight; private int Height; public String getName() { return this.name; } public void setName(String name) { this.name = name; } public int getWeight() { return this.Weight; } public void setWeight(int Weight) { this.Weight = Weight; } public int getHeight() { return this.Height; } public void setHeight(int Height) { this.Height = Height; } public StudentBean(String name, int Height, int Weight) { this.name = name; this.Weight = Weight; this.Height = Height; } @Override public int compareTo(Object arg0) { StudentBean sb = (StudentBean)arg0;     String name1 = this.name; int Height1 = this.Height; int Weight1 = this.Weight;     int returnval = 0; if(Height1 > sb.getHeight()) { returnval = 1; } else if(Height1 < sb.getHeight()) { returnval = -1; } else returnval = 0; } return ???????; } 文は以上です 出力は aaa 160 40 ・ ・ ・ なかんじでお願いします。

  • JAVAのComparableについて・・・

    compareto()を使って名前、身長、体重を「身長昇順」拡張for文でだしたいのですが・・・ (1)returnを使って何を返せばいいのか? (2)System.out.println()でなにをすればいいのか? (3)他の文で間違っているのか? この3点が分かりません。JAVAに詳しい方よろしくお願いします。。。 package class; public class NewClass { public static void main(String[] args) { NewClass2 A = new NewClass2("aaa", 160, 40); NewClass2 B = new NewClass2("bbb", 170, 60); NewClass2 C = new NewClass2("ccc", 150, 70); System.out.println("---Comparable---"); Set<Comparable> ts3 = new TreeSet<Comparable>(); ts3.add(A); ts3.add(B); ts3.add(C); for(Comparable cm : ts3) { System.out.println(?????????????); } package class; public class NewClass2 implements Comparable< NewClass2> { private String name; private int Weight; private int Height; public String getName() { return this.name; } public void setName(String name) { this.name = name; } public int getWeight() { return this.Weight; } public void setWeight(int Weight) { this.Weight = Weight; } public int getHeight() { return this.Height; } public void setHeight(int Height) { this.Height = Height; } public StudentBean(String name, int Height, int Weight) { this.name = name; this.Weight = Weight; this.Height = Height; } @Override public int compareTo(Object arg0) { StudentBean sb = (StudentBean)arg0;     String name1 = this.name; int Height1 = this.Height; int Weight1 = this.Weight;     int returnval = 0; if(Height1 > sb.getHeight()) { returnval = 1; } else if(Height1 < sb.getHeight()) { returnval = -1; } else returnval = 0; } return ???????; } 文は以上です 出力は aaa 160 40 ・ ・ ・ なかんじでお願いします。

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

  • 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について教えてください!

    public class Number{ private final String noo; private int ct; public Number(String noo){this.noo = noo;} public String getName(){return noo;} public void increment(){ct++;} public int getCount(){return ct;} public void reset(){ct = 0;} } このクラスを複数スレッドで使うためには、reset()とgetName()とgetCount()をsyncronizedで宣言すれば可能ですか?

    • ベストアンサー
    • Java
  • またしてもjava.until.Mapに関してです

    いつもお世話になっております。以前質問したjava.until.Mapに関してですが、以下のプログラムのjava.until.List部分を変えるとどういった風になるのでしょうか? 何卒ご回答よろしくお願い致します。 class CustomerManager { public static void main(String[] args){ CustomerManager manager = new CustomerManager(); manager.addCustomerCard( "山田一郎"); manager.addCustomerCard( "鈴木太郎"); manager.addCustomerCard( "田中次郎"); manager.printAllInfo(); } private List<CustomerCard> customers = new ArrayList<CustomerCard>(); private int index = 0; public void addCustomerCard(String name){ customers.add(new CustomerCard(1 + index,name)); index++; } public void printAllInfo() { for(CustomerCard cc : customers){ System.out.print("ID =" + cc.id + ","); System.out.println("名前 =" + cc.name); } } } class CustomerCard { String name; int id; public CustomerCard(int id,String name){ this.name = name; this.id = id; } public String getName(){ return this.name; } }

    • ベストアンサー
    • Java
  • java.lang.ClsaaCastExceptionで教えてください。

    以下はiアプリで画像を3枚順番に表示し、3番目の画像が表示されたときに選択キーを押すと点数が加算される内容です。 コンパイルは通りましたが、エミュレータで実行すると、Main:java. lang.ClassCastException AnimeIAppというエラーが出ます。 ご指導お願いいたします。 import com.nttdocomo.ui.*; public class AnimeIApp extends IApplication{ public void start(){ Display.setCurrent (new AnimeCanvas()); } } public class AnimeCanvas extends Canvas implements Runnable{ int imgInx; Image[] imgs; boolean isStopped; int score=0; Image animeImg[]=new Image[3]; MediaImage mI; public AnimeCanvas(){ for(int i=0;i<3; i++){ mI=MediaManager.getImage("resource:///"+i+".gif"); try {mI.use();} catch(Exception e){} } doStart(); } private void doStart(){ isStopped=false; Thread th=new Thread(this); th.start(); } private void doStope(){ isStopped=true; } public void run(){ imgInx=0; while(! isStopped){ try{ repaint(); Thread.sleep(500); imgInx++; if(imgInx>=imgs.length){ imgInx=0; } }catch(Exception e){} } } public void precessEvent(int type,int param){ if(type==Display.KEY_PRESSED_EVENT){ if(param==Display.KEY_SELECT && imgInx==2){ score++; } } } public void paint(Graphics g){ g.setColor(g.getColorOfRGB(255,255,255)); g.fillRect(0,0,getWidth(),getHeight()); g.drawImage(imgs[imgInx],0,0); g.setColor(g.getColorOfRGB(0,0,0)); g.drawString("スコア"+ score ,100,100); } }

  • java.lang.NullPointerException

    java初心者です。 ******************************************* Exception in thread "main" java.lang.NullPointerException at Region2.<init>(Region2.java:7) at Region2.main(Region2.java:11) ******************************************* というエラーで困っています。 ソースは、 ******************************************* import java.io.*; public class Region2 {  public Test[] t = new Test[10];  public Region2(){   t[0].x = 1;//ココ   System.out.println(t[0].x);  }  public static void main(String[]args){   Region2 reg = new Region2();//ココ   System.out.println(reg.t[0].x);   System.exit(0);  } } class Test{  public int x;  public Test (int x){//xをセット   this.x = x;  }  public void Show () {//xを表示   System.out.println(x);  } } **************************************** 見ての通りのプログラムで、あまり意味のないものですが、オブジェクトの配列の動作をテストしています。でずが、「ココ」とコメントしたところでたたかれてしまいます。私は恥ずかしながら「え?何でダメなの?」という感じです。 何がいけないのか、もしくはどうすれば、 1 1 と表示されるか、どなたかアドバイスください。

    • ベストアンサー
    • Java