日期:2014-05-20  浏览次数:20795 次

Exception in thread "main" java.lang.NullPointerException
谁帮我分析分析,我是新手

import javax.swing.JOptionPane;

public class Demo2 {
class Mpoint{
double x,y;
Mpoint(){}
void getX(){
String input1 = JOptionPane.showInputDialog("x坐标:");
x = Double.parseDouble(input1);
x = 45;
}
void getY(){
String input2 = JOptionPane.showInputDialog("y坐标:");
y = Double.parseDouble(input2);
}
}

public static void main(String[] args){
int n = 0;
Mpoint p1 = null;
do{
String input=
JOptionPane.showInputDialog("1:x"+'\n'+"2:y"+'\n'+"3:退出");
n = Integer.parseInt(input);
switch(n){
case 1:
p1.getX();
case 2:
p1.getY();
case 3:
break;
}

}while(n<3);

}

}

------解决方案--------------------
Mpoint p1 = null;问题在这句话上。。。没有创建对象 肯定是Nullpointer
------解决方案--------------------
Java code

import javax.swing.JOptionPane;


class Mpoint{
double x,y;
Mpoint(){}
void getX(){
String input1 = JOptionPane.showInputDialog("x坐标:");
x = Double.parseDouble(input1);
System.out.println(x);
//x = 45;
}
void getY(){
String input2 = JOptionPane.showInputDialog("y坐标:");
y = Double.parseDouble(input2);
System.out.println(y);
}
}
public class Test4 {
public static void main(String[] args){
int n = 0;
Mpoint p1 = new Mpoint();
do{
String input=
JOptionPane.showInputDialog("1:x"+'\n'+"2:y"+'\n'+"3:退出");
n = Integer.parseInt(input);
System.out.println(n);
switch(n){
case 1:
p1.getX();
case 2:
p1.getY();
case 3:
break;
}

}while(n<3);

}

}