开发者社区 问答 正文

使用Scanner输入报错。。。?报错

package com.text1; import java.util.Scanner; public class Text2 { public static void main(String[] args) { Scanner a=new Scanner(System.in); //定义对象数组 Dog dogs[]=new Dog[4]; //给狗赋初值 for(int i=0;i<4;i++) { //输入狗名 System.out.print("请输入第"+(i+1)+"只狗名:"); dogs[i].SetName(a.next()); //输入体重 System.out.print("请输入第"+(i+1)+"只狗的重量:"); dogs[i].SetWeight(a.nextInt()); } System.out.println("输出:"); //平均体重 float weightall=0; for(int i=0;i<4;i++) { weightall+=dogs[i].GetWeight(); } float avgWeight=weightall/dogs.length; System.out.print("总体重为:"+weightall+"平均体重:"+avgWeight); } } class Dog { private String name; private float weight; public String GetName() { return name; } public float GetWeight() { return weight; } public void SetName(String name) { this.name=name; } public void SetWeight(float weight) { this.weight=weight; } } 运行后为什么提示“Exception in thread "main" java.lang.NullPointerException at com.text1.Text2.main(Text2.java:18)”。。。。 本人新手。。。。。。求高手

展开
收起
爱吃鱼的程序员 2020-06-22 21:58:14 443 分享 版权
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB

    dogs[i]=newDog();

    2020-06-22 21:58:30
    赞同 展开评论
问答地址: