2014-01-10 47 views
-1

我想首先采取整数N后跟N行,其中每行有两个坐标x和y。 (以空格分隔)。我尝试过,但它给NullPointerException。输入阅读输入分隔空间

class solution{ 

class Point{ 
int x; 
int y; 
} 
public static void main(String[] args) throws IOException { 
int N; 
Scanner in = new Scanner(System.in); 
BufferedReader inp = new BufferedReader (new InputStreamReader(System.in)); 
N=Integer.parseInt(in.next()); 
Point[] P = new Point[N]; 
for(i=0;i<N;i++){ 
String[] s1 = inp.readLine().split(" "); 
P[i].x=Integer.parseInt(s1[0]); 
P[i].y=Integer.parseInt(s1[1]); 
} 
} 

例如:

4 
2 4 
5 7 
8 9 
1 0 
+0

为什么你使用'Scanner'和'BufferedReader'呢?使用其中任何一个。 –

+1

好的,你能告诉我们你在哪一行得到NullPointerException? – Ajeesh

+0

@RohitJain只能去练习..并且请不要做任何作业 – user119249

回答

1

在你的程序异常发生在P[i].x=Integer.parseInt(s1[0]);

试试这个.....

public class solution{ 

    Set<Point> s=new LinkedHashSet<>(); 
    class Point{ 
    int x; 
    int y; 

    public Point(int x, int y) { 
     this.x = x; 
     this.y = y; 
    } 

    public int getX() { 
     return x; 
    } 

    public void setX(int x) { 
     this.x = x; 
    } 

    public int getY() { 
     return y; 
    } 

    public void setY(int y) { 
     this.y = y; 
    } 

    } 

    public static void main(String[] args) throws IOException { 
    solution s=new solution(); 
    s.setValues(); 
    s.printValues(); 
    } 

    private void setValues() { 
    int N; 
    System.out.println("Enter Limit:"); 
    Scanner in = new Scanner(System.in); 
    N=Integer.parseInt(in.nextLine()); 
    System.out.println("Enter "+N+" numbers with space:"); 
    for(int i=0;i<N;i++){ 
    String[] s1 = in.nextLine().split(" "); 
    s.add(new Point(Integer.parseInt(s1[0]),Integer.parseInt(s1[1]))); 
    } 
    } 

    private void printValues() { 
     System.out.println("Enter numbers are:"); 
     for (Iterator<Point> it = s.iterator(); it.hasNext();) { 
      Point s = it.next(); 
      System.out.println("x="+s.getX()+" and y="+s.getY()); 
     } 
    } 
} 

输出

Enter Limit: 
4 
Enter 4 numbers with space: 
4 8 
1 9 
7 8 
2 3 
Enter numbers are: 
x=4 and y=8 
x=1 and y=9 
x=7 and y=8 
x=2 and y=3 
0
import java.awt.Point; 
import java.io.IOException; 
import java.util.Scanner; 


public class Solution { 

    public static void main(final String[] args) throws IOException { 
     int size; 
     Scanner in = new Scanner(System.in); 
     size = Integer.parseInt(in.nextLine()); 
     Point[] points = new Point[size]; 
     for (int i = 0; i < size; i++) { 
      String[] pointInput = in.nextLine().split(" "); 
      points[i] = new Point(); 
      points[i].x = Integer.parseInt(pointInput[0]); 
      points[i].y = Integer.parseInt(pointInput[1]); 
     } 
     in.close(); 
     for (Point point : points) { 
      System.out.println("This is a point: " + point.x + ", " + point.y); 
     } 
    } 
} 

这是你说你想要做的一个工作示例。从你的问题和下面的评论来看,我会强烈建议你在继续这个之前通过关于Java的一些基本教程。因为除非你真正理解了在哪里发生了什么,给你这个答案最终没有任何用处。