Java CSV data String array to double - java

Hi i have a CSV file with 2 column, i can read the data and i did split it for 2 part String[] country = line.split(";");, i did split country[1] String[] price_split = country[1].split(" "); and got 2 part, the first part is (yes i know that all item is string)(first item a string and the other 4 item is double), i want to convert the 4 double from price_split[0] to 4 distinct double
my code is
String csvFile = "pontcsoport.csv";
BufferedReader br = null;
String line = "";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
String[] country = line.split(";");
String[] price_split = country[1].split(" ");
System.out.println(price_split[0]);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done");
and the output is:
price
70.99
21.38
19.24
12.83
Done
So i want that double a=70.99; double b=21.38; etc

If you want to convert String to Double use,
String str = "12.00";
double d = Double.parseDouble(str);
If you want to store the details as Double format create a list with Double & store accordingly.
List<Double> doubleDTList = new ArrayList<Double>();
while ((line = br.readLine()) != null) {
// Other Stuff's
System.out.println(price_split[0]);
try{
doubleDTList.add(Double.parseDouble(price_split[0]));
} catch(NumberFormatException e){
}
}
And this doubleDTList contains all the values.

Related

Reading from text file saving it and printing it out into a text

I hope someone can help me.
I am trying to create a program to read variables from an input file to output file
the input file is as follows employee's first name, two double precision values, seller's salary and the total value sold by him/her.
JOAO
450.00
1230.30
FDJSI
333.00
2.00
MAJDIIDFH
433.00
222.50
The required seller's total salary is output
This is the code I have been trying to make
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
/**
* A simple example program that reads a text file line by line and display each line.
*/
public class Salary {
public static void main(String[] args) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("temp.txt"));
String sellerName;
while ((sellerName = br.readLine()) != null) {
String salary = br.readLine();
String totalSale =br.readLine();
double percentage = 0.15;
double SaleAfterPercentage = totalSale * percentage;
//value of the total salary
double finalSalary = salary + SaleAfterPercentage ;
System.out.println(sellerName);
// System.out.println(salary);
// System.out.println(totalSale);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Try This
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("temp.txt"));
String line = null;
while ((line = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line);
String sellerName = st.nextToken();
String salary = st.nextToken();
String totalSale =st.nextToken();
double percentage = 0.15;
double SaleAfterPercentage = (Double.parseDouble(totalSale)) * percentage;
//value of the total salary
double finalSalary = Double.parseDouble(salary) + SaleAfterPercentage ;
System.out.println(sellerName);
System.out.println(finalSalary);
System.out.println(totalSale);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
To read this
JOAO 450.00 1230.30
FDJSI 333.00 2.00
MAJDIIDFH 433.00 222.50

How do I skip lines when I'm reading from a text file?

I'm reading from a text file which looks like this:
1
The Adventures of Tom Sawyer
2
Huckleberry Finn
4
The Sword in the Stone
6
Stuart Little
I have to make it so that the user can enter the reference number and the program will perform binary and linear search and output the title. My teacher said to use two ArrayLists, one for the numbers and one for the titles, and output from them. I just can't figure out how to skip lines so I can add to the corresponding arraylist.
int number = Integer.parseInt(txtInputNumber.getText());
ArrayList <String> books = new ArrayList <>();
ArrayList <Integer> numbers = new ArrayList <> ();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("bookList.txt"));
String word;
while ((word = br.readLine()) != null ){
books.add(word);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Thanks in advance, I appreciate any help!
You can check if you are in even or odd lines by doing a modulo 2 operation on the line number:
try (BufferedReader br = new BufferedReader(new FileReader("bookList.txt"))) {
String word;
int lineCount = 0;
while ((word = br.readLine()) != null ){
if (++lineCount % 2 == 0) {
numbers.add(Integer.parseInt(word));
} else {
books.add(word);
}
}
} catch (IOException e) {
e.printStackTrace();
}
int number = Integer.parseInt(txtInputNumber.getText());
ArrayList <String> books = new ArrayList <>();
ArrayList <Integer> numbers = new ArrayList <> ();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("bookList.txt"));
String word;
while ((word = br.readLine()) != null ){
numbers.add(Integer.valueOf(word));
word = br.readLine()
books.add(word);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
You could make check to see if it is actually a integer, that you read from the file. As far as I remember, there is no built in method to do this, but you can define your own as:
boolean tryParseInt(String value) {
try {
Integer.parseInt(value);
return true;
} catch (NumberFormatException e) {
return false;
}
}
Then just make a check to see if the line you have read in is a integer or not.
int number = Integer.parseInt(txtInputNumber.getText());
ArrayList <String> books = new ArrayList <>();
ArrayList <Integer> numbers = new ArrayList <> ();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("bookList.txt"));
String word;
while ((word = br.readLine()) != null ){
if (tryParseInt(word))
numbers.add(Integer.parseInt(word))
else
books.add(word);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Hope this help!

Buffer Reader reading String with comma, Then inserting 2d array

My proccesos.txt has this
1,500,600
2,300,800
3,800,1000
4,200,5000
What im trying to do here is insert the procesos.txt in a 2d array that will be displaying as follow 4 rows with 3 columns but without the comamas
This is currently my code on the buttom
`
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\Users\\Ifrahim\\Desktop\\Procesos.txt"));
br2 = new BufferedReader(new FileReader("C:\\Users\\Ifrahim\\Desktop\\Procesos.txt"));
int lines = (int) br2.lines().count();
myArr = new int[lines][3];
String[] lineArray = null ;
while ((sCurrentLine = br.readLine()) != null) {
lineArray=sCurrentLine.split(",");
System.out.println(Arrays.toString(lineArray));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
`
int line = 0;
while((sCurrentLine = br.readLine()) != null){
String[] tmp = sCurrentLine.split(",");//split the line up into its separate values
for(int i = 0 ; i < 3 ; i++)
myArr[line][i] = Integer.parseInt(tmp[i]);
//convert the values into integers and insert them at the matching position
//in the array
line++;
}

How to pass parameter to data provider in testng from csv file

Am reading data from csv file , i have test for which this data will be the input .
i want it to run as tescase for every set of value. for that am using data provider
The problem is , it is taking only the last set row of data , please help me in debugging the code
For eg : if my csv has following data
name1 id1 text1
name2 id2 text2
name3 id3 text3
it taking only last row name3 id3 text3 and running the test only once not three times.
#DataProvider(name = "test")
public Object[][] provider( ) throws InterruptedException
{
Object[][] returnObject ;
String[] checkpoint = ReadfromCSV();
count = count + 1;
returnObject = new Object[][]{checkpoint };
return returnObject;
}
#Test(description = "Test", groups = "test" , dataProvider = "test")
public void compare(String val1,String val2,String val3,String val4,String val5,String val6,String val7,String val8,String val9,String val10,String val11 ) {
System.out.println("1:" + val1);
System.out.println("4:" + val2);
System.out.println("5:" + val3);
}
#SuppressWarnings("null")
public String[] ReadfromCSV() throws InterruptedException {
String[] data= null;
String csvFile = "F:/sample1.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
data= line.split(cvsSplitBy);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done");
return data;
}
You should read entire file in data provider and return iterator of test cases. Here is some pseudocode for data provider. Notice that I used List<String []> to store test cases instead of Object[][]. This allows you do define test cases dynamically.
#DataProvider(name = "test")
public Iterator<Object []> provider( ) throws InterruptedException
{
List<Object []> testCases = new ArrayList<>();
String[] data= null;
//this loop is pseudo code
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
data= line.split(cvsSplitBy);
testCases.add(data);
}
return testCases.iterator();
}
public String[][] ReadfromCSV() throws InterruptedException {
int count =0;
String[] data= null;
String returnObj[][] = null;
//System.out.println(System.getProperty("user.dir"));
String csvFile = System.getProperty("user.dir")+ "/src/test/resources/testdata.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
ArrayList<String> content = new ArrayList<String>();
try {
//this loop is pseudo code
br = new BufferedReader(new FileReader(csvFile));
int datalength = 0;
int listsize =0;;
while ((line = br.readLine()) != null) {
// use comma as separator
content.add(line);
}
System.out.println(content);
listsize = content.size();
datalength = content.get(0).split(cvsSplitBy).length;
returnObj = new String[listsize][datalength];
for (int i = 0; i<listsize; i++) {
data = content.get(i).split(cvsSplitBy);
for (int j=0; j< datalength ; j++) {
returnObj[i][j] = data[j];
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done");
return returnObj;
}}

String tokenizer and parsing plain text JAVA

I am making a simple text based card game for fun/practice with parsing files. I have a plain text file with all the specs for the card. My cards are split with "##########". They are multilined. For now I simply want to be able to pull up the entirety of any ONE card whenever I want. For example, Player picks character 1, so I pull up Card 1 Only? How ?
EXAMPLE:
##########
CARD 1
Character Name:
Something Else:
##########
CARD 2
Character Name:
Something Else:
##########
Character Name:
Something Else:
##########
HOW CAN I ACTUALLY SPLIT THE CARDS SO THAT I CAN JUST ASK THE USER WHICH CARD.
I don't want to have to read the lines and print the way I did. It is rather cumbersome and convoluted.
My NEW ATTEMPT:
ArrayList listForCard1 = new ArrayList();
Integer selected_card = 1;
try {
String line;
FileReader fR = new FileReader("MyText.txt");
BufferedReader br = new BufferedReader(fR);
int x = 0;
Integer card = 1;
while ((line = br.readLine()) != null) {
ALines[x] = line;
x++;
if (line.contains("##########")) {
if ( card == selected_card) {
listForCard1.add(br.readLine());
// System.out.println(br.readLine());
break;
} else {
card++;
}
}
}
System.out.println("Done");
System.out.println(ALines[0]);
System.out.println(ALines[1]);
System.out.println(ALines[2]);
System.out.println(ALines[3]);
System.out.println(ALines[4]);
System.out.println(ALines[5]);
System.out.println(ALines[6]);
} catch (IOException e) {
e.printStackTrace();
}
}
try this
ArrayList<String> listForCard1 = new ArrayList<String>();
Integer selected_card = 1;
BufferedReader br = null;
try {
String line;
br = new BufferedReader(new FileReader("MyText.txt"));
Integer card = 1;
while ((line = br.readLine()) != null) {
if (line.contains("##########")) {
if ( card == selected_card) {
listForCard1.add(br.readLine());
listForCard1.add(br.readLine());
listForCard1.add(br.readLine());
break;
} else {
card++;
}
}
}
System.out.println("Done");
for (String s : listForCard1) {
System.out.println(s);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
select the card by setting selected_card.. we count how many #####'s we see when we have seen enough we read out that card and stop reading the file.. then print it from the arraylist

Categories

Resources