Iothin :
I have a string (taken from file):
Computer: intel, graphic card: Nvidia,
Mouse: razer, color: white etc.
I need to take words between ":" and ",".
When I'm doing this in that way
Scanner sc = new Scanner(new File(path));
String str = sc.nextLine();
ArrayList<String> list = new ArrayList<String>();
while (sc.hasNextLine()) {
for (int i = 0; i < str.length(); i++) {
list.add(str.substring(str.indexOf(":"), str.indexOf(",")));
}
System.out.println("test");
sc.nextLine();
}
I'm only taking ": intel". I don't know how to take more word from same line and them word from next line.
Arvind Kumar Avinash :
Assuming the content of the file, test.txt
is as follows:
Computer: intel, graphic card: Nvidia
Mouse: razer, color: white
The following program will
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
class Coddersclub {
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(new File("test.txt"));
ArrayList<String> list = new ArrayList<String>();
String str = "";
while (sc.hasNextLine()) {
str = sc.nextLine();
String[] specs = str.split(",");
for (String item : specs) {
list.add(item.substring(item.indexOf(":") + 1).trim());
}
}
System.out.println(list);
}
}
output:
[intel, Nvidia, razer, white]
Note: if you are looking for the list to be as [: intel, : Nvidia, : razer, : white]
, replace list.add(item.substring(item.indexOf(":") + 1).trim());
with list.add(item.substring(item.indexOf(":")).trim());
.
Feel free to comment if you are looking for something else.