gpt4 book ai didi

java - java中的 split 导致 "java.lang.NumberFormatException: For input string: "

转载 作者:太空宇宙 更新时间:2023-11-04 06:15:45 27 4
gpt4 key购买 nike

这里我写了一段代码

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();
}

vector 类在这里

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()放在like后面:

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

nextInt() 之后放置:

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

关于java - java中的 split 导致 "java.lang.NumberFormatException: For input string: ",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28118262/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com