读取由空格分隔的输入

时间:2014-01-10 16:31:31

标签: java nullpointerexception

我想首先取整数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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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的基础教程。因为除非你真正理解在哪里发生了什么,否则给你这个答案最终将没有任何用处。