CODE:
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(reader);
String input = in.readLine();
ArrayList<String> massiiv = new ArrayList();
for (int i = 0; i < input.length(); i++)
massiiv.add(input[i]); // error here
HI!
How can I split the input and add the input to the data structure massiiv?
For instance, input is: "Where do you live?". Then the massiiv show be:
massiv[0] = where
massiv[1] = do
massiv[2] = you
THANKS!
The Java Documentation is your friend:
http://download.oracle.com/javase/6/docs/api/java/lang/String.html
String[] myWords = input.split(" ");
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(reader);
String input = in.readLine();
String[] massiiv = input.split(" ");
Use a StringTokenizer, which allows an application to break a string into tokens.
Use space as delimiter, set the returnDelims flag to false such that space only serves to separate tokens. Then
StringTokenizer st = new StringTokenizer("this is a test");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
prints the following output:
this
is
a
test
Try using split(String regex).
String[] inputs = in.readLine().split(" "); //split string into array
ArrayList<String> massiiv = new ArrayList();
for (String input : inputs) {
massiiv.add(inputs);
}
You would use the string.split() method in java. In your case, you want to split on spaces in the string, so your code would be:
massiiv = new ArrayList(input.split(" "));
If you don't want to have the word you in your output, you would have to do additional processing.
A one-line solution. Any amount of whitespace possible between the strings.
ArrayList<String> massiiv = new ArrayList(Arrays.asList(input.split("\\s+")));
Related
My file
ABABCCC
My java code:
BufferedReader br = new BufferedReader(new FileReader("My file"));
StringTokenizer sr = new StringTokenizer(br.readLine());
char[] problem = null;
int i = 0;
while(sr.hasMoreTokens())
{
problem[i] = sr.nextToken();
i++;
}
desired output:
problem[0] = 'A'
problem[1] = 'B'
and so on
Please help me in this and provide me a good method for this.
You don't need a StringTokenizer for this data. Just read the data from the file into a String and convert it to a char array.
String line = br.readLine();
char[] problem = line.toCharArray();
You'd only need a loop to read this data if you had multiple lines in your file, or if you had multiple tokens to parse.
StingTokenizer doesn't split up a line by chars it will do it by tokens which is equivalent to words in a sentence. Here is an example usage of that class.
You can store the entire line into a string and then convert that into the char array you have setup.
String fileInput = br.readLine();
char[] problem = fileInput.toCharArray();
You shouldn't be using StringTokenizer, from the Javadoc -
StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.
If I understand what you're trying to do, here's one way to do it with a Scanner and String.toCharArray() -
Scanner sc;
char[] problem = null;
try {
sc = new Scanner(new File("My file"));
if (sc.hasNext()) {
problem = sc.next().toCharArray();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println(Arrays.toString(problem));
What is the best way to split a string containing three words?
My code looks like this right now (see below for updated code):
BufferedReader infile = new BufferedReader(new FileReader("file.txt"));
String line;
int i = 0;
while ((line = infile.readLine()) != null) {
String first, second, last;
//Split line into first, second and last (word)
//Do something with words (no help needed)
i++;
}
Here is the full file.txt:
Allegrettho Albert 0111-27543
Brio Britta 0113-45771
Cresendo Crister 0111-27440
Dacapo Dan 0111-90519
Dolce Dolly 0116-31418
Espressivo Eskil 0116-19042
Fortissimo Folke 0118-37547
Galanto Gunnel 0112-61805
Glissando Gloria 0112-43918
Grazioso Grace 0112-43509
Hysterico Hilding 0119-71296
Interludio Inga 0116-22709
Jubilato Johan 0111-47678
Kverulando Kajsa 0119-34995
Legato Lasse 0116-26995
Majestoso Maja 0116-80308
Marcato Maria 0113-25788
Molto Maja 0117-91490
Nontroppo Maistro 0119-12663
Obligato Osvald 0112-75541
Parlando Palle 0112-84460
Piano Pia 0111-10729
Portato Putte 0112-61412
Presto Pelle 0113-54895
Ritardando Rita 0117-20295
Staccato Stina 0112-12107
Subito Sune 0111-37574
Tempo Kalle 0114-95968
Unisono Uno 0113-16714
Virtuoso Vilhelm 0114-10931
Xelerando Axel 0113-89124
New code as #Pshemo suggested:
public String load() {
try {
Scanner scanner = new Scanner(new File("reg.txt"));
while (scanner.hasNextLine()) {
String firstname = scanner.next();
String lastname = scanner.next();
String number = scanner.next();
list.add(new Entry(firstname, lastname, number));
}
msg = "The file reg.txt has been opened";
return msg;
} catch (NumberFormatException ne) {
msg = ("Can't find reg.txt");
return msg;
} catch (IOException ie) {
msg = ("Can't find reg.txt");
return msg;
}
}
I receive multiple errors, what's wrong?
Assuming that each line always contains exactly three words instead of split you can simply use Scanners method next three times for each line.
Scanner scanner = new Scanner(new File("file.txt"));
int i = 0;
while (scanner.hasNextLine()) {
String first = scanner.next();
String second = scanner.next();
String last = scanner.next();
//System.out.println(first+": "+second+": "+last);
i++;
}
line.split("\\s+"); // don't use " ". use "\\s+" for more than one whitespace
Assuming the line has 3+ words, use the split(delimiter) method:
String line = ...;
String[] parts = line.split("\\s+"); // Assuming words are separated by whitespaces, use another if required
then you can access to the first, second and last respectively:
String first = parts[0];
String second = parts[1];
String last = parts[parts.length() - 1];
Remember that indexes starts with 0.
String []parts=line.split("\\s+");
System.out.println(parts[0]);
System.out.println(parts[1]);
System.out.println(parts[parts.length-1]);
I have this code:
BufferedReader br =new BufferedReader(new FileReader("userdetails.txt"));
String str;
ArrayList<String> stringList = new ArrayList<String>();
while ((str=br.readLine())!=null){
String datavalue [] = str.split(",");
String category = datavalue[0];
String value = datavalue[1];
stringList.add(category);
stringList.add(value);
}
br.close();
it works when the variables category and value do not have a comma(,),however the values in the variable value does contain commas.Is there a way that I can split the index of the without using comma?
The solution is given bellow:
BufferedReader br =new BufferedReader(new FileReader("userdetails.txt"));
String str;
ArrayList<String> stringList = new ArrayList<String>();
while ((str=br.readLine())!=null){
int firstIndexOfComma = str.indexOf(',');
String category = str.substring(0, firstIndexOfComma);
String value = str.substring(firstIndexOfComma + 1);
stringList.add(category);
stringList.add(value);
System.out.println(category+" "+value);
}
br.close();
When data has ',' it is generally called CSV file. OpenCSV is fairly used library to handle it. The format looks simple, but it has it quirks. See wikipedia for some details
If I understood you correctly:
String str = "category,vvvv,vvv";
int i = str.indexOf(',');
String category = str.substring(0, i);
String value = str.substring(i + 1);
split() uses regex.
if the reader code works perfectly, do
str.split("\\,");
Not 100% sure, but couldnt you just do
String datavalue [] = str.split("--");
or something?
sample file:
x,y,z--123--Hello World
output:
"x,y,z",
"123",
"Hello World"
I am trying to read a BufferedReader that reads in a file containing records separated by commas. I would like to split each string (or record) in between two commas, strip the double quotes, and put each of those into an index of a String array. For example:
say I have this line in the file:
("0001", "00203", "82409" (newline)
"0002", "00204", "82500" (newline)
etc.)
I want to put 0001 into a String array[1],
I want 00203 into String array[2],
and so on....
The following code traverses the file, putting all records in column two into String array[2]. This means, after I execute the code below, if I do System.out.println (arr[2]), it will print 00203 and 00204, whereas I would like array[2] to be 00203 and array[5] to be 00204.
Here is my code:
public String[] getArray(String source) {
FileInputStream fileinput = new FileInputStream(source);
GZIPInputStream gzip = new GZIPInputStream(fileinput);
InputStreamReader inputstream = new InputStreamReader(gzip);
BufferedReader bufr = new BufferedReader(inputstream);
String str = null;
String[] arr = null;
while((str = bufr.readLine()) != null) {
arr = str.replace("\"", "").split("\\s*,\\s*");
}
return arr;
Commons CSV was designed for your specific use case. Let's not reinvent the wheel, the code below will result in a GZipped CSV being parsed into fields and lines and seems to be what you're trying to do.
public String[][] getInfo() throws IOException {
final CSVParser parser = new CSVParser(new FileReader(new InputStreamReader(new GZIPInputStream(fileinput)), CSVFormat.DEFAULT.withIgnoreSurroundingSpaces(true));
String[][] result = parser.nextRecord().values();
return result;
}
Few of these modifications should work for you.
public String[] getArray(String source) {
FileInputStream fileinput = new FileInputStream(source);
GZIPInputStream gzip = new GZIPInputStream(fileinput);
InputStreamReader inputstream = new InputStreamReader(gzip);
BufferedReader bufr = new BufferedReader(inputstream);
String str = null;
List<String> numbers = new LinkedList<String>;
while((str = bufr.readLine()) != null) {
String[] localArr = str.split(",");
for(String intString : localArr){
numbers.add(intString.trim());
}
}
return arr;
Have you tried using the scanner class as well as scanner.nextInt(). you do not need to do striping then.
Scanner s = new Scanner(inputstream);
ArrayList<String> list = new ArrayList<String>();
while (s.hasNextInt())
list.add(s.nextInt());
String[] arr = list.toArray(new String[list.size()]);
Not tested:
arr = str.replaceAll("\"", "").replaceAll("(","").replaceAll(")","").split(",");
I know this is a very asked question but I can't find and apropiate answer for my problem. Thing is I have to program and aplication that reads from a .TXT file like this
Real:Atelti
Alcorcon:getafe
Barcelona:Sporting
My question is how what can I do to tell Java that I want String before : in one ArrayList and Strings after : in another ArrayList?? I guess It's using delimeter method but I don't know how use it in this case.
Sorry for my poor english, I've to improve It i guess. Thanks
use split function of java.
steps:
Declare two arrayList. l1 and l2;
read each line.
split each line by ":", this will return a array of length 2, array. (as per your input)
l1.add(array[0]) , l2.add(array1)
try yourself, post code if you need help :)
check here for use of split function, though through google you can find many different example
Split the string using ":" as delimiter. Add the odd entries from the result to one list and even to another list.
If your text is like this:
Real:Atelti
Alcorcon:getafe
Barcelona:Sporting
You can achieve what you want by using:
StringBuilder text = new StringBuilder();
Scanner scanner = new Scanner(new FileInputStream(fFileName), encoding); //try utf8 or utf-8 for 'encoding'
try {
while (scanner.hasNextLine()){
String line = scanner.nextLine();
String before = line.split(":")[0];
String after = line.split(":")[1];
//dsw 'before' and 'after' - add them to lists.
}
}
finally{
scanner.close();
}
Scanner scanner = new Scanner(new FileInputStream("YOUR_FILE_PATH"));
List<String> firstList = new ArrayList<String>();
List<String> secondList = new ArrayList<String>();
while(scanner.hasNextLine()) {
String currentLine = scanner.nextLine();
String[] tokenizedString = currentLine.split(":");
firstList.add(tokenizedString[0]);
secondList.add(tokenizedString[1]);
}
scanner.close();
Enumerating firstList and secondList will get you the desired result.
1. Use ":" as delimiter.
2. Then Store them in the String[] using split() function.
3. Try using BufferedReader instead of Scanner.
Eg:
File f = new File("d:\\Mytext.txt");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
ArrayList<String> s1 = new ArrayList<String>();
ArrayList<String> s2 = new ArrayList<String>();
while ((br.readLine())!=null){
String line = br.readLine();
String bf = line.split(":")[0];
String af = line.split(":")[1];
s1.add(bf);
s2.add(af);
}