我试图将一个名为pt的Item对象的String从ReadAndSearch类中创建到事件类中。我无法让程序返回数据,对象的时间字段只能为NULL。 ReadAndSearch类中对象的字段中有数据。在显示<< ==注释时发生错误。这是我的第一个Java程序,我在这里学习。我不确定我错过了什么,无法找到它搜索Java 7 API或从谷歌搜索。以下是涉及的三个课程;项目,ReadAndSearch和事件。
public class Item {
private String name;
private String time;
public String getName() {
return this.name;
}
public String setName(String name){
this.name = name;
return name;
}
public String getTime() {
return this.time;
}
public String setTime(String time){
this.time = time;
return time;
}
}
public class Event implements ActionListener { //wiring for action listener
Item pt; //Put item assignment here, I think scope is part of the problem.
@Override
public void actionPerformed(ActionEvent e) {
newProductCode = parttextfield.getText(); //This is where I assign the input to a String object.
ReadAndSearch rs = new ReadAndSearch(); //Sending keyboard input to method readIt of class ReadAndSearch
rs.readIt(newProductCode); //Sending keyboard input to method readIt of class ReadAndSearch
String t = pt.getTime(); // <<== **This keeps pulling a NULL**
int convertedtime = Integer.parseInt(t); // <<== Added this line to convert String to int **Failed
System.out.println("If you can see this, " + convertedtime + " has been retrieved");
timerLabel.setText(" "+ convertedtime); //This is the first displayed element, then it is passed to TimeClass.
TimeClass tc = new TimeClass(convertedtime);
timer = new Timer(1000, tc); //tc is the actionListener the timer is waiting on.
timer.start();
}
}
public class ReadAndSearch {
public String line;
public String name;
public String time;
Item pt = new Item();
public void readIt(String newProductCode){ //method that takes screen input.
String findMe = newProductCode; //assign value of data passed in to the findMe variable.
try {
BufferedReader br = new BufferedReader(new FileReader("dataFile.csv")); // Open the file as a buffered reader.
int linecount = 0; // Start a line count and declare a string to hold our current line.
System.out.println("Searching for " + findMe + " in file..."); // Just to verify what I am searching for.
while (( line = br.readLine()) != null) { // Loops through each line, stashing the line into line variable.
linecount++; // Increment the count and find the index of the word.
int indexfound = line.indexOf(findMe.toUpperCase()); // Convert input to case match what is in data file.
if (indexfound > -1) { // If greater than -1, means the word was found.
String[] parts = line.split(","); // Splitting file lines by comma
name = parts[0]; // Line split, this is the part number.
time = parts[1]; // Line split, this is the time allocated.
System.out.println(name +" was found, " + time + " seconds are allocated for completion"); //For verification of search only.
}
}
pt.setTime(time);
pt.setName(name);
br.close(); // Close the file after searching.
}
catch (IOException e) {
System.out.println("IO Error Occurred: " + e.toString());
}
}
}