[英]How to read in integers from a file in Java
好的,我想读取文件中包含的整数以及字符串。 到目前为止,我已经有了这段代码,并且不断出现错误。 我的文本文件中有这个:Grey:30 Black:40我试图读取字符串和整数,因为我想将整数设置为值得该字符串(彩色)的点
while (strike!=3){
Scanner name1 = new Scanner(System.in);
System.out.println("Enter A color");
String nameTaken = name1.next();
while(filechecker.hasNextLine()){
list.add(filechecker.nextLine());
}
String line =filechecker.nextLine();
String[] details = line.split(":");//checks for the integer next to the color
if((list.contains(nameTaken))&&(filechecker.hasNextInt())){
int points = Integer.parseInt(details[2]);
System.out.println("The Answer Exists!! You Got " +details[2]);
您没有指出要得到什么错误,但是从以下代码中可以看到,您很可能会收到NullPointerException
或类似的错误。
编辑 :似乎您正在获取NoSuchElementException
因为没有行要读取。
此代码块循环遍历您的filechecker
,并将所有行读入列表,直到不再剩余行。 在while块之后的那一行试图从中读取另一行,但由于您已全部读取,因此找不到该行(它将返回null
)。 因此,您尝试split
行将引发异常。
while(filechecker.hasNextLine()){
list.add(filechecker.nextLine());
}
String line =filechecker.nextLine(); // <-- this line is throwing it. Don't use it here, use your list or do your work in the while loop instead.
String[] details = line.split(":");//checks for the integer next to the color
循环使用后,而不是循环使用filechecker
。 或者更好的是,改为在 while循环中完成所有工作。
使用HashMap来存储数据可能会更容易:
HashMap<String, Integer> colorData = new HashMap<String, Integer>();
然后,您可以使用ObjectOutputStream和ObjectInputStream写入和读取文件:
void write(String fileName) {
FileOutputStream fileOut = new FileOutputStream(fileName);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(colorData);
}
void read(String fileName) {
ObjectInputStream in = null;
try {
fileIn = new FileInputStream(fileName);
in = new ObjectInputStream(fileIn);
colorData = (HashMap<String, Integer>) in.readObject();
} catch (Exception e) {
e.printStackTrace();
}finally {
if(objectinputstream != null)
objectinputstream .close();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.