Importing 2 types of variables from text file - arrays

I am not very fluent, simple question: when i have text file like this:
Name number
Name2 number2
How do i import it to Arrays, that I can operate on both of these? Numbers and names are separated by space. I have seen guides just to one type of variable, but what if i have two of them?

In pseudocode
while not eof:
read name
do sth with name
read number
do sth with number
In Java
String line;
String[] row;
ArrayList<String> names = new ArrayList<String>();
ArrayList<Integer> numbers = new ArrayList<Integer>();
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
while ((line = br.readLine()) != null) {
row = line.split("\\s+");
names.add(row[0]);
numbers.add(Integer.parseInt(row[1]));
}
} catch (IOException e) {}

Related

Input Mismatch scanner.next(string pattern) from file

I'm having a problem while using a
Scanner file = new Scanner(filePath);
my file is organised as so
Question x.y
Answer1
Answer2
Answer3
Answer4
Hint: Hint to Question x.y Level z Genere t
I'm quite new to java and in all of this project I've used
.next(string pattern)
to return a string that includes the parrtern and arrives to the end of the line but i continue to get mismatch exceptions.. i don't really get what
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
defines as token and for this reason i don't know how to handle it..
my code is
public Question getQuestion(String filePath)
{
ArrayList questions = new ArrayList();
Scanner file = new Scanner(filePath);
String questionInFile = "Question";
while(file.hasNextLine())
questions.add(questionInFile+file.next(questionInFile));
Random rg = new Random();
String Q = (String)questions.get(rg.nextInt(10)+1);
file.close();
ArrayList<String> answer=getAnswers(filePath, Q);
String correctAnswer=answer.get(0);
return new Question(Q, answer, correctAnswer);
}
try adding
File filePath = new File(".txt");
before Scanner file

Simple ArrayIndexOutOfBoundsException 1 in loop

I have a .data file containing lines of values. I partition them into separate values using the split method, then I initialize an ArrayList where I add the model items to the list. I had a while loop for this specific code here which looked like this:
while (inFile.hasNextLine() {
// Do something
}
That didn't seem to work so I switched it to a for loop.
public MachineLearningInstance(File f) {
try {
int noOfRowsInData = 0;
LineNumberReader lnr = new LineNumberReader(new FileReader(f));
try {
lnr.skip(Long.MAX_VALUE);
noOfRowsInData = lnr.getLineNumber();
//System.out.println(noOfRowsInData);
lnr.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
irisData = new ArrayList<Iris>();
// While there is another line in inFile.
Scanner inFile = new Scanner(f);
for (int i = 0; i < noOfRowsInData; i++) {
if (inFile.hasNextLine()) {
// Store line into String
String line = inFile.nextLine();
// Partition values into separate elements in array
String[] numbers = line.split(comma);
// Grab values from that line and store it into a Iris ArrayList Item
irisData.add(i, new Iris(i, numbers[0], numbers[1], numbers[2], numbers[3], numbers[4]));
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
For some weird reason (and I bet it is a really simply reason I just can't see it) I keep getting the ArrayListIndexOutOfBoundsException 1 when I run this piece of code. I'm guessing that my while loop keeps looping? I don't understand what the problem seems to be.
Is it possible that my LineNumberReader is not reading the number of lines properly? I don't think that is the case though. Most likely I am not declaring something correctly.
So this happened to solve my problem, I'm really tired and have no interest right now in finding out why but it fixed the issue lol:
for (int i = 0; i < noOfRowsInData - 1; i++) {
if (inFile.hasNextLine()) {
// Store line into String
String line = inFile.nextLine();
// Partition values into separate elements in array
String[] numbers = line.split(comma);
// Grab values from that line and store it into a Iris ArrayList Item
irisData.add(i, new Iris(i, numbers[0], numbers[1], numbers[2], numbers[3], numbers[4]));
}
}
Supposedly noOfRowsInData - 1 fixes it.

How to read and add only numbers to array from a text file

I'm learning java and I have a question regarding reading from file
i want to read only numbers from file that contains strings as well.
here is an example of my file:
66.56
"3
JAVA
3-43
5-42
2.1
1
and here is my coding:
public class test {
public static void main (String [] args){
if (0 < args.length) {
File x = new File(args[0]);
try{
Scanner in = new Scanner( new FileInputStream(x));
ArrayList<Double> test = new ArrayList<>();
while(in.hasNext()){
if(in.hasNextDouble()){
Double f=in.nextDouble();
test.add(f);}
else
{in.next();}
}
catch(IOException e) { System.err.println("Exception during reading: " + e); }
}
my problem is it only add 66.56,2.1 and 1
it doesn't add 3 after "3 or it ignores 3-43 and 5-42
can you tell me how to skip Strings and only add doubles here?
thanks
All the said three ie; "3, 3-43 and 4-42 are strings
Either u read a string and split it and check for number at " and - or you put in a space between characters and integers.
The JVM after compilation would treat it all as string if it cannot be converted to a double.
And the File reader wont stop reading till at least a space or a newline.
Hence your code would never work the way you intend it to unless you do as I said above.
Solution 1:
Change your input file to something like this:
66.56
" 3
JAVA
3 - 43
5 - 42
2.1
1
Solution 2:
Considering the highly variable nature of your input file I am posting a solution only made for your current input. If the input changes a more versatile algorithm would need to be implemented.
public static void main(String[] args) {
File x = new File(args[0]);
try {
Scanner in = new Scanner(new FileInputStream(x));
ArrayList<Double> test = new ArrayList<>();
while (in.hasNext()) {
if (in.hasNextDouble()) {
Double f = in.nextDouble();
test.add(f);
} else {
String s=in.next();
if(s.contains("\"")){
String splits[]=s.split("\"");
test.add(Double.parseDouble(splits[1]));
}
else if (s.contains("-")){
String splits[]=s.split("-");
test.add(Double.parseDouble(splits[0]));
test.add(Double.parseDouble(splits[1]));
}
}
}
System.out.println(test);
} catch (IOException e) {
System.err.println("Exception during reading: " + e);
}
}
You can write custom Type Sensor Utility class to check whether the object can be converted to Integer or not. I would approach to this problem like this.
Moreover I can see that you have values like 2.1 and " 3 to handle these scenarios write additional methods like isDoubleType() or isLongType() etc.
Also you need to write some custom logic to solve this problem.
public class TypeSensor {
public String inferType(String value) throws NullValueException {
int formatIndex = -1;
if (null == value) {
throw new NullValueException("Value provided for type inference was null");
}else if (this.isIntegerType(value)) {
return "Integer";
}else{
LOGGER.info("Value " + value + " doesnt fit to any predefined types. Defaulting to String.");
return "String";
}
}
}
private boolean isIntegerType(String value) {
boolean isParseable = false;
try {
Integer.parseInt(value);
LOGGER.info("Parsing successful for " + value + " to Integer.");
isParseable = true;
} catch (NumberFormatException e) {
LOGGER.error("Value " + value + " doesn't seem to be of type Integer. This is not fatal. Exception message is->"
+ e.getMessage());
}
return isParseable;
}
}

Search a Substring in a List<string>

I have a List of Codes (COD_XX) and I need to search each code in a text file, and get the index of the line where is located. The first caracter of the line contains the cod.
I've saved all the lines in a List
var fileLines = File.ReadAllLines(filePath);
List<string> fileItems = new List<string>(fileLines);
foreach (string param in lstCodes)
{
int idx = fileItems.FindIndex(m => m.Substring(0,6) == param)
}
But this expression is not working :( How should I writte it?
Thank you in advanced for your help.
Your code works fine if you put ; after fileItems.FindIndex(...)
But m.Substring(0,6) could throw an exception if m is shorter than 6.
You should use String.StartsWith method.
foreach (string param in lstCodes)
{
int idx = fileItems.FindIndex(m => m.StartsWith(param));
}

Read data from csv file using java in webdriver

How to read data of each cell in Selenium WebDriver using Java?
I have tried with following code:
CSVReader reader = new CSVReader(new FileReader("D:/data1.csv"));
expectedLabels = reader.readNext();
FieldNames = reader.readNext();
FieldValues = reader.readNext();
File file = new File("D:/data.csv");
if(file.exists()){
System.out.println("File Exists");
}
BufferedReader bufRdr;
bufRdr = new BufferedReader(new FileReader(file));
String line = null;
while((line = bufRdr.readLine()) != null){
StringTokenizer st = new StringTokenizer(line,",");
col=0;
while (st.hasMoreTokens()){
//Following stroing the data of csv
numbers[row][col] = st.nextToken();
col++;
}
System.out.println();
row++;
}
bufRdr.close();
reading csv files become very easy with OPENCSV jar file. I have used this jar file couple of time to read file.
We have predefined class called CSVReader, create an object and pass the csv file path
call readAll() method which will return the csv content in List
using Iterator, you can iterate all the values and use according to application
I have written article on this have a look it might help you.
http://learn-automation.com/how-to-read-csv-files-using-java/
I am not able to provider string type variable in FileReader() function , it shows error while passing filereader() method with parameter in buffer reader fn
code shown below:
String f1= (System.getProperty("User.dir") + "\\Module9TestNG\\src\\TestLogin.xlsx");
BufferedReader bufRdr;
bufRdr = new BufferedReader(new FileReader(file));
String record;
String url= null;
while ((record = bufRdr.readLine()) != null)
{
String fields[] = record.split(",");
url= fields[0].toString();
}
private String Fpath ="D:\\CkycApps.csv";
String line;
File file = new File(Fpath);
BufferedReader bufRdr;
bufRdr = new BufferedReader(new FileReader(file));
while((line = bufRdr.readLine()) != null){
System.out.println(line);
String[] cell= line.split(",");
String FirstName=cell[0];
String MiddleName=cell[1];
}

Resources