Java - Splitting ArrayList - java

Hello all I am trying to scan the bottom 6 lines of a text file and display them in a JOptionPane.showMessageDialog currently it is being displayed as [line7, line6, line5, line4, line3, line2] I would prefer it to be displayed as a vertical list instead of the comma seperator.
ArrayList<String> bandWidth = new ArrayList<String>();
FileInputStream in = null;
try {
in = new FileInputStream("src/list.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String tmp;
try {
while ((tmp = br.readLine()) != null)
{
bandWidth.add(tmp);
if (bandWidth.size() == 7)
bandWidth.remove(0);
}
} catch (IOException e) {
e.printStackTrace();
}
ArrayList<String> reversedSix = new ArrayList<String>();
for (int i = bandWidth.size() - 1; i >= 0; i--)
reversedSix.add(bandWidth.get(i));
JOptionPane.showMessageDialog(null,bandWidth,null,JOptionPane.INFORMATION_MESSAGE);

Try looping the ArrayList and produce a String with new line characters:
String result = "";
for (int i = 0; i < bandWidth.size(); i++)
{
result += bandWidth.get(i) + "\n";
}
JOptionPane.showMessageDialog(null,result ,null,JOptionPane.INFORMATION_MESSAGE);
Note: if this is outputting HTML, then use <br \> instead of \n.

Related

Empty line in arraylist Java

protected synchronized static void getRandomProxy(String srcFile) throws FileNotFoundException {
List<String> words = new ArrayList<>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(srcFile));
String line;
while ((line = reader.readLine()) != null) {
words.add(line);
System.out.println(line);
}
int k = 0;
for (int i = 0; i < words.size(); i++) {
k++;
String[] splitted = words.get(i).split(":");
String ip = splitted[0];
String port = splitted[splitted.length - 1];
// System.out.println(k + " " + ip + " * " + port);
}
} catch (IOException iOException) {
} finally {
try {
reader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
I want to get output printed without empty lines .
These are kind of results am getting Like :
result 1.
result 2.
result 3.
i want output like :
result 1.
result 2.
result 3.
without blank lines.
Don't add the String to the list if it's empty :
if(!line.trim().isEmpty()) {
words.add(line);
System.out.println(line);
}
If you still want to add the blank lines to the list but don't display them, just move the condition :
words.add(line);
if(!line.trim().isEmpty())
System.out.println(line);
Doc
Use System.out.print. Note that the file contains a newline char at the end of each line.
If srcFile is created with Notepad, try removing first the carriage return char System.out.print(line.replaceAll("\\r",""))
ArrayList<String> words = new ArrayList<>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(srcFile));
String line;
while ((line = reader.readLine()) != null) {
line = line.trim(); // remove leading and trailing whitespace
if (!line.isEmpty() && !line.equals("")) {
words.add(line);
System.out.println(line);
}
}

Printing Sentences in Java

I have a method that reads from a URL and splits the text into sentences using a delimiter. Here's what I have:
try {
URL url = new URL("Some link");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String l;
while((l = in.readLine()) != null) {
String sentence = l.replaceAll("[^a-zA-Z?.!]"," ");
String[] sent = sentence.split("[?.!]", 2);
for(int x = 0; x < sent.length; x++) {
System.out.println(sent[x]);
}
}
in.close();
} catch (MalformedURLException me) {
System.out.println(me);
} catch (IOException ioe) {
System.out.println(ioe);
}
This prints out the text sentence by sentence. However, I would like to read 30 sentences at a time, just wondering how I would go about doing that.
Use a StringBuilder to concatenate the whole text to work with first, then split it with a point and finally loop over it 50 times printing the 50 first indexes of the whole text array.
StringBuilder sb = new StringBuilder();
while((l = in.readLine()) != null) {
sb.append(l);
}
String[] sentences = sb.toString().split(".");
for (int i = 0 ; i < 50 ; i++){
System.out.println(sentences[i]);
}

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;
}}

Txt file into a double 2d array

I am trying to read a txt file into a array of doubles. I am using the following code which reads every line of the file:
String fileName="myFile.txt";
try{
//Create object of FileReader
FileReader inputFile = new FileReader(fileName);
//Instantiate the BufferedReader Class
BufferedReader bufferReader = new BufferedReader(inputFile);
//Variable to hold the one line data
String line;
// Read file line by line and print on the console
while ((line = bufferReader.readLine()) != null) {
System.out.println(line);
}
//Close the buffer reader
bufferReader.close();
}catch(Exception e){
System.out.println("Error while reading file line by line:"
+ e.getMessage());
}
However I want to store the txt file into a 2d double array.
I ve tried the above to load also the dimension of the txt. But I am having problems with the exceptions catch (NoSuchElementException e), it seems that it couldnt read the file.
try {
while (input.hasNext()) {
count++;
if (count == 1) {
row = input.nextInt();
r = row;
System.out.println(row);
continue;
} else if (count == 2) {
col = input.nextInt();
System.out.println(col);
c = col;
continue;
} else {
output_matrix = new double[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
String el = input.next();
Double temp = Double.valueOf(el);
double number = temp.doubleValue();
//output_matrix[i][j] = el;
output_matrix[i][j] = number;
//System.out.print(output_matrix[i][j]+" ");
}
//System.out.println();
}
}
}
} catch (NoSuchElementException e) {
System.err.println("Sfalma kata ti tropopoisisi toy arxeioy");
System.err.println(e.getMessage()); //emfanisi tou minimatos sfalmatos
input.close();
System.exit(0);
} catch (IllegalStateException e) {
System.err.println("Sfalma kata ti anagnosi toy arxeioy");
System.exit(0);
}
You might want to be using the Scanner class for it, especially the Scanner.nextDouble() method.
Also, if you don't know in advance the dimensions of the array - I'd suggest using an ArrayList instead of a regular array.
Code example:
ArrayList<ArrayList<Double>> list = new ArrayList<>();
while ((line = bufferReader.readLine()) != null) {
ArrayList<Double> curr = new ArrayList<>();
Scanner sc = new Scanner(line);
while (sc.hasNextDouble()) {
curr.add(sc.nextDouble());
}
list.add(curr);
}
At firs declare a list and collect into it all read lines:
List<String> tempHistory = new ArrayList<>();
while ((line = bufferReader.readLine()) != null) {
tempHistory.add(line);
}
Then, after bufferReader.close(); convert this tempHistory list into double[][] array.
double[][] array = new double[tempHistory.size()][];
for (int i = 0; i < tempHistory.size(); i++) {
final String currentString = tempHistory.get(i);
final String[] split = currentString.split(" ");
array[i] = new double[split.length];
for (int j = 0; j < split.length; j++) {
array[i][j] = Double.parseDouble(split[j]);
}
}
It works, but as I added in comments, this is a not so good solution, and is better to use Collections instead of array.
BTW, it works even the rows lengths are different for different lines.

Categories

Resources