[英]having String Index Out Of Bounds Exception while file reading
public List<SoruKelime> getAllQuestion() {
List<SoruKelime> questions = new ArrayList<>();
try {
Scanner myReader = new Scanner(myFile);
while (myReader.hasNextLine()) {
String data;
data = myReader.nextLine();
int index = data.indexOf("&");
String question = data.substring(0, index);
String answer = data.substring(index+1);
SoruKelime soru = new SoruKelime();
soru.setSoru(question);
soru.setKelime(answer);
questions.add(soru);
}
myReader.close();
} catch (FileNotFoundException exception) {
exception.printStackTrace();
}
return questions;
}
@Override
public void initialize(URL url, ResourceBundle rb) {
FileProcess fileProcess = new FileProcess();
List<SoruKelime> sorular = new LinkedList<SoruKelime>();
SoruKelime cekilenSoru = new SoruKelime();
sorular = (ArrayList<SoruKelime>) fileProcess.getAllQuestion();
cekilenSoru = sorular.get(0);
this.soruLabel.setText(cekilenSoru.getSoru());
}
Caused by: java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1967)
at word_game.FileProcess.getAllQuestion(FileProcess.java:53)
at word_game.GameController.initialize(GameController.java:34)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2548)
while i'm reading a file in java with javafx i'm having this kind of issue.当我用 javafx 读取 java 中的文件时,我遇到了这种问题。 i've tried to change linkedList to List but that didn't work.
我试图将linkedList 更改为List,但没有奏效。 I don't know what else I can do.
我不知道我还能做什么。 Can you help me about that
你能帮我解决这个问题吗
You might have a line where there isn't an ampersand (&).您可能有一条没有与号 (&) 的行。 Now, it is always a nice practice to assure yourself that what you're going to access exists, so you won't end up with NullPointers or IndexOutOfBounds.
现在,向自己保证要访问的内容存在始终是一种很好的做法,这样您就不会得到 NullPointers 或 IndexOutOfBounds。
List<SoruKelime> questions = new ArrayList<>();
try {
Scanner myReader = new Scanner(myFile);
while (myReader.hasNextLine()) {
String data;
data = myReader.nextLine();
int index = data.indexOf('&');
if(index==-1 || index > data.length){
//There is no &, do something
}else{
String question = data.substring(0, index);
String answer = data.substring(index+1);
SoruKelime soru = new SoruKelime();
soru.setSoru(question);
soru.setKelime(answer);
questions.add(soru);
}
}
myReader.close();
} catch (FileNotFoundException exception) {
exception.printStackTrace();
}
return questions;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.