Empty array when reading text file into array list - java

Goal: To fill an array with doubles from a text file.
Error: Empty array printed.
A small part of my text file which contains close to 500 numbers, I only need the values and not the "Z" at the start:
Z, 10.9123728, 5.3872839283, 11.30903923, 20.128192821, 3.8716134
My code:
Scanner inFile = new Scanner(new File(filename1));
ArrayList<Float> values = new ArrayList<Float>();
while (inFile.hasNext()) {
String line = inFile.nextLine();
String[] nums = line.trim().split(",");
if(inFile.hasNextDouble()) {
float token = Float.parseFloat(nums[1].trim());
values.add(token);
}
}
System.out.println(values);
inFile.close();

You are using two different routes here. Pick one. If you want to use hasNextDouble then you have to set up your Scanner to use a comma as a delimiter. However if given your current code, just abandon the hasNextDouble. NOTE that I did not test this, this is just me typing in the editor, so there could be syntax issues.
Scanner inFile = new Scanner(new File(filename1));
ArrayList<Float> values = new ArrayList<Float>();
while (inFile.hasNext()) {
String line = inFile.nextLine();
String[] nums = line.trim().split(",");
for (String num : nums) {
try {
float float = Float.parseFloat(nums[i].trim());
values.add(token);
} catch (NumberFormatException nfe) {
// the 'z'
continue;
}
}
}
System.out.println(values);
inFile.close();

Related

How to add comma seperated string and int into two different arraylists [java]

Say I have strings and integers being read from a file and seperated by a comma and I want to add them into two different arrayLists.
hamburger,15
cheese,10
soda,15
How would I go about doing this? I intially used nextLine() to add them into one arraylist and extract the integer and erase the comma but this wasn't working for arrayLists. I also tried using nextInt() to just grab the int's but was given an exception.
public static void readFile(ArrayList items, ArrayList cost)
{
String intValue = "";
try
{
Scanner read = new Scanner(new File("Menu.txt"));
while (read.hasNext())
{
items.add(read.nextLine());
}
read.close();
for (int i = 0; i < items.size(); i++)
{
intValue = items.indexOf(i).replaceAll("[^0-9]", "");
int value = Integer.parseInt(intValue);
cost.add(value);
}
System.out.println(item);
System.out.println(cost);
}
catch(FileNotFoundException fnf)
{
System.out.println("File was not found.");
}
}
my end result would be:
items = [hamburger, cheese, soda]
cost = [15, 10, 15]
public static void readFile(List<String> items, List<Integer> costs) {
try {
Scanner read = new Scanner(new File("Menu.txt"));
while (read.hasNext()) {
String line = read.nextLine();
String[] itemsAndCosts = line.split(",");
items.add(itemsAndCosts[0]);
costs.add(Integer.parseInt(itemsAndCosts[1]));
}
read.close();
System.out.println(items);
System.out.println(costs);
} catch (FileNotFoundException fnf) {
System.out.println("File was not found.");
}
}
Use List<String> instead of ArrayList.
You can split the line on the , and then you have an array of 2 elements, item and cost. (Note: will only work if there is only one , per line). You can also use .subString(...), but for me, splitting is cleaner.
Use try-with-resources so you don't need to do .close():
try (Scanner read = new Scanner(new File("Menu.txt"))) {
while (read.hasNext()) {
String line = read.nextLine();
String[] itemsAndCosts = line.split(",");
items.add(itemsAndCosts[0]);
costs.add(Integer.parseInt(itemsAndCosts[1]));
}
System.out.println(items);
System.out.println(costs);
} catch (FileNotFoundException fnf) {
System.out.println("File was not found.");
}

JAVA: how do I convert a txt file into a 2-D array with numbers in E notation?

I have a .txt file with 300 rows and 785 columns with a bunch of numbers in E notation (e.g. -6.431571950262252035e-02). How would I covert those numbers into a 2-D array?
This is all I have:
double[][] hiddenArray = new double[300][785];
Scanner scanner = new Scanner(System.in) ;
String hiddenFile = "hidden-weights.txt";
String outputFile = "output-weights.txt";
scanner.close();
Scanner in = new Scanner(new File(hiddenFile));
String hidden= in.nextLine();
Use Scanner::hasNext() to loop while there are more lines and Scanner::nextLine() to fetch the next line, then use String::split() to get an array of strings on each line (Note: my presumption is that the columns are separated by commas (i.e. ,) but feel free to adjust for your needs). For parsing the numbers in e notation, use Double.valueof(), and add that value to the array (e.g. hiddenArray).
You should be able to use the sample below. I also created an example on tutorialspoint.com codingGround but that may not work...
try {
String delimiter = ","; //separates columns - change for your needs
int row = 0;
Scanner in = new Scanner(new File(hiddenFile));
String line;
while (in.hasNext() && (line = in.nextLine()) != null ) {
String[] vals = line.trim().split(",");
for (int col = 0; col < vals.length; col++) {
hiddenArray[row][col] = Double.valueOf(vals[col]);
}
row++;
}
}
catch(FileNotFoundException e) {
System.out.println("file not found - "+e.getMessage());
}

Java: searching a string array from a CSV file

I am new at Java so please bear with me.
I need help for one of my assignments again. Now it involves FileI/O.
The task that I have to do is:
I have to read a .csv file. The values that's inside the file are:
Christopher Lee,54.0
Stanley Wright,90.5
Oliver Stewart,75.8
Jessica Chang,34.65
As the task said, I must store the contents on the file into two arrays. One for the names, and one for the test marks. I should read the file at least twice, once to check how many names are in the file and a couple more times to actually read the file (to get the names and marks). So basically, I should have an array to store the names as Strings, and an array to store the marks of the student as real numbers.
I should line up the arrays (e.g.students[0] should store the name of the first student and marks[0] should store the mark of the first student
After I stored the contents of the .csv file into an array I have to display a following menu to the user. If the user pressed 1, it should prompt the user to enter the name of a student. If the user pressed 2, the program should exit. If the name exists, it should display the test mark for the student entered. If the student does not exist then I must output a message indicating so to the user, yet the program should not end but return to the above menu.
This is my code so far:
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String fileName = "file:///Documents/Java/marks_file.csv"; // Opens the file
String[] arrayString = new String[6]; // String length inside the file
int numLines, selection = 0;
double[] arrayReal = new double[6]; // Number length inside the file
numLines = getNumLines(fileName); // Gets the length of the file
readFile(arrayString, arrayReal, fileName);
// Selection menu
do
{
System.out.println("Select an option:");
System.out.println("1. Display mark");
System.out.println("2. Exit");
selection = sc.nextInt();
if (selection == 1)
{
System.out.println("Enter your full name");
{
// Do something
}
}
else if (selection == 2)
{
System.out.println("Goodbye");
}
}
while (selection == 1);
//System.out.println("Number of arrays: " + numLines);
}
// Method to get the length of the .csv file
public static int getNumLines(String fileName)
{
FileInputStream fileStrm = null;
InputStreamReader rdr;
BufferedReader bufRdr;
String line;
int lineNum = 0;
try
{
fileStrm = new FileInputStream(fileName);
rdr = new InputStreamReader(fileStrm);
bufRdr = new BufferedReader(rdr);
line = bufRdr.readLine();
while (line != null)
{
lineNum = lineNum + 1;
line = bufRdr.readLine();
}
fileStrm.close();
}
catch (IOException e)
{
try
{
if (fileStrm != null)
{
fileStrm.close();
}
}
catch (IOException ex2)
{
// Nothing to do
}
System.out.println("Error in file processing: " + e.getMessage());
}
return lineNum;
}
// Method to store the values to arrays
public static void readFile(String[] arrayString, double[] arrayReal, String fileName)
{
Scanner sc = new Scanner(System.in);
FileInputStream fileStrm = null;
InputStreamReader rdr;
BufferedReader bufRdr;
String line;
try
{
fileStrm = new FileInputStream(fileName);
rdr = new InputStreamReader(fileStrm);
bufRdr = new BufferedReader(rdr);
for (int i = 0; i < arrayString.length; i++)
{
line = bufRdr.readLine();
arrayString[i] = processString(line);
arrayReal[i] = processReal(line);
}
}
catch (IOException e)
{
try
{
if (fileStrm != null)
{
fileStrm.close();
}
}
catch (IOException ex2)
{
// Nothing to do
}
System.out.println("Error in file processing: " + e.getMessage());
}
}
// Stores the String lines to array
public static String processString(String line)
{
String string;
String[] lineArray = line.split(",");
return string = lineArray[0];
}
// Stores real number lines to array
public static double processReal(String line)
{
double real;
String[] lineArray = line.split(",");
return real = Double.parseDouble(lineArray[1]);
}
So far, I finished the "reading the file" part and processing the contents from a .csv file to an array.
I am not too sure how to prompt a user to search a string array from a .csv file. I tried looking at other sources, even at this website but I have no luck at all. I tried the Scanner.next() method but that doesn't work at all. Maybe I just missed something. Also, I am not sure if I did the "reading the file twice" right.
Am I on the right track? I am need of some guidance here
First of all I want to say that I'd use a Map instead of two arrays but I'll show you a solution using two arrays.
You were close to the solution. One of you problems is that scanner.next() only reads the input until the first whitespace. That's why you need to use scanner.nextLine(). This method reads the complete line. And the code could look something like that:
Solution with two arrays
Scanner sc = new Scanner(System.in);
System.out.print("Please enter name of student: ");
String name = sc.nextLine();
for(int i = 0; i < arrayString.length; i++){
if(name.equals(arrayString[i])) {
System.out.println(arrayReal[i]);
}
}
Solution with a HashMap
Initialize HashMap
HashMap<String, Double> hm = new HashMap<String, Double>();
Fill HashMap
hm.put("Christopher Lee", 54.0);
Print double value of student
System.out.print("Please enter name of student: ");
String name = sc.nextLine();
System.out.println(hm.get(name));
Instead of storing into arrays, I would rather tell you to pass the data to data into generic arraylist and then query the result using get() method.
You are making simple thing difficult.
Just use a HashMap with name as the keys and test-score as the values.
You open file
You read each line and translate each line to an entry of hash map
When a text is input to the console, you just get it from hash map, if existed return the value, if not then back to number 3

How can i read .txt file to long [] JAVA?

I need to read file into the array long[], so the result will be same as creating new instance:
long [] y = new long[] {
500, 300, 16800, 35200,
60000, 50000, 2200, 2200, 29500
};
How can I do it?
try {
Scanner scanner = new Scanner(new File("myFile.txt"));
long[] values = new long[100];
int i = 0;
while (scanner.hasNextLong()) {
values[i] = scanner.nextLong();
i++;
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Try. Ugly, but should work
Scanner scanner = new Scanner(new File("myfile.txt"));
String[] numbersStrings = scanner.readLine().split(" ");
long[] numbers = new long[numbersStrings.length];
for (int i = 0; i < numbersStrings.length; i++) {
numbers[i] = Long.parseLong(numbersStrings[i]);
}
scanner.close();
You can use a Scanner, a List<Long> and a pair of loops (one to read the long(s) into a List then a second to convert the List to an array) with something like -
public static long[] readFile(String filePath) {
List<Long> al = new ArrayList<Long>();
File f = new File(filePath);
Scanner scanner = null;
try {
scanner = new Scanner(f);
while (scanner.hasNextLong()) {
al.add(scanner.nextLong());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (scanner != null) {
scanner.close();
}
}
long[] ret = new long[al.size()];
for (int i = 0; i < al.size(); i++) {
ret[i] = al.get(i);
}
return ret;
}
Using the previous answer as a base:
try (Scanner scanner : new Scanner(new File("myfile.txt")) {
List<Long> numbers = new ArrayList<>();
while (scanner.hasNextLong()) {
numbers.add(scanner.nextLong());
}
Long[] value = numbers.toArray(new Long[numbers.size()]);
// or:
long[] values = new long[numbers.size()];
int i = 0;
for (Long n : numbers) {
values[i] = n;
++i;
}
}
The try-with-resources is used to close the Scanner, and the file, when you're done reading it.
Scanner is a class that can read various thing, and among all, it can read Long.
We need to store the values inside an ArrayList because we don't know the amount of number there are in the file.
Converting the ArrayList is then a little tricky:
With auto boxing Long can be converted to long (and long to Long), but that don't work for arrays: Long[] is not a long[].
The first form use the toArray method, which return an array of Long.
The second form create an array of long[] and fill it with the numbers from the list using a for-each.
Scanner might be a bit slow for larger inputs. I recommend tokenizer
Also, this will be more memory effective since we're not allocating any extra Object (wrappers for primitives), and no extra temporary data structure (except tokenizer internals)
// Read the file into the string.
// WARNING: This will throw OutOfMemoryException on very large files
// To handle large file you will need to wrap the file into a buffer and read it partially.
// Also this method is present only in Java 7+ . If you're on 6, just use regular file reading
byte[] fileContent = Files.readAllBytes(Paths.get(path));
String str = new String(fileContent, encoding);
// The second parameter is the delimiter. If your data is separated by space, this will work.
// Otherwise (ex. by comma - ,) you will need to supply it here
StringTokenizer tokenizer = new StringTokenizer(str," ");
long[] values = new long[tokenizer.countTokens()];
int idx = 0;
while(tokenizer.hasMoreTokens()) {
values[idx++] = Long.parseLong(tokenizer.nextToken());
}

Java delimiter reading a text file

I'm trying to read a text file with this format:
Array x
1,3,5,4
Array y
12,13,15,11
and put it in two array, but I only want the integer.
What delimiter should I use to ignore the String and the empty line?
Here's my code in putting the int to arrays. By the way, I'm using scanner to read the file:
Scanner sc = null;
try
{
sc = new Scanner(new FileInputStream("C:\\x.txt"));
sc.useDelimiter(""); // What will I put inside a quote to get only the int values?
}
catch(Exception e)
{
System.out.println("file not found!");
}
int[] xArray = new int[4];
int[] yArray = new int[4];
while (sc.hasNextInt( )){
for(int i=0; i<4; i++){
xArray[i] = sc.nextInt( );
}
for(int i=0; i<4; i++){
yArray[i] = sc.nextInt( );
}
}
What I want to get is
int[] xArray = {1,3,5,4}
int[] yArray = {12,13,15,11}
I hope you understand :)
Thanks.
I suggest you to use bufferedreader instead of scanner. You can use below code :
BufferedReader br=new BufferedReader(new FileReader("your file name"));
br.readLine(); //it will omit first line Array x
String x=br.readLine(); //it return second line as a string
String[] x_value=x.split(","); //You can parse string array into int.
This is for Array x. You can do the same for array y. and after that parse into int.

Categories

Resources