Basically I have this Java program and I want to enter 2 specific values for lineIndex and wordIndex and add the word that matches these coordinates to the ArrayList fileWords.
Sample file content:
worda wordb wordc wordd
worde wordf wordg wordh
wordi wordj wordk wordl
wordm wordn wordo wordp
This code simply adds all the words in the List. How should it look if I want it to match my needs?
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<String> fileWords = new ArrayList<>();
String filePath = "x file path";
int lineIndex = 0;
int wordIndex =0;
addWordsToArray(fileWords,filePath,lineIndex,wordIndex);
}
public static void addWordsToArray(ArrayList<String> fileWords, String filePath,int lineIndex, int wordIndex) {
Scanner tmp1 = null;
try {
tmp1 = new Scanner(new File(filePath));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (tmp1.hasNextLine()) {
Scanner tmp2 = new Scanner(tmp1.nextLine());
while (tmp2.hasNext()) {
String s = tmp2.next();
fileWords.add(s);
}
}
}
CodePudding user response:
You are not checking for any conditions in the code and that is why it is adding all the words to the list.
public static void addWordsToArray(ArrayList<String> fileWords, String filePath,int lineIndex, int wordIndex) {
Scanner tmp1 = null;
try {
tmp1 = new Scanner(new File(filePath));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int currentLineIndex = 0;
int currentWordIndex = 0;
while (tmp1.hasNextLine()) {
Scanner tmp2 = new Scanner(tmp1.nextLine());
if(currentLineIndex == lineIndex) {
while (tmp2.hasNext()) {
String s = tmp2.next();
if(currentWordIndex == wordIndex){
fileWords.add(s);
}
currentWordIndex ;
}
}
currentLineIndex ;
}
}
You can do something like the given code to achieve what you want.
NOTE: Logic assumes that the indexes are zero based, i.e. lineIndex = 0
means the first line and wordIndex = 0
means the first word.