KaiquanMah's picture
String row = reader.nextLine(); String[] chunks = row.split(","); Integer.valueOf(chunk);
150962c verified
raw
history blame
2.27 kB
nextLine() - returns String
valueOf() - Integer OR Double
===================================================================
import java.util.Arrays;
public class Example {
public static void main(String[] args){
String str = "first,second,third";
String[] chunks = str.split(",");
//print array - [first, second, third]
System.out.println(Arrays.toString(chunks));
//print string elements
for (String chunk : chunks) {
System.out.println(chunk);
}
String sentence ="This is a sentence with many words";
String[] words = sentence.split(" ");
System.out.println(Arrays.toString(words));
for (String word : words) {
System.out.println(word);
}
}
}
Program outputs:
[first, second, third]
first
second
third
[This, is, a, sentence, with, many, words]
This
is
a
sentence
with
many
words
===================================================================
eg
luvut/numbers.csv
1,4,3,5,2,4,5,2
4,5,11,2,4,2,5,4,3
6,7,5,2,3,3,2,4,6
8,7,4,5,4,3,3,2,1
0,0,2,4,2,0,2,5,3
reads the file
decomposes each line into chunks,
converts the chunks to integers and
finally calculates the sum of the numbers:
import java.io.FileNotFoundException;
import java.io.File;
import java.util.Scanner;
public class Example {
public static void main(String[] args){
File file = new File("luvut.csv");
// read the file
try(Scanner reader = new Scanner(file)) {
int sum = 0;
while (reader.hasNextLine()) {
// process line by line
String row = reader.nextLine();
// split into an array of number strings
String[] chunks = row.split(",");
// parse each number string as Integer
for (String chunk : chunks) {
int num = Integer.valueOf(chunk);
sum += num;
}
}
System.out.println("Sum of the numbers: " + sum);
}
catch (FileNotFoundException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Program outputs:
Sum of the numbers: 159