分成 java 导致 "java.lang.NumberFormatException: For input string: "

split in java causing "java.lang.NumberFormatException: For input string: "

这里我写了一段代码

try {
        ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("vectorValues.txt"));
        HashMap tokenVector = new HashMap();
        while(true){
            System.out.println("Enter word : ");
            word = scan.next(); //giving input normal word
            System.out.println("Enter Vector values <happy,sad,angry,surprise> :");             
            vec = scan.nextLine(); //giving input as vector : "8 5 6 7"
            firstLine = vec.split(" ");
            //Here I am trying to print
            for(String s:firstLine)
                System.out.println("Splitted part : "+s);
            hap = Integer.parseInt(firstLine[0]); 
            sad = Integer.parseInt(firstLine[1]);
            ang = Integer.parseInt(firstLine[2]);
            sur = Integer.parseInt(firstLine[3]); 

            tokenVector.put(word, new Vector(hap,sad,ang,sur));

            System.out.println("Enter more : (0 for no) : ");
            if(scan.nextInt()==0)
                break;
        }
        os.writeObject(tokenVector);
        os.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

矢量 class 在这里

class Vector implements Serializable{
    int happy,sad,angry,surprise;
    public Vector(int hap,int sad,int ang,int sur){
        happy = hap;
        this.sad = sad;
        angry = ang;
        surprise = sur;
    }
    public String toString(){
        return ""+happy+" "+sad+" "+angry+" "+surprise+"\n";
    }
}

这会产生以下错误

Enter word : 
4 5 6 7
Enter Vector values <happy,sad,angry,surprise> :
Splitted part : 
Splitted part : 5
Splitted part : 6
Splitted part : 7
java.lang.NumberFormatException: For input string: ""
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:592)
    at java.lang.Integer.parseInt(Integer.java:615)
    at FileHandler.inputIntoFile(FileHandler.java:35)
    at FileHandler.main(FileHandler.java:13)

正在使用 next() 接受单词,但它不等待 nextLine() 输入变量 vec()。它是否在 next() 时从先前的标准输入中获取了 '\n' 字符并直接移动到下一行,从而仅将空白字符串存储到导致 NumberFormatException 的 vec 中?

问题可能是您没有用完第一条语句中的 \n 字符:

 System.out.println("Enter word : ");
            word = scan.next(); //try nextLine() here
            System.out.println("Enter Vector values <happy,sad,angry,surprise> :");             
            vec = scan.nextLine(); //giving input as "8 5 6 7"
            firstLine = vec.split(" ");

第一次输入时尝试 nextLine()

word = scan.nextLine();

或在赞后加上nextLine():

word = scan.next();
scan.nextLine();

在你的 nextInt() 之后输入:

if(scan.nextInt()==0)
                break;
scan.nextLine();