扫描仪nextLine问题

时间:2014-08-29 05:12:48

标签: java java.util.scanner

我正在编写一个读取以下输入的代码

3
Ruby
Diamond
Sapphire

这是我的程序

import java.util.Scanner;

public class GemStones {

    private int numOfStones;
    private String[] gemArray;

    public void solve() throws Exception{

        Scanner in = new Scanner(System.in);

        //Reading the integer
        numOfStones = Integer.parseInt(in.nextLine());
        //in.nextLine();
        System.out.println(numOfStones);


        //reading the strings
        for(int i=0;i<numOfStones;i++){
            gemArray[i] = in.nextLine();
            System.out.println(gemArray[i]);
        }


        for(int i=0;i<numOfStones;i++){
            System.out.println(gemArray[i]);
        }
        in.close();
    }


    public static void main(String[] args) throws Exception {
        GemStones check = new GemStones();
        check.solve();


    }

}

我在阅读后面的字符串时遇到问题。每当我尝试读取字符串时,它就会显示错误!请帮帮我..

以下是我在控制台中收到的错误

3
Ruby
Diamond
Sapphire3Exception in thread "main" 
java.lang.NullPointerException
    at com.sudarabisheck.easy.GemStones.solve(GemStones.java:23)
    at com.sudarabisheck.easy.GemStones.main(GemStones.java:37)

3 个答案:

答案 0 :(得分:1)

主要问题是,一旦您阅读了要输入的宝石数量,就不会在使用之前初始化gemArray ......

numOfStones = Integer.parseInt(in.nextLine());
//in.nextLine();
System.out.println(numOfStones);

//reading the strings
for (int i = 0; i < numOfStones; i++) {
    gemArray[i] = in.nextLine();
    System.out.println(gemArray[i]);
}

您应该使用numOfStones值初始化gemArray

numOfStones = Integer.parseInt(in.nextLine());
//in.nextLine();
System.out.println(numOfStones);

// Intialise gemStones here...
gemStones = new String[numOfStones];

//reading the strings
for (int i = 0; i < numOfStones; i++) {
    gemArray[i] = in.nextLine();
    System.out.println(gemArray[i]);
}

答案 1 :(得分:1)

您永远不会对数组gmeArray进行初始化,因此请添加初始化:

public void solve() throws Exception{

            Scanner in = new Scanner(System.in);

            //Reading the integer
            numOfStones = Integer.parseInt(in.nextLine());
            //in.nextLine();
            System.out.println(numOfStones);

            gemArray = new String[numOfStones];
            //reading the strings
            for(int i=0;i<numOfStones;i++){
                gemArray[i] = in.nextLine();
                System.out.println(gemArray[i]);
            }


            for(int i=0;i<numOfStones;i++){
                System.out.println(gemArray[i]);
            }
            in.close();
        }

答案 2 :(得分:1)

您需要将数组初始化为

gemArray = new String[numOfStones];