我的这段java代码为什么会报空指针?

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq511tv/article/details/79640586

这是学生类

package com.lianxi.com;


public class Student{

private int on;   //学生编号

private String name;   //学生名字

private int age;   //年龄

private double java;  //java成绩

private double C;   //c语言成绩

private double HTML;   //html成绩

private double SQL;   //sql 成绩

private double sum;   //总分

private double avg;   //平均分


public int getOn() {

return on;

}

public void setOn(int on) {

this.on = on;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public int getAge() {

return age;

}

public void setAge(int age) {

this.age = age;

}

public double getJava() {

return java;

}

public void setJava(double java) {

this.java = java;

}

public double getC() {

return C;

}

public void setC(double c) {

this.C = c;

}

public double getHTML() {

return HTML;

}

public void setHTML(double hTML) {

this.HTML = hTML;

}

public double getSQL() {

return SQL;

}

public void setSQL(double sQL) {

this.SQL = sQL;

}

public double getSum() {

return sum = this.java+this.C+this.HTML+this.SQL;   //总分

}

public double getAvg() {

return avg = this.sum/4 ;  //平均分

}

String msg;

public String toString() {   //改写toString方法

msg = this.on+"\t"+this.name+"\t"+this.age+"\t"+this.java+"\t"+this.C+"\t"+this.HTML+"\t"

+this.SQL+"\t"+this.sum+"\t"+this.avg;

return msg;

}

}

这是方法类:===========================================华丽的分割线

package com.lianxi.com;


public class Admin {

String msg = "编号"+"\t"+"姓名"+"\t"+"年龄"+"\t"+"java"+

"\t"+"C#"+"\t"+"HTML"+"\t"+"SQL"+"\t"+"总分"+"\t"+"平均分";


public void print(Student[] stu) {  //打印的方法 传进学生数组 


System.out.println(msg); 

for(int i=0;i<stu.length;i++) {

if(stu[i] != null) {  //判断学生数组非空的 然后打印出来

System.out.println(stu[i]);

}

}

}

public void ten(String name,int age,Student[] stu) {  

//重点了 就是这个方法报错了 在主函数中 调用了这个方法 传进名字 年龄 学生数组

if(this.setIndex(stu) == 99999) { //setIndex这个方法在下面

System.out.println("你已经输入完了");

}else {}

stu[this.setIndex(stu)].setName(name); //给 返回的为空的数组下标 放置名字

stu[this.setIndex(stu)].setAge(age); //放置年龄

stu[this.setIndex(stu)].setOn(this.setIndex(stu)); //放置编号

this.print(stu);     //打印

}

public int setIndex(Student[] stu) {//返回为空的下标

for(int i = 0; i<stu.length;i++) {

if(stu[i] == null) {

return i;

}

}

return 99999;

}

}

割==============================================这是执行类:

package com.lianxi.com;


import java.util.Scanner;


public class Test{

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

System.out.println("---请输入学生人数---");

int num = in.nextInt();

while(true) {

System.out.println("---你要执行的功能---");

System.out.println("10:添加一个学生");

System.out.println("11:查找一个学生");

System.out.println("12:根据学生编号更新学生的基本信息");

System.out.println("13:根据学生编号删除学生");

System.out.println("14:根据编号输入学生的各门成绩");

System.out.println("15:根据某一门成绩进行排序");

System.out.println("16:根据总分进行排序");

System.out.println("99:退出系统");

int a = in.nextInt(); //你要执行的操作 对应的编号

Student[] jjyynew Student[num]; //学生数组

Admin adminnew Admin(); 

switch(a) {

case 10: //10为添加一个学生

System.out.println("请输入学生的姓名");

String name = in.next();

System.out.println("请输入学生的年龄");

int age = in.nextInt();

admin.ten(nameagejjyy); //给传进名字 年龄 和学生数组

//admin.print(jjyy);

break;


default:

break;

}

}

}

}





展开阅读全文

ServletActionContext.getRequest()为什么会报空指针

10-13

做一个项目的时候,用到了HttpSessionBindingListener监听session失效rn当运行valueBound的时候可以正常获取request,而当session失效运行valueUnbound的时候,获取request就会报空指针错误rn代码如下:rn[code=Java]public class SessionListener implements HttpSessionBindingListenerrn private User userObject;rn public SessionListener(User userObject) rn // TODO Auto-generated constructor stubrn this.userObject = userObject;rn rn //用户存sessionrn public void valueBound(HttpSessionBindingEvent event) rn // TODO Auto-generated method stubrn HttpSession session = event.getSession();rn session.setAttribute("userInfo", userObject);rn DateFormat df = DateFormat.getDateTimeInstance();rn System.out.println(df.format(new Date())+"绑定数据源:"+userObject.getUserName()+":"+session.getId()+":"+session.getCreationTime());rn try rn //这里就不会报错..奇怪rn System.out.println("测试一下获取request");rn HttpServletRequest request = ServletActionContext.getRequest();rn HttpSession session1 = request.getSession();rn catch (Exception e) rn // TODO: handle exceptionrn e.printStackTrace();rn rn rn rn // 用户SESSION失效,重新封装用户信息rn public void valueUnbound(HttpSessionBindingEvent event) rn //这里就会报错..rn HttpServletRequest request = ServletActionContext.getRequest();rn HttpSession session = request.getSession();rn rn rn public static String getCookieValue(Cookie[] cookies,String cookieName,String defaultValue) rn for(int i=0; i 论坛

为什么log会报空指针异常错误?

05-16

我在编写添加背景音乐的程序时,参考了这里的代码http://apps.hi.baidu.com/share/detail/18496230rnrn我的工程中有两个类,一个是music类,继承activity,另一个是musicServer类,集成service。music类如下:rn[code=Java]package mx.music;rnrnimport android.app.Activity;rnimport android.content.Intent;rnimport android.os.Bundle;rnimport android.view.View;rnimport android.view.View.OnClickListener;rnimport android.widget.Button;rnrnpublic class music extends Activity rn /** Called when the activity is first created. */rn rn [color=#FF0000]private Intent intent = new Intent("mx.music.MUSIC");[/color]rn private Button startButton;rn private Button stopButton;rn @Overridern public void onCreate(Bundle savedInstanceState) rn super.onCreate(savedInstanceState);rn setContentView(R.layout.main);rn startButton = (Button) findViewById(R.id.startButton);rn stopButton = (Button) findViewById(R.id.stopButton);rn startButton.setOnClickListener(new startListener());rn stopButton.setOnClickListener(new stopListener());rn rn rn rn rn class startListener implements OnClickListenerrnrn public void onClick(View v) rn // TODO Auto-generated method stubrn [color=#FF0000] startService(intent);[/color]rn rn rn rn rn class stopListener implements OnClickListenerrnrn public void onClick(View v) rn // TODO Auto-generated method stubrn [color=#FF0000]stopService(intent);[/color]rn rn rn rn rn @Overridern protected void onPause() rn // TODO Auto-generated method stubrn super.onPause();rn rn rn rn rn rn rnrn[/code]rnrnmusicserver类如下:[code=Java]rnpackage mx.music;rnrnimport android.app.Service;rnimport android.content.Intent;rnimport android.media.MediaPlayer;rnimport android.os.IBinder;rnrnpublic class musicServer extends Servicernrn private MediaPlayer mp;rn @Overridern public IBinder onBind(Intent arg0) rn // TODO Auto-generated method stubrn return null;rn rn @Overridern public void onStart(Intent intent, int startId) rn // TODO Auto-generated method stubrn super.onStart(intent, startId);rn if(mp==null)rn mp=MediaPlayer.create(this, R.raw.mmp);rn [color=#FF0000]mp.start();[/color]/*显示这里空指针异常,但是我在上句都已经定义了啊,并且在raw中存在mmp的MP3文件*/rn rn rn @Overridern public void onDestroy() rn // TODO Auto-generated method stubrn super.onDestroy();rn mp.stop();rn rn rn rnrnrn[/code] 论坛

这段代码为什么会报空指针异常

03-29

服务器端:public void registerNewUser() rn //将用户信息插入数据库中的sql语句rn String sql = "INSERT INTO USER_INFO (accNUM,NAME,PASSWORD," +rn "SIGN,PIC,SEX,EMAIL,BIRTHDAY) VALUES(?,?,?,?,?,?,?,?)";rn //读取qq号码的sql语句rn String sql2 = "SELECT accNUM FROM ACCNUM WHERE ID = 1";rn Statement stmt = null;rn ResultSet rs = null;rn try rn stmt = conn.createStatement();rn rs = stmt.executeQuery(sql2);rn rs.next();rn int acc = rs.getInt("accNUM");rn PreparedStatement pre1 = conn.prepareCall(sql);rn acc += 1; //将QQ号加1rn //下面读取客户端发来的信息rn String name = in.readUTF();rn String password = in.readUTF();rn //String ip = in.readUTF();rn String sign = in.readUTF();rn String pic = in.readUTF();rn String sex = in.readUTF();rn String email = in.readUTF();rn String birthday = in.readUTF();rn pre1.clearParameters();rn pre1.setInt(1, acc);rn pre1.setString(2, name);rn pre1.setString(3, password);rn //pre1.setString(4, ip);rn pre1.setString(4, sign);rn pre1.setString(5, pic);rn pre1.setString(6, sex);rn pre1.setString(7, email);rn pre1.setString(8, birthday);rn System.out.println(sql);rn pre1.executeUpdate();rn //更改QQ号的sql语句rn String sql3 = "UPDATE ACCNUM SET accNUM = ? WHERE ID = 1";rn PreparedStatement pre2 = conn.prepareCall(sql3);rn pre2.clearParameters();rn pre2.setInt(1, acc);rn pre2.executeUpdate();rn out.writeUTF("registerOver");rn //向用户返回注册的QQ号rn out.writeInt(acc);rn rs.close();rn stmt.close();rn catch (Exception ex) rn try rn out.writeUTF("registerFail");rn catch (IOException ex1) rn ex1.printStackTrace();rn rn ex.printStackTrace();rn rn rnrnrnrnrnrn客户端: public long registerNewUser(String name, String password, String sign,String pic, String sex, String email,String birthday) rn long acc = 0;rn String serverInfo = "";rn try rn rn Socket socket = new Socket(logAddress, serverPort);rnrn DataInputStream in = new DataInputStream(socket.getInputStream());rn DataOutputStream out = new DataOutputStream(socket.getOutputStream());rn out.writeUTF("registerNewUser");rn out.writeUTF(name);rn out.writeUTF(password);rn out.writeUTF(sign);rn out.writeUTF(pic);rn out.writeUTF(sex);rn out.writeUTF(email);rn out.writeUTF(birthday);rn serverInfo = in.readUTF();rn if (serverInfo.equals("registerFail")) rn return 0;rn else rn acc = in.readInt();rn rn catch (IOException ex) rn ex.printStackTrace();rn rn return acc;rn 论坛

listview下滑会报空指针

04-06

package jp.co.tre.pacer.shelfcheck;rnrnimport java.util.ArrayList;rnimport java.util.HashMap;rnimport java.util.List;rnrnimport jp.co.tre.pacer.shelfcheck.R;rnimport jp.co.trejapan.pacer.android.activity.PacerMainActivity;rnimport jp.co.trejapan.pacer.android.ui.FooterAdapter;rnimport android.content.Context;rnimport android.content.Intent;rnimport android.os.Bundle;rnimport android.view.LayoutInflater;rnimport android.view.View;rnimport android.view.ViewGroup;rnimport android.view.View.OnClickListener;rnimport android.widget.AdapterView;rnimport android.widget.AdapterView.OnItemClickListener;rnimport android.widget.ListView;rnimport android.widget.TextView;rnrnpublic class NewShelfReferActivity extends PacerMainActivity rn private List> list = new ArrayList>(); // 声明列表容器rn private HashMap item1 = new HashMap();rn private ListAdapter dataAdapter;rn private ListView listView;rn private TextView title;rn private int selectedPosition = 0;rnrn @Overridern public void onCreate(Bundle savedInstanceState) rnrn super.onCreate(savedInstanceState);rn setContentView(R.layout.shelf_refer);rn titleLayout.setTitleText(getString(R.string.title_name));rn pageinit();rn listInit();rn setFooterStyle();rn rnrn public void pageinit() rn listView = (ListView) findViewById(R.id.mylist_refer);rn title = (TextView) findViewById(R.id.title1);rn Intent intent = getIntent();rn String name = intent.getStringExtra("name");rn title.setText(name);rn for (int i = 0; i < 10; i++) rn HashMap skt = new HashMap();rn skt.put("name", "lll" + i);rn skt.put("id", "8101" + i);rn list.add(skt);rn rn rnrn public void listInit() rnrn dataAdapter = new ListAdapter(NewShelfReferActivity.this, list,rn R.layout.list_shelf_refer, new String[] "name", "id" ,rn new int[] R.id.shelfname, R.id.shelfno ) rn class ViewHolder rn TextView sname;rn TextView sno;rn rnrn public View getView(final int position, View convertView,rn ViewGroup parent) rn ViewHolder holder = null;rn View view = convertView;rn if (view == null) rn LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);rn view = inflater.inflate(R.layout.list_shelf_refer, null,rn false);rn holder = new ViewHolder();rn holder.sname = (TextView) view.findViewById(R.id.shelfname);rn holder.sno = (TextView) view.findViewById(R.id.shelfno);rnrn else rn holder = (ViewHolder) view.getTag();rn rn HashMap record = list.get(position);rn holder.sname.setText(record.get("name"));rn holder.sno.setText(record.get("id"));rn dataAdapter.notifyDataSetChanged();rn return view;rn rnrn ;rnrn listView.setAdapter(dataAdapter);rn listView.setOnItemClickListener(new OnItemClickListener() rnrn @Overridern public void onItemClick(AdapterView arg0, View arg1, int arg2,rn long arg3) rn selectedPosition = arg2;rn item1 = list.get(selectedPosition);rn Intent intent = new Intent();rn intent.setClass(NewShelfReferActivity.this,rn NewShelfLoginActivity.class);rn intent.putExtra("name", item1.get("name"));rn intent.putExtra("id", item1.get("id"));rn startActivity(intent);rnrn rn );rn rnrn // btn定义rn private void setFooterStyle() rn String[] btnText = new String[4];rn btnText[0] = getString(R.string.back);rn btnText[1] = "";rn btnText[2] = "";rn btnText[3] = "";rnrn OnClickListener[] listenner = new OnClickListener[4];rn listenner[0] = new OnClickListener() rnrn @Overridern public void onClick(View v) rn finish();rn System.exit(0);rn rn ;rnrn listenner[1] = new OnClickListener() rnrn @Overridern public void onClick(View v) rn rn ;rn listenner[2] = null;rn listenner[3] = new OnClickListener() rnrn @Overridern public void onClick(View arg0) rn // TODO Auto-generated method stubrnrn rnrn ;rn FooterAdapter adapter = new FooterAdapter(this, btnText, listenner);rn footer.setAdapter(adapter);[code=java][/code]rnrn rnrn 论坛

为什么我的会报NullPointerException

07-26

rn首先这个是我的JSP页面:rnrn<%@ page language="java" pageEncoding="UTF-8"%>rn<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>rnrn rn 美讯购物网rn rn rn rn 商品添加页面rn rn rn rn rn rn rn 商品名称:rn rn *rn rn rnrnrn rn rn 商品单价:rn *rn rn rnrn rn rn 商品图片:rn rn rnrn rn rn 是否推荐:rn 是 rn 否rn rn rn 是否有效:rn rn 是 rn 否rn rn rn rn rn 商品类别:rn rn rn $category.ctypern rn rn rn rn rn 产品描述:rn rn rn rnrn rn 详细介绍:rn rn rn rn rn rn rn rn rn rn rn rnrnrnrnrnrn这个是我的Servletrn public void doPost(HttpServletRequest request, HttpServletResponse response)rn throws ServletException, IOException rn String status = request.getParameter("status");rn if(status.equals("saveGoodss")) //这里有问题rn Goods goods = new Goods();rn goods.setGname(request.getParameter("gname"));rn String str = request.getParameter("gprice");rn double gprice = Double.parseDouble(str);rn goods.setGprice(gprice);rn goods.setGpic(request.getParameter("gpic"));rn goods.setGiscommend(Boolean.parseBoolean(request.getParameter("giscommend")));rn goods.setGisopen(Boolean.parseBoolean(request.getParameter("gisopen")));rn goods.setCategory((Category)request.getSession().getAttribute("category"));rn goods.setGremark(request.getParameter("gremark"));rn goods.setGxremark(request.getParameter("gxremark"));rn goodsImpl.saveGoods(goods);rn response.sendRedirect("/t31/admin/saveGoods.jsp");rn rn 论坛

java代码出现异常,空指针

05-30

package view;rnrnimport java.awt.BorderLayout;rnimport java.awt.EventQueue;rnrnimport javax.swing.JFrame;rnimport javax.swing.JPanel;rnimport javax.swing.border.EmptyBorder;rnimport javax.swing.JLabel;rnimport java.awt.Font;rnimport java.awt.event.ActionEvent;rnimport java.awt.event.ActionListener;rnimport java.sql.Connection;rnimport java.sql.PreparedStatement;rnimport java.sql.SQLException;rnimport java.sql.Statement;rnrnimport javax.swing.JTextField;rnimport javax.swing.JButton;rnimport util.*;rnrnpublic class AddStuView extends JFrame rnrn private JPanel contentPane;rn private JTextField stuidField;rn private JTextField stunameField;rn private JTextField sexField;rn private JTextField snativeField;rn private JTextField phoneField;rn private JTextField classField;rn private JTextField gradeField;rn private JTextField majorField;rn private JTextField collegeField;rn rn private Connection con = null;rn private Statement stmt = null;rn // private PreparedStatement pstmt = null;rn /**rn * Launch the application.rn */rn public static void main(String[] args) rn EventQueue.invokeLater(new Runnable() rn public void run() rn try rn AddStuView frame = new AddStuView();rn frame.setVisible(true);rn catch (Exception e) rn e.printStackTrace();rn rn rn );rn rnrn /**rn * Create the frame.rn */rn public AddStuView() rn setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);rn setBounds(100, 100, 450, 320);rn contentPane = new JPanel();rn contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));rn setContentPane(contentPane);rn contentPane.setLayout(null);rn rn JLabel label = new JLabel("\u6DFB\u52A0\u5B66\u751F\u4FE1\u606F");rn label.setFont(new Font("宋体", Font.PLAIN, 18));rn label.setBounds(177, 10, 113, 36);rn contentPane.add(label);rn rn JLabel label_1 = new JLabel("\u5B66 \u53F7 \uFF1A");rn label_1.setBounds(27, 60, 54, 15);rn contentPane.add(label_1);rn rn stuidField = new JTextField();rn stuidField.setBounds(78, 57, 121, 21);rn contentPane.add(stuidField);rn stuidField.setColumns(10);rn rn JLabel label_2 = new JLabel("\u59D3 \u540D \uFF1A");rn label_2.setBounds(27, 96, 54, 15);rn contentPane.add(label_2);rn rn stunameField = new JTextField();rn stunameField.setColumns(10);rn stunameField.setBounds(78, 93, 121, 21);rn contentPane.add(stunameField);rn rn JLabel label_3 = new JLabel("\u6027 \u522B \uFF1A");rn label_3.setBounds(27, 134, 54, 15);rn contentPane.add(label_3);rn rn sexField = new JTextField();rn sexField.setColumns(10);rn sexField.setBounds(78, 131, 121, 21);rn contentPane.add(sexField);rn rn JLabel label_4 = new JLabel("\u7C4D \u8D2F \uFF1A");rn label_4.setBounds(27, 169, 54, 15);rn contentPane.add(label_4);rn rn snativeField = new JTextField();rn snativeField.setColumns(10);rn snativeField.setBounds(78, 166, 121, 21);rn contentPane.add(snativeField);rn rn JLabel label_5 = new JLabel("\u7535 \u8BDD \uFF1A");rn label_5.setBounds(27, 201, 54, 15);rn contentPane.add(label_5);rn rn phoneField = new JTextField();rn phoneField.setColumns(10);rn phoneField.setBounds(78, 198, 121, 21);rn contentPane.add(phoneField);rn rn JLabel label_6 = new JLabel("\u73ED \u7EA7 \uFF1A");rn label_6.setBounds(231, 56, 54, 15);rn contentPane.add(label_6);rn rn classField = new JTextField();rn classField.setColumns(10);rn classField.setBounds(286, 56, 121, 21);rn contentPane.add(classField);rn rn JLabel label_7 = new JLabel("\u5E74 \u7EA7 \uFF1A");rn label_7.setBounds(231, 96, 54, 15);rn contentPane.add(label_7);rn rn gradeField = new JTextField();rn gradeField.setColumns(10);rn gradeField.setBounds(286, 93, 121, 21);rn contentPane.add(gradeField);rn rn JLabel label_8 = new JLabel("\u4E13 \u4E1A \uFF1A");rn label_8.setBounds(231, 134, 54, 15);rn contentPane.add(label_8);rn rn majorField = new JTextField();rn majorField.setColumns(10);rn majorField.setBounds(286, 131, 121, 21);rn contentPane.add(majorField);rn rn JLabel label_9 = new JLabel("\u5B66 \u9662 \uFF1A");rn label_9.setBounds(231, 169, 54, 15);rn contentPane.add(label_9);rn rn collegeField = new JTextField();rn collegeField.setColumns(10);rn collegeField.setBounds(286, 166, 121, 21);rn contentPane.add(collegeField);rn rn JButton savebutton1 = new JButton("\u4FDD\u5B58");rn savebutton1.setBounds(192, 249, 93, 23);rn contentPane.add(savebutton1);rn rn //为savebutton1添加监听器rn savebutton1.addActionListener(b1);rn rn //为savebutton1创建监听器rn private ActionListener b1 = new ActionListener()rnrn public void actionPerformed(ActionEvent e) rn // TODO Auto-generated method stubrn con = CommonaJdbc.conection;rn String sql = "insert into student values('"+stuidField.getText()rn +"','"+stunameField.getText()rn +"','"+sexField.getText()rn +"','"+snativeField.getText()rn +"','"+phoneField.getText()rn +"','"+classField.getText()rn +"','"+gradeField.getText()rn +"','"+majorField.getText()rn +"','"+collegeField.getText()rn +rn "')";rn try rn stmt.executeUpdate(sql);rn catch (SQLException e1) rn // TODO Auto-generated catch blockrn e1.printStackTrace();rn rn rn rn rn ;rnrnrn rnException in thread "AWT-EventQueue-0" java.lang.NullPointerExceptionrn at view.AddStuView$1.actionPerformed(AddStuView.java:176)rn at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)rn at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)rn at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)rn at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)rn at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)rn at java.awt.Component.processMouseEvent(Component.java:6505)rn at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)rn at java.awt.Component.processEvent(Component.java:6270)rn at java.awt.Container.processEvent(Container.java:2229)rn at java.awt.Component.dispatchEventImpl(Component.java:4861)rn at java.awt.Container.dispatchEventImpl(Container.java:2287)rn at java.awt.Component.dispatchEvent(Component.java:4687)rn这代码出现这种异常,请问各位,这个应该怎么改才行啊?我想了很久都没有想出来rnrnrn 论坛

没有更多推荐了,返回首页