java空指针异常问题 程序运行空指针异常 10C

//这个是学生类
public class Student {
private int on;
private String name;
private int age;
private int java;
private int c;
private int html;
private int sql;
private int sum;
private int avg;
Student(){
}
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 int getJava() {
return java;
}
public void setJava(int java) {
this.java = java;
}
public int getC() {
return c;
}
public void setC(int c) {
this.c = c;
}
public int getHtml() {
return html;
}
public void setHtml(int html) {
this.html = html;
}
public int getSql() {
return sql;
}
public void setSql(int sql) {
this.sql = sql;
}
public int getSum() {
return sum;
}
public void setSum() {
this.sum = this.java+this.c+this.sql+this.html;
}
public int getAvg() {
return avg;
}
public void setAvg() {
this.avg = this.sum/4;
}
public String toString(){
String msg="\t"+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.age;
return msg;
}
}

public class Admin {//管理学生类
Student[] stuArr=new Student[10];
public void addStudent(String name,int age,int renShu,int i){
stuArr=new Student[renShu];
stuArr[i].setName(name);
stuArr[i].setAge(age);
}
public String showStudent(){
String show="";
for(int i=0;i<stuArr.length;i++){
show=stuArr[i].toString();
}
return show;
}
}

import java.util.*;

public class Test {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner in=new Scanner(System.in);
    Student student=new Student();
    System.out.println("------请输入学生人数------");
    int studentNum=in.nextInt();
    Student[] stuArr=new Student[studentNum];
    Admin admin=new Admin();
    int c=0;
    do{
        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:退出系统");
        c=in.nextInt();
        if(c==10){
            System.out.println("请输入学生姓名:");
            String name=in.next();
            System.out.println("请输入学生年龄:");
            int age=in.nextInt();
            int i=0;
            admin.addStudent(name, age, studentNum, i);
            System.out.println("\t编号\t姓名\t年龄\tjava\tc\thtml\tsql\t总分\t平均分");
            System.out.println(admin.showStudent());
            i++;
        }
    }while(c!=99);
}

}

7个回答

public void addStudent(String name,int age,int renShu,int i){
stuArr=new Student[renShu];
stuArr[i].setName(name);
stuArr[i].setAge(age);
}

这个不对
首先,根据你调用的代码
admin.addStudent(name, age, studentNum, i);
你不应该每调用一次addStudent就来一个stuArr=new Student[renShu];
其次
stuArr[i].setName(name);
前面应该加上
stuArr[i] = new Student();

 public class Admin {
Student[] stuArr; //这里先不分配
public Admin(int renShu) //加上构造函数
{
stuArr=new Student[renShu];
}
...
}

然后
Admin admin=new Admin();
修改为
Admin admin=new Admin(studentNum);
Main函数里的Student[] stuArr=new Student[studentNum]; 似乎没有用上,可以删除,不删除也没事。

最后
public void addStudent(String name,int age,int renShu,int i){
//stuArr=new Student[renShu];删除这个
stuArr[i] = new Student(); //加上这个
stuArr[i].setName(name);
stuArr[i].setAge(age);
}

当然,int renShu其实也用不上了,可以删除,并且把调用的那个也对应去掉。留着也不影响

for(int i=0;i<stuArr.length && stuArr != null;i++){
show=stuArr[i].toString();
}

我将你的代码进行了一下调试,出错的原因为 stuArr[i] 没有实例化
public class Admin {//管理学生类
Student[] stuArr=new Student[10];
public void addStudent(String name,int age,int renShu,int i){
stuArr=new Student[renShu];
stuArr[i].setName(name);

stuArr[i].setAge(age);
}

另外 showStudent() 这里你需要判断一下stuArr[i] .toString 是否为空。 建议加上try,catch进行调试,很容易找到问题原因!
public String showStudent(){
String show="";
for(int i=0;i<stuArr.length;i++){
show=stuArr[i].toString();
}
return show;
}
}

run:
------请输入学生人数------
5
请选择你要执行的功能:
10:添加一个学生
11:查找一个学生
12:根据学生编号跟新学生信息
13:根据学生编号删除学生
14:根据编号输入学生各门成绩
15:根据某门成绩进行排序
16:根据总分进行排序
99:退出系统
10
请输入学生姓名:
lj
请输入学生年龄:
23
编号 姓名 年龄 java c html sql 总分 平均分
Exception in thread "main" java.lang.NullPointerException
at myrobot.Admin.showStudent(Admin.java:30)
at myrobot.Test.main(Test.java:44)

new出来一个数组 只是在内存中开辟一段空间 一定要为数组指定实例对象 否则会报指针异常

yang98351
yang98351 new出来的数组,只是有地址空间,没有对象的空间,所以如果直接去访问会报空指针异常,在许多情况下对对象的使用之前,会先做下判断。
一年多之前 回复

你每次addStudent都变一下students数组,当然会报空指针。建议参考一下ArrayList的实现,判断一下当前容量再扩容

public void addStudent(String name, int age, int renShu, int i) {
stuArr = new Student[renShu];
stuArr[i].setName(name);
stuArr[i].setAge(age);
}
这函数在被调用时,为stuArr分配了renShu个引用的内存大小,每个引用的值都是null,所以在执行stuArr[i].setName(name);时会报空指针异常。正确的做法是给stuArr[i]分配空间,即stuArr[i]=new Student(),使得stuArr[i]的值由原先的null变成student对象。如果用C语言去理解的话,就是为原来的空指针分配空间,使其指向这块空间。分配了空间后,就可以在空间上存储数据了。

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
java空指针异常问题 为何会出现空指针异常
npublic class Student n private int on;n private String name;n private int age;n private int java;n private int c;n private int html;n private int sql;n private int sum;n private int avg;n public int getOn() n return on;n n public void setOn(int on) n this.on = on;n n public String getName() n return name;n n public void setName(String name) n this.name = name;n n public int getAge() n return age;n n public void setAge(int age) n this.age = age;n n public int getJava() n return java;n n public void setJava(int java) n this.java = java;n n public int getC() n return c;n n public void setC(int c) n this.c = c;n n public int getHtml() n return html;n n public void setHtml(int html) n this.html = html;n n public int getSql() n return sql;n n public void setSql(int sql) n this.sql = sql;n n public int getSum() n return sum;n n public void setSum() n this.sum = this.java+this.c+this.sql+this.html;n n public int getAvg() n return avg;n n public void setAvg() n this.avg = this.sum/4;n n public String toString()n String msg="\t"+this.on+"\t"+this.name+"\t"+this.age+"\t"+this.javan +"\t"+this.c+"\t"+this.html+"\t"+this.sql+"\t"+this.sum+"\t"n +this.age;n return msg;n nnnnnnnnpublic class Admin //管理学生类n public void addStudent(String name,int age,Student[] stuArr)n Student stu=new Student();n int i=this.getIndex(stuArr);n stuArr[i]=stu;n stu.setName(name);n stu.setAge(age);n this.show(stuArr);n n public int getIndex(Student[] stuArr)n for(int i=0;i
空指针异常问题!!!java
int port=1025;rnport=Integer.parseInt(text_port.getText()); rnrnrn此处代码出现异常:rnException in thread "main" java.lang.NullPointerExceptionrn at ok.Cshell.createSShell(Cshell.java:126)---->port=Integer.parseInt(text_port.getText()); rnrn at ok.Cshell.main(Cshell.java:86)---->thisClass.createSShell();注释:port所在的函数:creatSShellrnrnrn 我已经初始化port了。怎么还会出现异常。
JAVA 空指针异常问题
今天运行以前编译和运行均通过了的程序,结果都出现了空指针异常,具体是:rnException in Thread "main" java.lang.NullPointerExceptionrnrn把程序在另外一台电脑上运行又没有问题。很纠结啊,不知道是不是自己电脑上的编译器出问题了啊?但是一直没动它啊。rnrn有没有碰到类似情况的童鞋啊,高手出来指教指教撒
空指针异常问题
private void get()rn rn rn List curentResult = new ArrayList();rn CustContactMVO m1=new CustContactMVO();rn m1.setContactId("001");rn curentResult.add(m1);rn PagView pagview=new PagView();rn pagview.setCount(7);rn pagview.setPagCount(3);rn pagview.setPagNo(0);rn pagview.setPagSize(2);rn pagview.setViewList(curentResult);rn current.setPagView(pagview);rnrn rn这段程序引发了空指针异常,求解释?
java空指针异常问题,新人求教
先上代码rnimport java.io.*; rnpublic class Testrn public static void main(String[] args) rn rn while(true)rn char[] password = System.console().readPassword();rn System.out.println(password);rn rn rn rnrn主要是测试console类中的readPassword方法。rn在eclipse中。会出现java.lang.NullPointerException,即空指针异常,应该是由于console控制台引起的,但为什么用javac,java在命令提示符中编译的时候木有一点问题? 求教
Java中的空指针异常问题.doc
Java中的空指针异常问题Java中的空指针异常问题.docJava中的空指针异常问题.doc
遍历目录空指针异常问题
当遍历目录搜索指定文件时,当遍历到系统文件夹隐藏文件时,listFile()会返回null,则会报空指针异常,应进行判空操作 public static void serach(File file, String name) { if(file.isDirectory()) { File[] files = file.listFiles(); if(files != null)...
NullPointerException 空指针异常问题
NullPointerException 空指针异常rn我调用javabean老是这个错误rn我有一个是get和set方法的javabeanrn然后到另一个类里 new一个出来rn再调用,就获取不到值。。不知道怎么解决。。。等待各位的帮助。。。QQ 39163008
valueOf和空指针异常问题
valueOf的源码是rnpublic static String valueOf(Object obj) rn return (obj == null) ? "null" : obj.toString();rnrn可是为什么rnif(String.valueOf(null).equals("null") )rn System.out.println("ss");rnrn报空指针异常?
request.attribute空指针异常问题!求教!
在tomcat上运行all.jsp就显示空指针异常,应该是attribute方法没有获取到,但为什么呢?rnrnrnall.jsp:rnrn<%@page import="java.util.List" %>rn<%@ page language="java" contentType="text/html; charset=UTF-8"rn pageEncoding="UTF-8"%>rnrnrnrn rn Insert title herernrnrnrn <%= request.getAttribute("id")%>rn <%rn rn List names = (List)request.getAttribute("id");rn rn rn for(String name: names)rn %> rn <%=name %> rn <% rn rn %>rn %>rnrnrnrnrnrnListAllServlet.java:rnpackage com.xugencheng.javaweb;rnrnimport java.io.IOException;rnimport javax.servlet.ServletException;rnimport javax.servlet.http.HttpServlet;rnimport javax.servlet.http.HttpServletRequest;rnimport javax.servlet.http.HttpServletResponse;rnrnrnrnrnpublic class ListAllServlet extends HttpServlet rn private static final long serialVersionUID = 1L;rnrn @Overridern protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException rn request.setAttribute("id", "aa");rn request.getRequestDispatcher("/all.jsp").forward(request, response);rnrn rn @Overridern protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException rn doGet(request,response);rn rn rnrn
tomcat 空指针异常问题
tomcat 在MyEclipse下能够正常启动 发布项目正常运行rnrn但在tomcat目录下启动tomcat 报空指针异常rnrn百度好多方法不起作用rnrnrn求前辈指教 rnrnrn异常内容如下:rnrn五月 14, 2016 7:25:23 下午 org.apache.catalina.core.StandardService startInternalrn信息: Starting service Catalinarn五月 14, 2016 7:25:23 下午 org.apache.catalina.core.StandardEngine startInternalrn信息: Starting Servlet Engine: Apache Tomcat/7.0.52rn五月 14, 2016 7:25:23 下午 org.apache.catalina.startup.HostConfig deployDirectoryrn信息: Deploying web application directory D:\apache-tomcat-7.0.11-windows-x86\apache-tomcat-7.0.11\webapps\Deck_audit2rn五月 14, 2016 7:25:23 下午 org.apache.catalina.startup.HostConfig deployDirectoryrn严重: Error deploying web application directory D:\apache-tomcat-7.0.11-windows-x86\apache-tomcat-7.0.11\webapps\Deck_audit2rnjava.lang.ExceptionInInitializerErrorrn at org.apache.catalina.startup.ContextConfig.createWebXmlDigester(ContextConfig.java:515)rn at org.apache.catalina.startup.ContextConfig.init(ContextConfig.java:836)rn at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:382)rn at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)rn at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)rn at org.apache.catalina.util.LifecycleBase.setStateInternal(LifecycleBase.java:402)rn at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:110)rn at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:139)rn at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)rn at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)rn at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:632)rn at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1229)rn at org.apache.catalina.startup.HostConfig$DeployDirectory.run(HostConfig.java:1875)rn at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)rn at java.util.concurrent.FutureTask.run(FutureTask.java:266)rn at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)rn at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)rn at java.lang.Thread.run(Thread.java:745)rnCaused by: java.lang.NullPointerExceptionrn at org.apache.tomcat.util.descriptor.DigesterFactory.idFor(DigesterFactory.java:107)rn at org.apache.tomcat.util.descriptor.DigesterFactory.(DigesterFactory.java:59)rn ... 18 morernrn五月 14, 2016 7:25:23 下午 org.apache.catalina.startup.HostConfig deployDirectoryrn信息: Deploying web application directory D:\apache-tomcat-7.0.11-windows-x86\apache-tomcat-7.0.11\webapps\docsrn五月 14, 2016 7:25:23 下午 org.apache.catalina.startup.HostConfig deployDirectoryrn严重: Error deploying web application directory D:\apache-tomcat-7.0.11-windows-x86\apache-tomcat-7.0.11\webapps\docsrnjava.lang.NoClassDefFoundError: Could not initialize class org.apache.tomcat.util.descriptor.DigesterFactoryrn at org.apache.catalina.startup.ContextConfig.createWebXmlDigester(ContextConfig.java:515)rn at org.apache.catalina.startup.ContextConfig.init(ContextConfig.java:836)rn at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:382)rn at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)rn at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)rn at org.apache.catalina.util.LifecycleBase.setStateInternal(LifecycleBase.java:402)rn at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:110)rn at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:139)rn at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)rn at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)rn at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:632)rn at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1229)rn at org.apache.catalina.startup.HostConfig$DeployDirectory.run(HostConfig.java:1875)rn at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)rn at java.util.concurrent.FutureTask.run(FutureTask.java:266)rn at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)rn at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)rn at java.lang.Thread.run(Thread.java:745)rnrn五月 14, 2016 7:25:23 下午 org.apache.catalina.startup.HostConfig deployDirectoryrn信息: Deploying web application directory D:\apache-tomcat-7.0.11-windows-x86\apache-tomcat-7.0.11\webapps\examplesrn五月 14, 2016 7:25:23 下午 org.apache.catalina.startup.HostConfig deployDirectoryrn严重: Error deploying web application directory D:\apache-tomcat-7.0.11-windows-x86\apache-tomcat-7.0.11\webapps\examplesrnjava.lang.NoClassDefFoundError: Could not initialize class org.apache.tomcat.util.descriptor.DigesterFactoryrn at org.apache.catalina.startup.ContextConfig.createWebXmlDigester(ContextConfig.java:515)rn at org.apache.catalina.startup.ContextConfig.init(ContextConfig.java:836)rn at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:382)rn at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)rn at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)rn at org.apache.catalina.util.LifecycleBase.setStateInternal(LifecycleBase.java:402)rn at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:110)rn at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:139)rn at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)rn at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)rn at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:632)rn at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1229)rn at org.apache.catalina.startup.HostConfig$DeployDirectory.run(HostConfig.java:1875)rn at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)rn at java.util.concurrent.FutureTask.run(FutureTask.java:266)rn at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)rn at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)rn at java.lang.Thread.run(Thread.java:745)rnrn五月 14, 2016 7:25:23 下午 org.apache.catalina.startup.HostConfig deployDirectoryrn信息: Deploying web application directory D:\apache-tomcat-7.0.11-windows-x86\apache-tomcat-7.0.11\webapps\host-managerrn五月 14, 2016 7:25:23 下午 org.apache.catalina.startup.HostConfig deployDirectoryrn严重: Error deploying web application directory D:\apache-tomcat-7.0.11-windows-x86\apache-tomcat-7.0.11\webapps\host-managerrnjava.lang.NoClassDefFoundError: Could not initialize class org.apache.tomcat.util.descriptor.DigesterFactoryrn at org.apache.catalina.startup.ContextConfig.createWebXmlDigester(ContextConfig.java:515)rn at org.apache.catalina.startup.ContextConfig.init(ContextConfig.java:836)rn at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:382)rn at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)rn at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)rn at org.apache.catalina.util.LifecycleBase.setStateInternal(LifecycleBase.java:402)rn at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:110)rn at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:139)rn at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)rn at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)rn at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:632)rn at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1229)rn at org.apache.catalina.startup.HostConfig$DeployDirectory.run(HostConfig.java:1875)rn at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)rn at java.util.concurrent.FutureTask.run(FutureTask.java:266)rn at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)rn at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)rn at java.lang.Thread.run(Thread.java:745)rnrn
概率空指针异常问题
不知道各位大侠遇到过此类问题没有:具体现象是在我的应用里操作操作着就出现了空指针异常,然后程序崩溃退出,关键是这空指针总是概率出现;rn 出现问题的位置我已经找到,并且进行了空指针的判断,但是还会出现,现在真的是无解了,几乎所有的可能的原因都想到了(变量被回收,服务器返回值为空等),但就是解决不了,求高人指教啊!rn 有需要的话我会贴出代码,谢谢各位大侠了! 问题补充 问题补充 我总觉得是服务器不稳定,造成了有时我这边发送请求时返回的数据为空,但又没有很好的证据
Java-对象数组空指针异常问题
最近写了一个功能接口,根据 “前台需求” 采用了对象数组来存储数据,但是debug调试时总是在利用对象数组中的每一个元素插入数据时报错,报空指针异常,经过请教,弄懂了这个问题,记录下来。package entity; //Result实体类 public class Result { private int changeScore; private UserLj userLj;
JSP空指针异常问题
运行环境:MyEclipse 2016 CIJSP登陆页面用<jsp:forward page=URL>出现问题:HTTP Status 500 - /forward.jsp (line: 2117, column: 5) Expecting "jsp:param" standard action with "name" and "value" attributes type Exception r
求解。一个空指针异常问题
package maze;rnrn//利用栈 解决迷宫问题rnrnpublic class MyMaze rn public static int mg[][]=1,1,1,1,1,1,//地图迷宫,其四周是为1的外框rn 1,0,0,0,1,1,rn 1,0,1,0,0,1,rn 1,0,1,0,1,1,rn 1,1,0,0,0,1,rn 1,1,1,1,1,1;rn public static Point[] stack=new Point[1000];//栈rn public static int top=-1;//栈顶指针rn// public static int path[];//保存最短路径的数组rn// public static int minLen;//最短路径长度。rn rn public static int mgPath(int xi,int yi,int xe,int ye)//探索路径为:(xi,yi)->(xe,ye)rn int i=0,j=0,di=-1,find=0;rn top++;rn stack[top].i=xi;//??????????????????????rn stack[top].j=yi;rn stack[top].di=-1;//初始结点进栈rn mg[1][1]=-1;rn while(top>-1)//栈不为空时循环rn i=stack[top].i;j=stack[top].j;di=stack[top].di;//取栈顶方块rn if(i==xe&&j==ye)//找到了出口,输出路径rn System.out.println("迷宫路径如下:");rn for(int k=0;k<=top;k++)rn System.out.println("("+stack[k].i+","+stack[k].j+")");rn if((k+1)%5==0)//每输出五个方块后换一行rn System.out.println();rn rn return 1;rn rn find=0;rn while(di<4&&find==0)//找(i,j)方块下一个可走方块rn di++;rn switch(di)//方向规定按顺时针方向来探索rn case 0: i=stack[top].i-1;j=stack[top].j;break;rn case 1: i=stack[top].i;j=stack[top].j+1;break;rn case 2: i=stack[top].i+1;j=stack[top].j;break;rn case 3: i=stack[top].i;j=stack[top].j-1;break;rn rn if(mg[i][j]==0)rn find=1;//找到下一个可走相邻方块rn rn if(find==1)//找到了一个可走的相邻方块rn stack[top].di=di;//修改原栈顶元素的di值rn top++;rn stack[top].i=i;stack[top].j=j;stack[top].di=-1;rn mg[i][j]=-1;//避免重复走到该方块,将其置为-1rn else//没有相邻方块可走,则退栈。rn mg[stack[top].i][stack[top].j]=0;//让该位置变为其他路径可走方块。rn top--;//将该方块退栈rn rn rn rn return 0;rn rn private class Point//点的位置及方位rn int i;rn int j;//i,j为方块的行号,列号。rn int di;//下一步可走相邻方位的方位号。rn rn rn public static void main(String[] args) rn MyMaze.mgPath(1, 1, 4, 4);rn rnrnrn注:在标注???的地方出现空指针异常。这个空指针异常应该与我的算法没关系,可能是我的某个基础知识没能理解造成的,请明白人指点一下。麻烦您了
【求助】空指针异常问题
一个简单的Java Socket通信程序,收发消息都是正常的,就是每次发送结束的时候会在最后输出一个“null”,然后抛出异常。比如:rnserver okrn************************************************rn123 456 789 987 654 321rnnullrnError:java.lang.NullPointerExceptionrnrnrnrnimport java.net.*;rnimport java.io.*;rnimport java.lang.*;rnpublic class server rn @SuppressWarnings("deprecation")rn public static void main(String args[]) rn ServerSocket server;rn Socket socket;rn String s;rn InputStream Is;rn DataInputStream DIS;rnrn try rn server = new ServerSocket(9000);rn socket = server.accept();rnrn System.out.println("server ok");rn System.out.println("************************************************");rn Is = socket.getInputStream();rn DIS = new DataInputStream(Is);rn while (true) rn s = DIS.readLine();rn System.out.println(s);rn if (s.trim().equals("BYE"))break;rn rn DIS.close();rn Is.close();rn socket.close();rn catch (Exception e) rn System.out.println("Error:" + e);rn rn rnrn
DefaultListModel 出现空指针异常问题
package com.hyn;rnrnrnimport java.awt.event.ActionEvent;rnimport java.awt.event.ActionListener;rnimport java.io.BufferedReader;rnimport java.io.IOException;rnimport java.io.InputStreamReader;rnimport java.io.ObjectOutputStream;rnimport java.net.Socket;rnimport java.net.UnknownHostException;rnimport java.text.DateFormat;rnimport java.util.ArrayList;rnimport java.util.Date;rnimport javax.imageio.ImageIO;rnimport javax.swing.DefaultComboBoxModel;rnimport javax.swing.DefaultListModel;rnimport javax.swing.ImageIcon;rnimport javax.swing.JButton;rnimport javax.swing.JFrame;rnimport javax.swing.JLabel;rnimport javax.swing.JList;rnimport javax.swing.JPanel;rnimport javax.swing.JScrollPane;rnimport javax.swing.JTextArea;rnimport javax.swing.JTextField;rnimport javax.swing.ScrollPaneConstants;rnimport javax.swing.UIManager;rnimport javax.swing.UnsupportedLookAndFeelException;rnrnpublic class Talklogin extends JFramern /**rn * rn */rn private static final long serialVersionUID = 1L;rn private ObjectOutputStream oos;rn private JList user_list;rn private JTextArea show_jta;rn private JTextField send_jtf;rn private JTextField jtf_username;rn private boolean loginFlag = false;rn public void createsocketlogin()rn try rn Socket socket=new Socket("localhost", 8765);rn oos=new ObjectOutputStream(socket.getOutputStream());rn new loginthread(socket).start();rn catch (UnknownHostException e) rn e.printStackTrace();rn catch (IOException e) rn e.printStackTrace();rn rn rn rn class loginthread extends Threadrn Socket socket;rn public loginthread(Socket socket)rn this.socket=socket;rn rn rn public void run()rn try rn BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream()));rn DefaultListModel dcbm=(DefaultListModel)user_list.getModel();rn while(true)rn String getout=br.readLine().trim();rn if(!getout.startsWith("MEG:"))rn if(getout.startsWith("退出:"))rn dcbm.removeElement(getout.substring(3));rn elsern @SuppressWarnings("unused")rn boolean flag=false;rn for(int i=0;i al=new ArrayList();rn Object[] receiveusername=user_list.getSelectedValues();rn if(receiveusername.length<=0)rn return;rn rn for(int i=0;i
关于空指针异常问题
我在写一个注册用户页面,在将数据往mysql里面插入的时候,遇到空指针异常,插入失败,求各位大神指点迷津!rn[img=https://img-bbs.csdn.net/upload/201705/18/1495096926_821512.png][/img]rn[img=https://img-bbs.csdn.net/upload/201705/18/1495096941_784415.png][/img]rn下面这张图是sqlHelper里面的insertManager方法:rn[img=https://img-bbs.csdn.net/upload/201705/18/1495096959_374134.png][/img]rnrn下面这张是servlet文件InsertManager的doPost代码rn[img=https://img-bbs.csdn.net/upload/201705/18/1495096970_300621.png][/img]rn[img=https://img-bbs.csdn.net/upload/201705/18/1495096978_599908.png][/img]rnrn找了很久还是没找到原因,求大神们指点!
空指针异常问题,怎么修改?
public ResultSet executeQuery(String sql) n try // 捕捉异常n conn = getConnection(); // 调用getConnection()方法构造connection对象的一个实例connn stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,n ResultSet.CONCUR_READ_ONLY);n rs = stmt.executeQuery(sql);n catch (SQLException ex) n System.err.println(ex.getMessage()); // 输出异常消息n n return rs; // 返回结果集对象n n n 报错:n java.lang.NullPointerExceptionn com.wgh.tools.ConnDB.executeQuery(ConnDB.java:56)n com.wgh.dao.DiaryDao.queryDiary(DiaryDao.java:28)n com.wgh.servlet.DiaryServlet.listAllDiary(DiaryServlet.java:249)n com.wgh.servlet.DiaryServlet.doPost(DiaryServlet.java:52)n com.wgh.servlet.DiaryServlet.doGet(DiaryServlet.java:66)n javax.servlet.http.HttpServlet.service(HttpServlet.java:624)n javax.servlet.http.HttpServlet.service(HttpServlet.java:731)n org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)n com.wgh.filter.CharacterEncodingFilter.doFilter(CharacterEncodingFilter.java:24)nn下面这是56行:nstmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,n ResultSet.CONCUR_READ_ONLY);
一个二维数组,空指针异常问题。
![图片说明](https://img-ask.csdn.net/upload/201606/18/1466239385_520858.jpg)
hibernate 空指针异常问题
package com.yuqidi.mapping;rnrnimport java.util.Iterator;rnrnimport org.hibernate.Session;rnimport org.hibernate.SessionFactory;rnimport org.hibernate.cfg.AnnotationConfiguration;rnimport org.hibernate.tool.hbm2ddl.SchemaExport;rnimport org.junit.AfterClass;rnimport org.junit.BeforeClass;rnimport org.junit.Test;rnrnpublic class mappingTest rn private static SessionFactory sessionFactory;rnrn@BeforeClassrnpublic static void beforeClass() rn new SchemaExport(new AnnotationConfiguration().configure()).create(false, true);rn sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();rnrn@AfterClassrnpublic static void afterClass() rn sessionFactory.close();rnrnrnrnrn@Testrnpublic void testSaveGroup() rn User u1 = new User();rn u1.setName("u1");rn User u2 = new User();rn u2.setName("u2");rn Group g = new Group();rn g.setName("g1");rn g.getUsers().add(u1);rn g.getUsers().add(u2);rn u1.setGroup(g);rn u2.setGroup(g);rn Session s = sessionFactory.getCurrentSession();rn s.beginTransaction();rn rn s.save(g);rn s.getTransaction().commit();rnrnrnrnrn@Testrnpublic void testGetGroup()rn testSaveGroup();rn Session s = sessionFactory.getCurrentSession();rn rn s.beginTransaction();rn Group g=(Group)s.get(Group.class, 0);rn System.out.println(g.getName());rn s.getTransaction().commit();rnrn@Testrnpublic void testSchemaExport() rn new SchemaExport(new AnnotationConfiguration().configure()).create(false, true);rnrnrnpublic static void main(String[] args) rn rn beforeClass();rnrnrnrnrn用Junit 测试时会报空指针异常;去掉System.out.println(g.getName());可以通过测试,情各位指教
求助空指针异常问题
我已经上传了附件,里面有要用到的文件rnrn空指针异常如下:rnjava.lang.NullPointerExceptionrn com.briup.bean.ShoppingCart.addLine(ShoppingCart.java:17)rn com.briup.web.servlet.AddOrderlineServlet.process(AddOrderlineServlet.java:83)rn com.briup.web.servlet.AddOrderlineServlet.doPost(AddOrderlineServlet.java:61)rn javax.servlet.http.HttpServlet.service(HttpServlet.java:710)rn javax.servlet.http.HttpServlet.service(HttpServlet.java:803)rn com.briup.web.filter.EncodeFilter.doFilter(EncodeFilter.java:29)rnrnrn其中com.briup.bean.ShoppingCart.addLine(ShoppingCart.java:17)代码是:rn rn else if(line.getNum()>0)rnrncom.briup.web.servlet.AddOrderlineServlet.process(AddOrderlineServlet.java:83)代码是:rn rn shoppingcart.addLine(orderline);rnrnjsp文件打开后,不管我输多少,都报这个异常,各位大哥帮帮忙,帮我找下错误在哪里,我找到头都大了,谢谢了
jtable.setModel(Dtm)空指针异常问题
rn[code=Java][/code]rnprivate DefaultTableModel Dtm=new Get_czb().get_czb();rn // Get_czb().get_czb();rn //这个方法是获得数据库链接 并且拿出数据rnTimer timer = new Timer();rntimer.schedule(new GetjTable(),1000,1000);rnclass GetjTable extends java.util.TimerTaskrnrn @Overridern public void run() rn System.out.println("kaishile");rn Dtm=new Get_czb().get_czb();rn jTable1.setModel(Dtm);rn //jTable1.repaint();rn //jTable1.updateUI();rn System.out.println(new JTable(Dtm));rn rn rnrn这里我用system.print测试过Dtm了 里边的数据已经改变了 但是在更新jtable1的时候出现空指针异常 , 就是这句 jTable1.setModel(Dtm);rnrn用线程也试过了 还是不行 为什么别人的都能用setModel这个方法 我怎么都不能用啊rnrn
求教空指针异常问题
Logcat显示的信息如下,自己的代码都逐步执行过,没有抛出异常。异常是在底层的代码里抛出来的rn跟踪到底层代码,发现是在android.app包下的Instrumentation.class中,mActivityMonitors为null而抛出rn而mActivityMonitors的实例化是在Instrumentation里的addMonitor(),在这里打了断点却没有进入rn直接调用了callActivityOnCreate()方法对mActivityMonitors操作而产生空指针异常rnrn还请救大神指点rnrn[code=text]rn06-16 05:46:19.076: W/dalvikvm(2336): threadid=1: thread exiting with uncaught exception (group=0xb3ac6ba8)rn06-16 05:46:19.086: E/AndroidRuntime(2336): FATAL EXCEPTION: mainrn06-16 05:46:19.086: E/AndroidRuntime(2336): Process: com.rivscs.client, PID: 2336rn06-16 05:46:19.086: E/AndroidRuntime(2336): java.lang.RuntimeException: Unable to start activity ComponentInfocom.rivscs.client/com.rivscs.client.component.BaseActivity: java.lang.NullPointerExceptionrn06-16 05:46:19.086: E/AndroidRuntime(2336): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)rn06-16 05:46:19.086: E/AndroidRuntime(2336): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)rn06-16 05:46:19.086: E/AndroidRuntime(2336): at android.app.ActivityThread.access$800(ActivityThread.java:135)rn06-16 05:46:19.086: E/AndroidRuntime(2336): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)rn06-16 05:46:19.086: E/AndroidRuntime(2336): at android.os.Handler.dispatchMessage(Handler.java:102)rn06-16 05:46:19.086: E/AndroidRuntime(2336): at android.os.Looper.loop(Looper.java:136)rn06-16 05:46:19.086: E/AndroidRuntime(2336): at android.app.ActivityThread.main(ActivityThread.java:5017)rn06-16 05:46:19.086: E/AndroidRuntime(2336): at java.lang.reflect.Method.invokeNative(Native Method)rn06-16 05:46:19.086: E/AndroidRuntime(2336): at java.lang.reflect.Method.invoke(Method.java:515)rn06-16 05:46:19.086: E/AndroidRuntime(2336): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)rn06-16 05:46:19.086: E/AndroidRuntime(2336): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)rn06-16 05:46:19.086: E/AndroidRuntime(2336): at dalvik.system.NativeStart.main(Native Method)rn06-16 05:46:19.086: E/AndroidRuntime(2336): Caused by: java.lang.NullPointerExceptionrn06-16 05:46:19.086: E/AndroidRuntime(2336): at com.rivscs.util.NetStatusUtil.isNetConnectivity(NetStatusUtil.java:11)rn06-16 05:46:19.086: E/AndroidRuntime(2336): at com.rivscs.client.component.BaseActivity.onStart(BaseActivity.java:401)rn06-16 05:46:19.086: E/AndroidRuntime(2336): at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1171)rn06-16 05:46:19.086: E/AndroidRuntime(2336): at android.app.Activity.performStart(Activity.java:5241)rn06-16 05:46:19.086: E/AndroidRuntime(2336): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2168)rn06-16 05:46:19.086: E/AndroidRuntime(2336): ... 11 morern[/code]
空指针异常问题,求解
运行时报错了:java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator()' on a null object referencern at com.neoandroid.mytheater.FilmListFragment.onCreateView(FilmListFragment.java:129)rn at android.app.Fragment.performCreateView(Fragment.java:2053)rn at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:894)rn at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)rn第129行就是下面93行,感觉fromJson()不会返回一个null吧,弄好久了,求大神看看rn[code=java]rnpublic class FilmListFragment extends Fragment rn ListView listView;rn private Button buyButton;rn private String response;rn private Bitmap bitmap;rn public static final int FILM_MSG = 1;rn public static final int FILM_IMG = 2;rn public static final int ERROR_MSG = 0;rn final String FILM_DATA_ADDRESS= "http://192.168.191.1:8080/TheaterWeb/servlet/FilmInfo";rn private List filmItemList;rn private Handler filmHandler = new Handler()rn @Overridern public void handleMessage(Message msg) rn switch (msg.what)rn case FILM_MSG:rn response = (String)msg.obj;rn break;rn case ERROR_MSG:rn Exception exception = (Exception) msg.obj;rn exception.printStackTrace();rn break;rn case FILM_IMG:rn bitmap = (Bitmap)msg.obj;rn break;rn default:rn break;rn rn rn ;rn //根据图片地址得到bitmaprn public Bitmap returnBitMap(String str)rn final String imgURL = str;rn new Thread(new Runnable() rn @Overridern public void run() rn Bitmap bitmap = null;rn HttpURLConnection connection = null;rn try rn URL url = new URL(imgURL);rn connection = (HttpURLConnection) url.openConnection();rn connection.setRequestMethod("GET");rn connection.setConnectTimeout(8000);rn connection.setReadTimeout(8000);rn connection.setDoInput(true);rn connection.setDoOutput(true);rn connection.connect();rn InputStream in = connection.getInputStream();rn bitmap = BitmapFactory.decodeStream(in);rn in.close();rn connection.disconnect();rn catch (Exception e)rn e.printStackTrace();rn rn Message message = new Message();rn message.what = FILM_IMG;rn message.obj = bitmap;rn filmHandler.sendMessage(message);rn rn ).start();rn return bitmap;rn rn @Overridern public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) rnrn View view = inflater.inflate(R.layout.fg_film_list,container,false);rn listView = (ListView)view.findViewById(R.id.film_list);rn buyButton = (Button)view.findViewById(R.id.buy_button);rnrn filmItemList = new ArrayList();rn //与服务器建立连接获取数据rn HttpUtil.sendHttpRequest(FILM_DATA_ADDRESS, new HttpCallbackListener() rn @Overridern public void onFinish(String response) rn Message msg = new Message();rn msg.what = FILM_MSG;rn msg.obj = response;rn filmHandler.sendMessage(msg);rn rnrn @Overridern public void onError(Exception e) rn Message message = new Message();rn message.what = ERROR_MSG;rn message.obj = e;rn filmHandler.sendMessage(message);rn rn );rn List> listItems = new ArrayList>();rn //解析json数据rn Gson gson = new Gson();rn List filmItems = gson.fromJson(response, new TypeToken>().getType());rn filmItemList = filmItems;rn for (FilmItem filmItem: filmItems)rn Log.d("FilmListFragment", "filmName is" + filmItem.getFilmName());rn Map filmItemForMap = new HashMap();rn filmItemForMap.put("img", returnBitMap(filmItem.getFilmImgURL()));rn filmItemForMap.put("name", filmItem.getFilmName());rn filmItemForMap.put("director", filmItem.getDirector());rn filmItemForMap.put("actor", filmItem.getActor());rn listItems.add(filmItemForMap);rn rn FilmSimpleAdapter simpleAdapter = new FilmSimpleAdapter(getActivity(), listItems, R.layout.film_item,new String[]"img","name","director","actor",new int[]R.id.film_item_img, R.id.film_item_name, R.id.film_item_director,R.id.film_item_actor);rn //设置图片rn simpleAdapter.setViewBinder(new SimpleAdapter.ViewBinder() rn @Overridern public boolean setViewValue(View view, Object data, String textRepresentation) rn if (view instanceof ImageView && data instanceof Bitmap) rn ImageView iv = (ImageView) view;rn iv.setImageBitmap((Bitmap) data);rn return true;rn rn return false;rn rn );rn listView.setAdapter(simpleAdapter);rn //设置点击事件rn listView.setOnItemClickListener(new AdapterView.OnItemClickListener() rn @Overridern public void onItemClick(AdapterView parent, View view, int position, long id) rn FilmItem filmItem = filmItemList.get(position);rn Intent intent = new Intent(getActivity(), FilmActivity.class);rn intent.putExtra("film_data", filmItem);rn startActivity(intent);rn rn );rn return view;rn rn[/code]
自定义数组的空指针异常问题
import java.util.*;rnclass Studentrn String name;rn String major;rnint num;rn int grade;rnpublic Student(String name,String major,int num,int grade)rnrn this.name=name;rn this.major=major;rn this.num=num;rn this.grade=grade;rnrnrnrn rnpublic class Teamrn public static void main(String[]args)rnrn Scanner in=new Scanner(System.in);rn Student team[][]=new Student[3][];rn for(int i=0;i<3;i++)rn for(int j=0;j
求助:空指针异常问题!急。
我建的是一个Web项目,在本机上测试没有异常!但发布Webservice之后,在另一个IP地址机上测试就rn报出了如下错误 :请问怎么解决!!!rnjava.lang.NullPointerExceptionrn at com.unitedpacs.impl.report.RisstudiesImpl.selectm(RisstudiesImpl.java:423)rn at com.unitedpacs.webservices.ReportWS.selectm(ReportWS.java:49)rn at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)rn at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)rn at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)rn at java.lang.reflect.Method.invoke(Method.java:597)rn at com.sun.xml.ws.api.server.InstanceResolver$1.invoke(InstanceResolver.java:246)rn at com.sun.xml.ws.server.InvokerTube$2.invoke(InvokerTube.java:146)rn at com.sun.xml.ws.server.sei.EndpointMethodHandler.invoke(EndpointMethodHandler.java:257)rn at com.sun.xml.ws.server.sei.SEIInvokerTube.processRequest(SEIInvokerTube.java:93)rn at com.sun.xml.ws.api.pipe.Fiber.__doRun(Fiber.java:598)rn at com.sun.xml.ws.api.pipe.Fiber._doRun(Fiber.java:557)rn at com.sun.xml.ws.api.pipe.Fiber.doRun(Fiber.java:542)rn at com.sun.xml.ws.api.pipe.Fiber.runSync(Fiber.java:439)rn at com.sun.xml.ws.server.WSEndpointImpl$2.process(WSEndpointImpl.java:243)rn at com.sun.xml.ws.transport.http.HttpAdapter$HttpToolkit.handle(HttpAdapter.java:444)rn at com.sun.xml.ws.transport.http.HttpAdapter.handle(HttpAdapter.java:244)rn at com.sun.xml.ws.transport.http.servlet.ServletAdapter.handle(ServletAdapter.java:135)rn at com.sun.xml.ws.transport.http.servlet.WSServletDelegate.doGet(WSServletDelegate.java:129)rn at com.sun.xml.ws.transport.http.servlet.WSServletDelegate.doPost(WSServletDelegate.java:160)rn at com.sun.xml.ws.transport.http.servlet.WSServlet.doPost(WSServlet.java:75)rn at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)rn at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)rn at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)rn at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)rn at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)rn at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)rn at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)rn at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)rn at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)rn at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)rn at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849)rn at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)rn at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454)rn at java.lang.Thread.run(Thread.java:619)rn
空指针异常问题(springMVC)
本人新人一枚,在学springmvc,报空指针异常能帮忙看看嘛rn[code=java]public class LoginController extends SimpleFormControllerrn private String showUser;rn private String errPage;rn public String getErrPage() rn return errPage;rn rn public void setErrPage(String errPage) rn this.errPage = errPage;rn rn public LoginController()rn setCommandClass(User.class);rn rn protected ModelAndView onSubmit(Object command,BindException exception)throws Exceptionrn User user = (User) command;rn LoginDao log = new LoginDao();rn if(user.getUser().equals(""))rn return new ModelAndView(getErrPage(),"error","用户名不能为空!");rn rn if(user.getPwd().equals(""))rn return new ModelAndView(errPage,"error","密码不能为空!");rn rn if(user.getPwd().length()<6)rn return new ModelAndView(errPage,"error","密码不能少于6位!");rn rn if(log.isExist(user.getUser(),user.getPwd()))rn return new ModelAndView(getShowUser(),"user",user);rn rn return new ModelAndView(errPage,"error","账号或密码错误!");rn rn [/code]rn[code=java]public class LoginDao rn public boolean isExist(String username,String password)rn Connection conn=DBManager.getConn();rn boolean result=false;rn String sql="select * from login where name=? and password=?";rn PreparedStatement ps=null;rn ResultSet rs=null;rn try rn ps=conn.prepareStatement(sql);rn ps.setString(1, username);rn ps.setString(2, password);rn rs=ps.executeQuery();rn if(rs.next())rn result=true;rn rn catch (SQLException e) rn e.printStackTrace();rn finally rn DBManager.closeAll(rs, ps, conn); rn rn return result;rn rn[/code]rn前面几个if判断都能执行并跳转但一运行到这个方法就报错rn该方法在测试类中是可以运行的rn[code=java]public class Test rn public static void main(String[] args) rn LoginDao log = new LoginDao();rn System.out.println(log.isExist("zhangsan","123456"));rn rn[/code]rn[img=https://img-bbs.csdn.net/upload/201807/22/1532255465_781398.png][/img]rn[img=https://img-bbs.csdn.net/upload/201807/22/1532255490_835718.png][/img][img=https://img-bbs.csdn.net/upload/201807/22/1532255500_633594.png][/img]rn[img=https://img-bbs.csdn.net/upload/201807/22/1532256376_330120.png][/img]rn是不是还要找spring-servlet中配置?还是别的
空指针异常问题解析
<p>rn <br />rn</p>rn<p>rn <p>rn 20周年限定一卡通!<span style="color:#337FE5;">可学Java全部课程</span>,仅售799元(原价7016元),<span style="color:#E53333;">还送漫威正版授权机械键盘+CSDN 20周年限量版T恤+智能编程助手!</span>rn </p>rn <p>rn 点此链接购买:rn </p>rn <table>rn <tbody>rn <tr>rn <td>rn <span style="color:#337FE5;"><a href="https://edu.csdn.net/topic/teachercard?utm_source=jsk20xqy" target="_blank">https://edu.csdn.net/topic/teachercard?utm_source=jsk20xqy</a><br />rn</span>rn </td>rn </tr>rn </tbody>rn </table>rn</p>rn<span>&nbsp;</span> rn<p>rn <br />rn</p>rn针对企业开发的主流框架进行讲解,注重理论和实践的结合,课程内容深入源码,讲解深入浅出,每个技术点都配备具有典型性和实用性的案例及代码。使学生具备开发企业级项目的能力,同时针对框架新特性也有讲授,通过这些新功能实用性强、易用性高,可大幅降低 JavaEE 开发的难度,同时有效提升应用开发的优雅性。
java绘图时出现的空指针异常问题
我想用绘图功能在一个Frame中画出两个图形,该图形名字一个为MyTank,另一个叫EnermyTank,他们有共同的父类Tank,绘图方法定义在父类中paintTank(Graphics g),该方法调用paint(Graphics g)方法。其中g是在MainFrame中创建的。在运行时出现空指针异常,请问程序错在哪里?rn具体代码如下:rn第一个文件TankClass.javarnimport java.awt.*;rnimport javax.swing.*;rnpublic abstract class TankClass extends Framern private int x,y;//定义坦克的位置rn private int type;//定义坦克的类型rn public int getX() rn return x;rn rn public void setX(int x) rn this.x = x;rn rn public int getY() rn return y;rn rn public void setY(int y) rn this.y = y;rn rn public int getType() rn return type;rn rn public void setType(int type) rn this.type = type;rn rn //画出坦克rn protected void paintTank(Graphics g)rn //根据坦克类型决定坦克颜色rn if(this.type==0)rn g.setColor(Color.red);rn rn else if(this.type==1)rn g.setColor(Color.blue);rn rn paint(g);rn rn public void paint(Graphics g)rn g.fillOval(this.x, this.y, 20, 20);rn rnrnclass MyTank extends TankClassrn rnclass EnermyTank extends TankClassrn rnrnrn第二个文件MainFrame.javarnimport java.awt.*;rnimport javax.swing.*;rnpublic class MainFrame extends Framern MyTank mt;rn EnermyTank et;rn Graphics g;rn public MainFrame()rn //创建图形对象rn g=getGraphics();rn mt=new MyTank();rn et=new EnermyTank();rn mt.setX(30);rn mt.setY(30);rn mt.setType(0);rn mt.paintTank(g);rn et.setX(70);rn et.setY(70);rn et.setType(1);rn et.paintTank(g);rn //this.add(mainp);rn this.setSize(100, 100);rn this.setVisible(true);rn rn rn public static void main(String[] args) rn MainFrame mf=new MainFrame();rnrn rnrnrnrn
android程序运行空指针问题。
调试程序报错空指针。rn我是在网上找别人的代码。rnrn[color=#FF0000]Mylocation.java[/color]rn rn rnrnpackage com.swift.mylocation;rn rnimport java.io.IOException;rn import java.util.List;rn import java.util.Locale;rn rnimport android.app.PendingIntent;rn rnimport android.content.Context;rn import android.content.Intent;rn rnimport android.location.Address;rn import android.location.Criteria;rn import android.location.Geocoder;rn import android.location.Location;rn import android.location.LocationListener;rn import android.location.LocationManager;rn import android.os.Bundle;rn rn rn rnimport android.widget.TextView;rn import android.widget.Toast;rn rnimport com.google.android.maps.GeoPoint;rn import com.google.android.maps.MapActivity;rn import com.google.android.maps.MapController;rn import com.google.android.maps.MapView;rn import com.google.android.maps.Overlay;rn import com.swift.mylocation.R;rn rnpublic class Mylocation extends MapActivity rn rn MapController mapController;rn List overlays;rn MyPositionOverlay positionOverlay;rn LocationManager locationManager;rn MapView myMapView;rn rn final String PROXIMITY_ALERT = new String(rn "android.intent.action.proximityalert");rn rn @SuppressWarnings("deprecation")rn @Overridern public void onCreate(Bundle icicle) rn super.onCreate(icicle);rn setContentView(R.layout.main);rn rn myMapView = (MapView) findViewById(R.id.myMapView);rn rn mapController = myMapView.getController();rn rn myMapView.setSatellite(true);rn myMapView.setStreetView(true);rn myMapView.displayZoomControls(false);rn rn mapController.setZoom(17);rn rn positionOverlay = new MyPositionOverlay();rn overlays = myMapView.getOverlays();rn overlays.add(positionOverlay);rn rn Criteria criteria = new Criteria();rn criteria.setAccuracy(Criteria.ACCURACY_FINE);rn criteria.setAltitudeRequired(true);rn criteria.setBearingRequired(false);rn criteria.setCostAllowed(false);rn criteria.setPowerRequirement(Criteria.POWER_LOW);rn locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);rn rn String provider = locationManager.getBestProvider(criteria, true);rn rn Location location = locationManager.getLastKnownLocation(provider);rn rn updateWithNewLocation(location);rn rn locationManager.requestLocationUpdates(provider, 2000, 10,rn locationListener);rn rn setProximityAlert();rn rn rn rn private final LocationListener locationListener = new LocationListener() rn @Overridern public void onLocationChanged(Location location) rn updateWithNewLocation(location);rn rn rn @Overridern public void onProviderDisabled(String provider) rn updateWithNewLocation(null);rn rn rn @Overridern public void onProviderEnabled(String provider) rn rn rn @Overridern public void onStatusChanged(String provider, int status, Bundle extras) rn rn ;rn rn rn rn rn void setProximityAlert() rn rn double lat = 31.620356666666666;rn double lng = 121.38631333333333;rn float radius = 50f;rn long expiration = -1;rn rn Intent intent = new Intent(PROXIMITY_ALERT);rn intent.setAction(PROXIMITY_ALERT);rn PendingIntent proximityIntent = PendingIntent.getBroadcast(this, -1,rn intent, 0);rn rn locationManager.addProximityAlert(lat, lng, radius, expiration,rn proximityIntent);rn rn rn rn /** Update UI with a new location */rn private void updateWithNewLocation(Location location) rn rn String latLongString;rn TextView myLocationText;rn myLocationText = (TextView) findViewById(R.id.myLocationText);rn String addressString = "No address found";rn if (location != null) rn rn positionOverlay.setLocation(location);rn rn Double geoLat = location.getLatitude() * 1E6;rn Double geoLng = location.getLongitude() * 1E6;rn GeoPoint point = new GeoPoint(geoLat.intValue(), geoLng.intValue());rn mapController.animateTo(point);rn rn double lat = location.getLatitude();rn double lng = location.getLongitude();rn latLongString = "Lat:" + lat + "\nLong:" + lng;rn double latitude = location.getLatitude();rn double longitude = location.getLongitude();rn rn Geocoder gc = new Geocoder(this, Locale.CHINA);rn try rn List addresses = gc.getFromLocation(latitude,rn longitude, 1);rn StringBuilder sb = new StringBuilder();rn if (addresses.size() > 0) rn Address address = addresses.get(0);rn for (int i = 0; i < address.getMaxAddressLineIndex(); i++)rn sb.append(address.getAddressLine(i)).append("\n");rn sb.append(address.getCountryName());rn sb.append(address.getLocality()).append("\n");rn rn addressString = sb.toString();rn catch (IOException e) rn rn else rn latLongString = "No location found";rn rn myLocationText.setText("Your Current Position is:\n" + latLongStringrn + "\n" + addressString);rn rn Toast.makeText(this,this.getIntent().getStringExtra(PROXIMITY_ALERT) , Toast.LENGTH_LONG);rn rn rn @Overridern protected boolean isRouteDisplayed() rn return true;rn rn rn rnrn rn rn[color=#FF0000]MyPostionOverlay.java[/color]rn rn rn rnrnpackage com.swift.mylocation;rn rnimport android.graphics.Canvas;rn import android.graphics.Paint;rn import android.graphics.Point;rn import android.graphics.RectF;rn import android.location.Location;rn rnimport com.google.android.maps.GeoPoint;rn import com.google.android.maps.MapView;rn import com.google.android.maps.Overlay;rn import com.google.android.maps.Projection;rn rnpublic class MyPositionOverlay extends Overlay rn rn Location location, mlocation;rn final Double lat = 31.620356666666666 * 1E6,rn lon = 121.38631333333333 * 1E6;rn final int ccc = 50;rn private final int mRadius = 5;rn rn /**rn * @return the locationrn */rn public Location getLocation() rn return location;rn rn rn /**rn * @param locationrn * the location to setrn */rn public void setLocation(Location location) rn this.location = location;rn rn rn @Overridern public void draw(Canvas canvas, MapView mapView, boolean shadow) rn Projection projection = mapView.getProjection();rn if (shadow == false) rn rn Double latitude = location.getLatitude() * 1E6;rn Double longitude = location.getLongitude() * 1E6;rn GeoPoint geoPoint, gp;rn geoPoint = new GeoPoint(latitude.intValue(), longitude.intValue());rn gp = new GeoPoint(lat.intValue(), lon.intValue());rn rn Point point = new Point();rn projection.toPixels(geoPoint, point);rn RectF oval = new RectF(point.x - mRadius, point.y - mRadius,rn point.x + mRadius, point.y + mRadius);rn rn Paint paint = new Paint();rn paint.setARGB(250, 255, 0, 0);rn paint.setAntiAlias(true);rn paint.setFakeBoldText(true);rn Paint backPaint = new Paint();rn backPaint.setARGB(175, 50, 50, 50);rn backPaint.setAntiAlias(true);rn RectF backRect = new RectF(point.x + 2 + mRadius, point.y - 3rn * mRadius, point.x + 65, point.y + mRadius);rn rn Point center = new Point();rn rn projection.toPixels(gp, center);rn rn Paint ccp = new Paint();rn ccp.setARGB(250, 0, 0, 255);rn ccp.setAntiAlias(true);rn rn canvas.drawCircle(center.x, center.y, ccc, ccp);rn rn canvas.drawOval(oval, paint);rn canvas.drawRoundRect(backRect, 5, 5, backPaint);rn canvas.drawText("Here I Am", point.x + 2 * mRadius, point.y, paint);rn rn rn super.draw(canvas, mapView, shadow);rn rn rn @Overridern public boolean onTap(GeoPoint point, MapView mapView) rn return false;rn rn rn
setOnClickListener报空指针异常问题汇总
有关设置控件监听器时,报空指针异常问题汇总
浅谈equals报空指针异常问题
浅谈equals报空指针异常问题 常见格式 我们常见的equals用法如下: if("111".equals(info.getProrgcode())){ System.out.println("雷猴啊!!"); } 一般常量在前比较内容在后,这样不会出什么问题 特殊格式 特殊格式如下: if(oldStation.getProrgcode().equals(info.getProrgc...
Hibernate实例化时的空指针异常问题
[color=#FF0000]错误代码如下[/color]:rnjava.lang.NullPointerExceptionrn at com.fuyun.hp.hibernate.mapping.AdsModuleDAO.getInstance(AdsModuleDAO.java:14)rn at org.apache.jsp.main_jsp._jspService(main_jsp.java:63)rn at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)rn at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)rn at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)rn at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:337)rn at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:266)rn at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)rn at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)rn at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)rn at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)rn at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)rn at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)rn at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)rn at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)rn at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286)rn at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)rn at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)rn at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)rn at java.lang.Thread.run(Thread.java:619)rnrn[color=#FF0000]main.jsp[/color]:(简单测试用)rn<%@ page language="java" contentType="text/html; charset=utf-8" %>rn<%@page import="java.util.List"%>rn<%@page import="com.fuyun.hp.hibernate.mapping.AdsModule"%>rn<%@page import="com.fuyun.hp.hibernate.mapping.AdsModuleDAO"%>rn<%rn AdsModule topModule;rn AdsModuleDAO moduleDao = AdsModuleDAO.getInstance();rn List topList = moduleDao.find("from AdsModule order by moduleIndex");rn for (int i = 0; i < topList.size(); i++) rn rn topModule = topList.get(i);rn out.println(topModule.getModuleName() + ":" + topModule.getCnName());rn rn%>rnrn[color=#FF0000]AdsModuleDAO.java[/color]:rnpackage com.fuyun.hp.hibernate.mapping;rnrnimport com.fuyun.hp.common.GenericHibernateDao;rnimport com.fuyun.hp.common.SpringContext;rnrnpublic class AdsModuleDAO extends GenericHibernateDao rnrn /**rn * 获得DAO实例rn * @returnrn */rn public static AdsModuleDAO getInstance()rn rn return (AdsModuleDAO)SpringContext.getContext().getBean(AdsModuleDAO.class.getSimpleName());rn rnrnrn[color=#FF0000]applicationContext.xml[/color]:(配置文件)rnrnrnrn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn WEB-INF/lib/jbpm-jpdl.jar rn rn rn rn rn rn rn rn rn rn org.hibernate.dialect.Oracle9Dialectrn rn rn rn org.hibernate.hql.ast.ASTQueryTranslatorFactory rn rn rn falsern rn rn rn true rn rn truern rn false rn 16rn rn rn rn rn rn rn rn rn com/fuyun/hp/hibernate/mapping/AdsModule.hbm.xml rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn rn
请教一个空指针异常问题 谢谢 了
rn rn rn rn 汽车名称rn rn rn rn rn rn rn rn rn rn rn rn rnrnrn rn rn rn rnrnrn rn rn rn rnrnpackage com.abc.service;rnrnimport com.abc.dao.CarDAO;rnimport com.abc.pojo.Car;rnrnpublic class CarService rn private CarDAO cd;rnrn public CarDAO getCd() rn return cd;rn rnrn public void setCd(CarDAO cd) rn this.cd = cd;rn rn public String save(Car car)rn String s ="fail";rn System.out.println(car.getCname());rn if(cd.save(car))rn s = "ok";rn rn return s;rn rnrn private CarService cs;rn public CarService getCs() rn return cs;rn rn public void setCs(CarService cs) rn this.cs = cs;rn rn public ActionForward execute(ActionMapping mapping, ActionForm form,rn HttpServletRequest request, HttpServletResponse response) rn CarForm c= (CarForm) form;// TODO Auto-generated method stubrn rn Car car = new Car();rn car.setCname(c.getCname());rn String s = "fail";rn System.out.println("car "+car.getCname());rn System.out.println(s+"ssssssssss");rn s = cs.save(car);rn return mapping.findForward(s);rn rn public boolean save(Car transientInstance) rn log.debug("saving Car instance");rn boolean b =false;rn try rn getHibernateTemplate().save(transientInstance);rn b=true;rn log.debug("save successful");rn catch (RuntimeException re) rn log.error("save failed", re);rn throw re;rn rn return b;rn rn rnrnrnrnrn
对象数组的空指针异常问题 新人求教
[code=java]rnimport java.util.Scanner;rnrnpublic class Main rnrn public static void main(String[] args) rn char choise;rn int size;rn Scanner sc = new Scanner(System.in);rnrn do rn System.out.println("------------------------------------------------");rn System.out.println("| Welcome to the BUU IT Wisdom Bank |");rn System.out.println("| What may I help you? |");rn System.out.println("| 1.开户 |");rn System.out.println("| 2.销户 |");rn System.out.println("| 3.按姓名查询 |");rn System.out.println("| 4.按账号查询 |");rn System.out.println("| 5.存钱 |");rn System.out.println("| 6.取钱 |");rn System.out.println("------------------------------------------------");rn System.out.println("");rn System.out.println("| Enter choice 1-6: |");rn System.out.println("");rn choise=sc.next().charAt(0);rn System.out.println();rn Account[] array=new Account[100];rn int i=0;rn switch (choise) rn case '1':rn for (int n=0;n<100;n++)rn rn array[n]=new Account("asd","asd","asd","asd",1);rn //我写的初始化遍历rnrnrn array[i]=new Account();rn array[i].setAccount();rn i++;rnrn break;rn case'2':rn System.out.println("请输入要删除的姓名或账号:");rn Scanner sd=new Scanner(System.in);rn String t=sd.nextLine();rn sd.close();rn for (int n=i;n<100;n++)rn rn array[n]=new Account("asd","asd","asd","asd",1);rn //调用那个查询那个就出现空指针异常 加上这个就出现rn // Exception in thread "main" java.util.NoSuchElementException: No line found at java.util.Scanner.nextLinernrn for (int y=0;y<=100;y++)rn rnrn if (array[y].getName().equals(t)) rnrn System.out.println("删除成功");rn else rn System.out.println("找不到");rn break;rn rn rnrnrn case'3':rn System.out.println("请输入要查找的姓名:");rn Scanner ss=new Scanner(System.in);rn String u=ss.nextLine();rn ss.close();rn for (int y=0;y<=100;y++)rn rn if (array[y].getName().equals(u))rn rn System.out.println("查询的姓名为:");rn array[y].getName();rn System.out.println("您的账号为:");rn array[y].getAccountNumber();rn System.out.println("您的余额为");rn array[y].getbalance();rn System.out.println("地址为:");rn array[y].getAdrees();rn rn elsern break;rn rn System.out.println("不存在");rn break;rn case'4':rn System.out.println("请输入要查找的账号:");rn Scanner sg=new Scanner(System.in);rn int m=sg.nextInt();rn sg.close();rn for (int y=0;y<=100;y++)rn rn if (array[y].getAccountNumber()==m)rn rn System.out.println("查询的姓名:");rn array[y].getName();rn System.out.println("您的账号为:");rn array[y].getAccountNumber();rn System.out.println("您的余额为");rn array[y].getbalance();rn System.out.println("地址为:");rn array[y].getAdrees();rn rn elsern break;rn rn System.out.println("不存在");rn break;rn case'5':rn System.out.println("请输入您的账号:");rn Scanner sqw=new Scanner(System.in);rn int qw=sqw.nextInt();rn sqw.close();rn for (int y=0;y<=100;y++)rn rn if (array[y].getAccountNumber()==qw)rn rn array[y].deposite();rn rn elsern break;rn rn break;rn case'6':rn System.out.println("请输入您的账号:");rn Scanner qwe=new Scanner(System.in);rn int qwr=qwe.nextInt();rn qwe.close();rn for (int y=0;y<=100;y++)rn rn if (array[y].getAccountNumber()==qwr)rn rn array[y].deposite();rn rn elsern break;rn rn case'7':rn System.out.println("Quit Succsess");rn break;rn default:System.out.println("illegl entry" );rn rnrnrn while (choise != '7');rnrnrnrn rnrnrn[/code]rnrnAccount类rn[code=java]rnimport java.util.Scanner;rnrnpublic class Account rn public int balance;rn public int Staticbalance;rn protected int AccountNumber;rn protected String IDcard;rn protected String Name;rn protected String Adrees;rn protected String password;rn public Account() rn rn public Account(String IDcard,String Name,String Adress,String password, int balance) rn this.IDcard=IDcard;rn this.Name=Name;rn this.Adrees=Adress;rn this.password=password;rn this.balance = balance;rn rn public void setStaticbalance()rn this.Staticbalance=Staticbalance;rn rn public void setAccountNumber() rn AccountNumber= (int) (Math.random()*1000000000);rn rnrn public void setBalance(int balance)rn this.balance=balance;rn rn public void setIDcard(String IDcard)rn rn this.IDcard=IDcard;rn rn public void setName(String Name)rn rn this.Name=Name;rn rn public void setAdrees(String Adress)rn this.Adrees=Adress;rn rn public void setPassword(String passwordrn )rn this.password=password;rn rn public String getName()rn return Name;rn rnrn public String getAdrees() rn return Adrees;rn rnrn public String getIDcard() rn return IDcard;rn rn public int getAccountNumber()rn return AccountNumber;rn rn public int getStaticbalance()return Staticbalance;rn public String getPassword() rn return password;rn rn public int getbalance()rn return balance;rn rn public void setbalance(int balance)rn this.balance=balance;rn rnrn public void setAccount()rn Scanner sc=new Scanner(System.in);rn System.out.println("请输入姓名:");rn String q=sc.nextLine();rn setName(q);rn System.out.println("请输入身份证:");rn String p=sc.nextLine();rn setIDcard(p);rn System.out.println("请输入地址:");rn String o=sc.nextLine();rn setAdrees(o);rn setBalance(100);rn setAccountNumber();rn rn public void deposite()rn System.out.println("请输入你需要存的现金:");rn Scanner sc=new Scanner(System.in);rn int w=sc.nextInt();rn System.out.println("1.活期 2.定期");rn int s=sc.nextInt();rn if (s==1)rn balance=balance+w;rn elsern rn Staticbalance=Staticbalance+w;rn System.out.println("最低存一年 一年内不可取");rn rn rn public void withdraw()rn System.out.println("请输入你要取得钱");rn Scanner sc=new Scanner(System.in);rn int w=sc.nextInt();rn if (balance>w)rn balance=balance-w;rn elsern System.out.println("您的余额不足!\n您的活期为"+balance+"定期为"+Staticbalance);rn rnrnrn[/code]
关于Volley网络请求框架空指针异常问题
今天试用了下Volley框架,运行时老师报这个错,郁闷了一会儿才发现,原来是在清单文件里面没有声明,擦 12-23 10:57:07.023 20997-20997/? E/AndroidRuntime: FATAL EXCEPTION: main                                                    java.lang.RuntimeExcep
调用WEBSERVICE出现空指针异常问题
调用代码如下:WEBSERVICE是通的,请问是什么原因啊,急....rnString endpoint="http://10.71.77.247/HZWGGZCLSERVICE/HZExceptionDisposeService.asmx";rnrn rnrn Service service = new Service();rnrn Call call = (Call)service.createCall();rnrn rnrn call.setTargetEndpointAddress(new java.net.URL(endpoint));rnrn call.setOperationName(new QName("http://10.71.77.247/hzwggzclservice","SendExceptionInfo"));rnrn rnrn call.addParameter("WorksheetNumber",org.apache.axis.encoding.XMLType.XSD_STRING,javax.xml.rpc.ParameterMode.IN);rnrn call.addParameter("TelephoneNumber",org.apache.axis.encoding.XMLType.XSD_STRING,javax.xml.rpc.ParameterMode.IN);rnrn call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);rnrn call.setUseSOAPAction(true);rnrn call.setSOAPActionURI("http://10.71.77.247/hzwggzclservice");rnrn rnrn rnrn res = (String)call.invoke(new Object[]bid,called);rnrn rnrn System.out.println( "result is ---------------------" + res + "----------.");rn
Android空指针异常问题,新手求教
[code=java]package com.stu.sqlite;rnrnimport java.util.ArrayList;rnimport java.util.HashMap;rnimport java.util.List;rnimport java.util.Map;rnrnimport com.stu.bean.Student;rnimport com.stu.service.StudentService;rnrnimport android.app.Activity;rnimport android.os.Bundle;rnimport android.widget.ListView;rnimport android.widget.SimpleAdapter;rnrnpublic class MainActivity extends Activity rn private StudentService studentService=null;rn private ListView listView=null;rn @Overridern public void onCreate(Bundle savedInstanceState) rn super.onCreate(savedInstanceState);rn setContentView(R.layout.main);rn studentService=new StudentService(getApplicationContext());rn rn listView=(ListView)findViewById(R.id.listView);rn rn show();rn rnrn private void show() rn List students=studentService.getScrollData(0,20);rn rn List> data=new ArrayList>();rn rn for(Student student:students)rn rn Map map=new HashMap();rn map.put("name",student.getName());rn map.put("age",student.getAge());rn map.put("money",student.getMoney());rn map.put("id",student.getId());rn data.add(map);rn rn rn //创建SimpleAdapter对象rn SimpleAdapter adapter=new SimpleAdapter(getApplicationContext(), data,R.layout.item,rn new String[]"name","age","money",new int[]R.id.name,R.id.age,R.id.money);rn rn [color=#FF0000]listView.setAdapter(adapter);//这个地方提示空指针异常[/color]rn rn rn[/code]rnrnrn
通过链接出现空指针异常问题,
有一个页面,单独执行时,一点问题都没,但通过链接就出现空指针异常了,没找到解决办法,来此处求助,希望大家多多指点.下面是代码,代码的目的是:当点击该链接,显示出全部数据,然后可以通过输入值进行查询.错误部分用红色标出rn<%@page contentType="text/html;charset=gb2312"%>rn<%@page import="java.sql.*"%>rnrnrn 设备信息rnrnrn 实验室设备管理系统rn----设备信息查询----rnrn rn rn 个人信息rn 使用情况rn 返回rn 退出rnrn rn rn rn 目前只支持通过设备号进行查询rn rn rn请输入设备号:rnrn rnrnrn rnrnrnrn rn rn rn 设备号rn rn 设备类别rn rn 出产商rn rn 价格rn rn 使用状态rn rn 所属实验室rnrn<%[color=#FF0000]rnString dno=new String(request.getParameter("no").getBytes("ISO8859-1"));rnif(dno==null)[/color]rnrntry //当没有输入设备号时直接显示出所有记录rnrn Class.forName("com.mysql.jdbc.Driver");rn Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/device","root","123456");rn Statement stmt=conn.createStatement();rn String sql="select * from dev";rn ResultSet rs=stmt.executeQuery(sql);rn if (!rs.next())rn rn out.println("没有数据!");rn rn elsern rn rs.previous();rn while (rs.next())rn rn String devno= new String (rs.getString("devno").getBytes("GB2312"));rn String devclass=new String (rs.getString("devclass").getBytes("GB2312"));rn String devfactory=new String (rs.getString("devfactory").getBytes("GB2312"));rn String devprice=new String (rs.getString("devprice").getBytes("GB2312"));rn String devstate=new String (rs.getString("devstate").getBytes("GB2312"));rn String labno=new String (rs.getString("labno").getBytes("GB2312"));rn%> rn rn rn rn <%=devno%>rn rn <%=devclass%>rn rn <%=devfactory%>rn rn <%=devprice%>rn rn <%=devstate%>rn rn <%=labno%>rn rn<% %>rn rn <%rn rs.close();rn stmt.close();rn conn.close();rn rnrncatch ( Exception e)rn out.println (e);rnrnelse//输入设备号进行查询rnrn tryrn rn Class.forName("com.mysql.jdbc.Driver");rn Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/device","root","123456");rn Statement stmt=conn.createStatement();rn String sql="select * from dev where devno='"+dno+"'";rn ResultSet rs=stmt.executeQuery(sql);rn if (!rs.next())rn rn out.println("没有数据!");rn rn elsern rn rs.previous();rn while (rs.next())rn rn String devno= new String (rs.getString("devno").getBytes("GB2312"));rn String devclass=new String (rs.getString("devclass").getBytes("GB2312"));rn String devfactory=new String (rs.getString("devfactory").getBytes("GB2312"));rn String devprice=new String (rs.getString("devprice").getBytes("GB2312"));rn String devstate=new String (rs.getString("devstate").getBytes("GB2312"));rn String labno=new String (rs.getString("labno").getBytes("GB2312"));rn%> rn rn rn rn <%=devno%>rn rn <%=devclass%>rn rn <%=devfactory%>rn rn <%=devprice%>rn rn <%=devstate%>rn rn <%=labno%>rn rn<% %>rn rn <%rn rs.close();rn stmt.close();rn conn.close();rn rnrncatch ( Exception e)rn rn out.println(e);rn rnrnrn%>rnrnrn
相关热词 c#检测非法字符 c#双屏截图 c#中怎么关闭线程 c# 显示服务器上的图片 api嵌入窗口 c# c# 控制网页 c# encrypt c#微信网页版登录 c# login 居中 c# 考试软件