gpt4 book ai didi

java - 从文件获取整数时出错(将字符串转换为整数)

转载 作者:行者123 更新时间:2023-12-02 05:34:49 25 4
gpt4 key购买 nike

我有一个文件:student.txt

1      Adam     50       50       50

2 Eric 34 28 38

3 Joash 44 48 49

4 Bill 34 30 45

我有 2 个类:1 个是主类,另一个负责所有工作。

// Class 1 ******************

public class Main {
public static void main(String[] args) {
readfile a = new readfile();
a.openFile();
a.readFile();
a.closeFile();
}
}

// ********* Class 2

import java.util.*;
import java.io.*;
import java.lang.*;

public class readfile {

private Scanner x;

public void openFile(){
try{
x = new Scanner(new File("student.txt"));

}
catch(Exception e){
System.out.println("Error");
}
}
public void readFile(){
int a=0;
String b;
int c=0;
int d = 0;
int e = 0;
int total;
while(x.hasNext()){
a = x.next();
b = x.next();
c = x.next();
d = x.next();
e = x.next();
int total = c+d+e;
total = x.nextInt();
System.out.printf("%s %s %s %s %s %s/n",a,b,c,d,e,total);
}
}
public void closeFile(){
x.close();
}
}

我有两个错误:

1) 这是在 a = x.next(); 的地方

Can't convert from String to int.

你能告诉我如何解决这个问题吗?

2)这是在:

Exception in thread "main"

Error java.lang.NullPointerException

如何解决这个问题?

最佳答案

尝试:

a = Integer.parseInt(x.next());

而不是

a = x.next();

你可以尝试使用

a = x.nextInt();

关于java - 从文件获取整数时出错(将字符串转换为整数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25090976/

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