从Java中读取文件和空指针异常(Reading From File in Java and Null Pointer Exception)
我是java的新手,我遇到了一个我自己无法解决的问题。 我用Google搜索了异常,但问题太具体了,据我所知,所以我发现自己在这里。 这是我的问题。
我有一个名为Student的类,它有一个不合格的数据成员及其get / set方法:
private String studentNumber; private String firstName; private String lastName; private int age; private String gender; private String country;
然后我创建了一个实例数组:
Student studentList[] = new Student(10);
我有一个数据库(文本文件)作为休息
081935 Cengiz rrrrr Male 21 Turkey 082935 Ayşe aaaaa Female 22 England 083935 Onur bbbbb Male 23 Germany 084935 Fatma ccccc Female 24 Cyprus 085935 Ali dddd Male 21 China 086935 Zehra eeee Female 22 Denmark 087935 Murat ffff Male 25 France 088935 Selin ggggg Female 26 Japan 086935 Cengiz hhhh Male 20 Korea 080935 Damla qqqqqq Female 19 Iran
我想要做的是将所有这些信息传递给我的类实例,并尝试实现这一目标:
import java.io.*; import java.util.Scanner; public class StudentTracker { private static int counter = 0; private static Student studentList[]; public static void readFromFile() throws FileNotFoundException { File file = new File("Database.txt"); Scanner scanner = new Scanner(new FileReader(file)); try { while (scanner.hasNextLine()){ processLine(scanner.nextLine()); } } finally { scanner.close(); } } public static void processLine(String line) { Scanner scanner = new Scanner(line); scanner.useDelimiter(" "); if (scanner.hasNext()) { studentList[counter].setStudentNumber(scanner.next()); studentList[counter].setFirstName(scanner.next()); studentList[counter].setLastName(scanner.next()); studentList[counter].setGender(scanner.next()); studentList[counter].setAge(Integer.parseInt(scanner.next())); studentList[counter].setCountry(scanner.next()); counter++; } else { System.out.println("Empty or invalid line. Unable to process."); } } public static void main(String[] args) throws FileNotFoundException { studentList = new Student[10]; readFromFile(); for(int i = 0; i < 10; i++) { System.out.printf(studentList[i].getStudentNumber(), " ", studentList[i].getFirstName()); } } }
但它会导致以下错误:
Exception in thread "main" java.lang.NullPointerException at StudentTracker.processLine(StudentTracker.java:28) at StudentTracker.readFromFile(StudentTracker.java:16) at StudentTracker.main(StudentTracker.java:68)
顺便说一句找不到像C-scanf这样的函数,它获取输入直到第一个空格,所以我找到另一种解析字符串的方法
readFromFile()和processLine函数,但我不确定它们是否按预期工作。
先谢谢你
I'm pretty new to java and I've got a problem that I couldn't solve by myself. I googled the exception but problem is too specific as far as I can understand so I find myself here. Here is my problem.
I have a class called Student which has fallowing data members and their get/set methods:
private String studentNumber; private String firstName; private String lastName; private int age; private String gender; private String country;
and I created an array of instances as fallowing:
Student studentList[] = new Student(10);
I got a database(a text file) as fallowing
081935 Cengiz rrrrr Male 21 Turkey 082935 Ayşe aaaaa Female 22 England 083935 Onur bbbbb Male 23 Germany 084935 Fatma ccccc Female 24 Cyprus 085935 Ali dddd Male 21 China 086935 Zehra eeee Female 22 Denmark 087935 Murat ffff Male 25 France 088935 Selin ggggg Female 26 Japan 086935 Cengiz hhhh Male 20 Korea 080935 Damla qqqqqq Female 19 Iran
What I'm trying to do is getting all these informations to my class instances and I try to achieve this is fallowing:
import java.io.*; import java.util.Scanner; public class StudentTracker { private static int counter = 0; private static Student studentList[]; public static void readFromFile() throws FileNotFoundException { File file = new File("Database.txt"); Scanner scanner = new Scanner(new FileReader(file)); try { while (scanner.hasNextLine()){ processLine(scanner.nextLine()); } } finally { scanner.close(); } } public static void processLine(String line) { Scanner scanner = new Scanner(line); scanner.useDelimiter(" "); if (scanner.hasNext()) { studentList[counter].setStudentNumber(scanner.next()); studentList[counter].setFirstName(scanner.next()); studentList[counter].setLastName(scanner.next()); studentList[counter].setGender(scanner.next()); studentList[counter].setAge(Integer.parseInt(scanner.next())); studentList[counter].setCountry(scanner.next()); counter++; } else { System.out.println("Empty or invalid line. Unable to process."); } } public static void main(String[] args) throws FileNotFoundException { studentList = new Student[10]; readFromFile(); for(int i = 0; i < 10; i++) { System.out.printf(studentList[i].getStudentNumber(), " ", studentList[i].getFirstName()); } } }
but it gives fallowing error:
Exception in thread "main" java.lang.NullPointerException at StudentTracker.processLine(StudentTracker.java:28) at StudentTracker.readFromFile(StudentTracker.java:16) at StudentTracker.main(StudentTracker.java:68)
by the way couldn't find a function like C-scanf which gets the input until first white space so I find another way to parse the strings from line with
readFromFile() and processLine functions but I'm not sure if they're workig as intended.
Thank you in advance
原文:https://stackoverflow.com/questions/9791837
最满意答案
IntentService
是Context
的子类(就像Activity
,Application
和许多其他Android类一样)。 当然,您可以从IntentService
创建SharedPreferences
。 它将看到与应用程序中的任何Activity
或其他Context
相同的SharedPreferences
值。 (这就是为什么它被称为共享 。)你只需要确保在一个上下文中apply()
或commit()
在首选项编辑器中进行的更改,以便在其他地方看到更改。 这些都包含在文档中 。An
IntentService
is a subclass ofContext
(just as areActivity
,Application
, and many other Android classes). So of course you can create aSharedPreferences
from anIntentService
. It will see the sameSharedPreferences
values that anyActivity
or otherContext
in your application would see. (That's why it's called shared.) You just have to make sure that youapply()
orcommit()
changes made in the preference's editor in one context for the changes to be seen in other places. This is all covered in the docs.
相关问答
更多-
SharedPreferences应用程序上下文与活动上下文(SharedPreferences application context vs activity context)[2023-06-12]
值得回顾一下显示Context实例(无论是Activity还是Application实例)共享相同静态映射HashMap。 因此,无论何时通过Context.getSharedPreferences(name, mode)请求一个名为SharedPreferences的实例,您都会得到相同的实例,因为它首先检查映射是否已经为某个键(这是传递的名称)包含SharedPreferences实例。 一旦加载了SharedPreferences实例,它 ... -
你的代码似乎很完美! 您可以通过在所有“放置”操作之后提交所有内容来简化操作。 虽然我不认为这可能是你的问题...... 只需确保正确定义了SavedStartSilentHour和SavedStartSilentMinutes xml的定义值,即如果它们是相同的,它们将被覆盖。 (考虑到你的代码,这是唯一对我有意义的事情)。 让我们知道你的进步;) Your code seems perfect! You could simplify the thing by committing all the stu ...
-
IntentService是Context的子类(就像Activity , Application和许多其他Android类一样)。 当然,您可以从IntentService创建SharedPreferences 。 它将看到与应用程序中的任何Activity或其他Context相同的SharedPreferences值。 (这就是为什么它被称为共享 。)你只需要确保在一个上下文中apply()或commit()在首选项编辑器中进行的更改,以便在其他地方看到更改。 这些都包含在文档中 。 An Intent ...
-
当然,您也可以使用应用程序上下文来显示吐司和共享前缀,因为它们都是在不与活动交互的情况下使用。 简单的例子就像服务,你可以使用这两个从服务和服务没有任何活动的参考,但它工作正常.. Yes definitely you can use application context for show toast and sharedprefrence also , Because they both are use without interact with activity. Simple example is ...
-
您需要将此代码放入Activity方法onCreate中。 活动无法实例化为常规类。 把你在构造函数中的内容放在像这样的方法中: public void onCreate(Bundle bundles) { } 只有这样,Context才能以正确的方式提供 this 将引用正确的上下文。 编辑: 你可以这样做: public Lesson1(String name, Context context) { super(name); SharedPreferences myPrefere ...
-
您应该在
标记中添加name=".ContextGetter" 。 You should add name=".ContextGetter" to manifest in tag. -
静态SharedPreferences(Static SharedPreferences)[2023-10-17]
您可以从Application wide共享首选项中保存并加载,而不是将prefs私有加载到Activity : private static boolean load(String tag) { SharedPreferences sharedPreferences = Context.getApplicationContext().getSharedPreferences("namespace", Context.MODE_PRIVATE); return sharedPreferenc ... -
如果你需要在Config.java中由REGISTER_URL存储的链接,你应该只是简单地得到它 String url = Config.REGISTER_URL; 你的代码 SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE); String RREGISTER_URL = sharedPreferences.getString(Config.RE ...
-
如何将SharedPreferences与BroadcastReceiver一起使用(How to use SharedPreferences with BroadcastReceiver)[2021-04-13]
如果Activity是与Receiver相同的应用程序的一部分,则在Activity内部子类化可能更容易: class MyActivity extends Activity { private BroadcastReceiver wifiBR = null; // All the usual things // And add in @Override public void onCreate() { // EVerything else ... -
你需要执行提交,以便在优先级中保存值,所以只需在添加任何内容后编写editor.commit() ,请检查更新的方法 public void checkLogin(){ // Check login status editor.putBoolean("login", true);// even if add true it will return false editor.commit(); if(!this.isLoggedIn()){ Toast.ma ...