Reading a CSV in Java / Jython - java

Here's a simple problem:
public static double[] stringsToDoubles(String[] inputArr) {
double[] nums = new double[inputArr.length];
for (int i = 0; i < nums.length; i++) {
nums[i] = Double.parseDouble(inputArr[i]);
}
return nums;
}
public static double[][] readPointCloudFile(String filename, int n) {
double[][] points = new double[n][];
String delimiter = ",";
Scanner sc = new Scanner(filename);
for (int i = 0; i < n; i++) {
String line = sc.nextLine();
points[i] = stringsToDoubles(line.split(delimiter));
}
return points;
}
from jython I import properly, and then call the function as
readPointCloudFile("points.txt", 3)
This gives the error
java.lang.NumberFormatException: java.lang.NumberFormatException: For input string: "points.txt"

You never read from the file. You pass the file name to the Scanner and assume that this string is your csv data, but it is just the filename.
Reading a file can be done as follows when you use Java 8:
import java.nio.file.Files;
import java.nio.file.Paths;
[...]
public static double[][] readPointCloudFile(String filename, int n) {
double[][] points = new double[n][];
String delimiter = ",";
String filecontent = new String(Files.readAllBytes(Paths.get(filename)));
Scanner sc = new Scanner(filecontent);
for (int i = 0; i < n; i++) {
String line = sc.nextLine();
points[i] = stringsToDoubles(line.split(delimiter));
}
return points;
}

Here's my solution in the spirit of solving your own problems, but I'll give someone else credit because the other solutions are probably better.
public static double[] stringsToDoubles(String[] inputArr){
double[] nums = new double[inputArr.length];
for(int i = 0; i < nums.length; i++){
nums[i] = Double.parseDouble(inputArr[i]);
}
return nums;
}
public static double[][] readPointCloudFile(String filename, int n) throws FileNotFoundException{
double[][] points = new double[n][];
String delimiter = ",";
try{
Scanner sc = new Scanner(new File(filename));
for(int i = 0; i < n; i++){
String line = sc.nextLine();
points[i] = stringsToDoubles(line.split(delimiter));
}
} catch (FileNotFoundException e){
System.err.println(e.getMessage());
} finally {
return points;
}
}

Related

Reading in a DAG from a file in Java

I am given a text file as follows:
0:1,2,3
1:3
2:
3:2
I'm trying to read in from the file then add it to a singly linked list array. Here is what I have so far. I'm able to print out the first part of the file however struggling to print out the values following the ":".
Here is my code.
public static void main(String[] args) throws FileNotFoundException {
ArrayList<String> arrayList = new ArrayList<>();
Scanner sc = new Scanner(new File(args[0]));
while (sc.hasNextLine()) {
arrayList.add(sc.nextLine());
}
SinglyLinkedList singlyLinkedList[] = new SinglyLinkedList[arrayList.size()];
for (int i = 0; i < arrayList.size(); i++) {
String dag = arrayList.get(i);
String[] daglist = dag.split(":");
int listindex = Integer.parseInt(daglist[0]);
System.out.println(listindex + ":");
Thanks in advance
Here is the following code that I've tried.
public static void main(String[] args) throws FileNotFoundException {
ArrayList<String> arrayList = new ArrayList<>();
Scanner sc = new Scanner(new File(args[0]));
while (sc.hasNextLine()) {
arrayList.add(sc.nextLine());
}
SinglyLinkedList singlyLinkedList[] = new SinglyLinkedList[arrayList.size()];
for (int i = 0; i < arrayList.size(); i++) {
String dag = arrayList.get(i);
String[] daglist = dag.split(":");
int listindex = Integer.parseInt(daglist[0]);
System.out.println(listindex + ":");
// for (int j = 0; j < arrayList.size(); j++) {
// String[] daglist1 = dag.split(",");
// int listvalues = Integer.parseInt(daglist1[1]);
// System.out.println(listindex + ":" + listvalues + " ");
// }
}
}
This is giving me an infinite loop and not printing out correctly.

Subsequence words

Suppose this is my .txt file ABCDBCD and I want to use .substring to get this:
ABC BCD CDB DBC BCD
How can I achieve this? I also need to stop the program if a line is shorter than 3 characters.
static void lesFil(String fil, subsekvens allHashMapSubsequences) throws FileNotFoundException{
Scanner scanner = new Scanner(new File("File1.txt"));
String currentLine, subString;
while(scanner.hasNextLine()){
currentLine = scanner.nextLine();
currentLine = currentLine.trim();
for (int i = 0; i + subSize <= currentLine.length(); i++){
subString = currentLinje.substring(i, i + subSize);
subSekStr.putIfAbsent(subString, new subsequence(subString));
}
}
scanner.close();
With a minor changes of your code:
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("C:\\Users\\Public\\File1.txt"));
String currentLine, subString;
int subSize = 3;
while (scanner.hasNextLine()) {
currentLine = scanner.nextLine();
currentLine = currentLine.trim();
if (currentLine.length() < subSize) {
break;
}
for (int i = 0; i + subSize <= currentLine.length(); i++) {
subString = currentLine.substring(i, i + subSize);
System.out.print(subString + " ");
}
System.out.print("\n");
}
scanner.close();
}
This may be what you need
String str = "ABCDBCD";
int substringSize = 3;
String substring;
for(int i=0; i<str.length()-substringSize+1; i++){
substring = str.substring(i, i+substringSize);
System.out.println(substring);
}
import java.util.*;
public class Main
{
public static void main(String[] args) {
String input = "ABCDBCD";
for(int i = 0 ; i < input.length() ; i++) {
if(i < input.length() - 2) {
String temp = input.substring(i,i+3);
System.out.println(temp);
}
}
}
}

executing code which reads from file and outputs data

My code is meant to read from a random file that looks like this: (but without blank lines in between)
Amy 12.23 7.43 4
Jake 9.01 23.34 3
Alan 34.00 34.21 7
The file will always have this format but could be any number of lines. I made up a .txt document that looked like this to test my code. When I tried to run it on command line nothing happened. Any suggestions why and what I can do to fix that?
import java.util.Scanner;
import java.io.*;
public class EmployeePay {
public static void main(String[] args) throws FileNotFoundException {
if (args.length != 1) {
final String msg = "Usage: EmployeePay name_of_input file";
System.err.println(msg);
throw new IllegalArgumentException(msg);
}
int linesCount = 0;
final String inputFileName = args[0];
final File input = new File (inputFileName);
final Scanner scanner = new Scanner(new FileReader(input));
while (scanner.hasNextLine()) {
linesCount = linesCount +1;
}
String identification[] = new String[linesCount];
double workTime [] = new double [linesCount];
double moneyPerHour [] = new double [linesCount];
int totalDeductions [] = new int [linesCount];
for(int i = 0; i < linesCount; i++){
String line = scanner.nextLine();
String [] lineParts = line.split(" ");
identification[i]= lineParts[0];
workTime[i]= Double.valueOf(lineParts[1]);
moneyPerHour[i] = Double.valueOf(lineParts[2]);
totalDeductions[i] = Integer.parseInt(lineParts[3]);
double totalGrossPay = 0.00;
if ((workTime[i] >= 1.0) && (moneyPerHour[i] >= 15) && (totalDeductions[i]>0)&&(totalDeductions[i]<35)){
double totalPay[] = new double[linesCount];
totalPay[i] = workTime[i] *moneyPerHour[i];
totalGrossPay += totalPay[i];
double theTaxRate = 0.15;
double taxTotal = theTaxRate * totalGrossPay;
double max = Double.MIN_VALUE;
for (int a =0; a< linesCount; a++) {
if (totalPay[a] > max) {
max = totalPay[a];
}
}
System.out.println(totalGrossPay);
System.out.println(taxTotal);
System.out.println(max);
}
}
}
}

Keep getting Exceptions

I am trying to read two files, match them, then print another file as result. But i keep getting this ArrayIndexOutOfBoundsException. I have no idea how to fix it, can someone help me please? Here is my code:
import java.io.IOException;
import java.util.Scanner;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
class Test{
final static char[][] DIG_CHAR = {{}, {}, {'A', 'B', 'C'}, {'D', 'E', 'F'}, {'G', 'H', 'I'}, {'J', 'K', 'L'}, {'M', 'N', 'O'}, {'P', 'Q', 'R', 'S'}, {'T', 'U', 'V'}, {'W', 'X', 'Y', 'Z'}};
public static void main(String[] args) throws IOException {
String s1 = "telephone.txt";
String s2 = "sample.txt";
Process(s1, s2);
}
public static void Process(String s1, String s2) throws IOException {
int size43 = ThreeCharacters(s2);
int size44 = FourCharacters(s2);
int size47 = SevenCharacters(s2);
String[] WordsOf3 = Store3Words(s2, size43);
String[] WordsOf4 = Store4Words(s2, size44);
String[] WordsOf7 = Store7Words(s2, size47);
String[] s = Char2Dig(WordsOf3);
String[] p = Char2Dig(WordsOf4);
String[] q = Char2Dig(WordsOf7);
Print3(WordsOf3, s, s1);
Print4(WordsOf4, p, s1);
Print7(WordsOf7, q, s1);
}
public static int ThreeCharacters(String s2) throws IOException {
Scanner in = new Scanner(new File(s2));
int count = 0;
while (in.hasNextLine()) {
in.nextLine();
if (in.nextLine().length() == 3) {
count++;
}
}
in.close();
return count;
}
public static int FourCharacters(String s2) throws IOException {
Scanner in = new Scanner(new File(s2));
int count = 0;
while (in.hasNextLine()) {
in.nextLine();
if (in.nextLine().length() == 4) {
count++;
}
}
in.close();
return count;
}
public static int SevenCharacters(String s2) throws IOException {
Scanner in = new Scanner(new File(s2));
int count = 0;
while (in.hasNextLine()) {
in.nextLine();
if(in.nextLine().length() == 7) {
count++;
}
}
in.close();
return count;
}
public static String[] Store3Words(String s2, int size) throws IOException {
//Here is where i keep getting the ArrayIndexOutOfBoundsException, probably same as the next two methods
String[] words = new String[size];
String temp = "";
Scanner in = new Scanner(new File(s2));
int i = 0;
while (in.hasNextLine()) {
temp = in.nextLine();
if (temp.length() == 3) {
words[i] = temp;
i++;
}
}
in.close();
return words;
}
public static String[] Store4Words(String s2, int size) throws IOException {
String[] words = new String[size];
String temp = "";
Scanner in = new Scanner(new File(s2));
int i = 0;
while (in.hasNextLine()) {
temp = in.nextLine();
if (temp.length() == 4) {
words[i] = temp;
i++;
}
}
in.close();
return words;
}
public static String[] Store7Words(String s2, int size) throws IOException {
String[] words = new String[size];
String temp = "";
Scanner in = new Scanner(new File(s2));
int i = 0;
while (in.hasNextLine()) {
temp = in.nextLine();
if (temp.length() == 7) {
words[i] = temp;
i++;
}
}
in.close();
return words;
}
public static String[] Char2Dig(String[] arr) { // ||
String temp = "";
String q = "";
String str = "";
for (int i = 0; i < arr.length; i++) {
temp = arr[i];
str = "";
for (int j = 0; j < temp.length(); j++) {
for (int m = 2; m < DIG_CHAR.length; m++) {
for (int k = 0; k < DIG_CHAR[m].length; k++) {
if (temp.charAt(j) == DIG_CHAR[m][k]) {
q = q + DIG_CHAR[m];
str = str + q;
break;
}
}
if (q == "") {
continue;
}
break;
}
q = "";
}
arr[i] = str;
}
return arr;
}
public static void Print3(String[] WordsOf3, String[] arr, String s1) throws IOException {
PrintWriter outfile = new PrintWriter(new FileWriter("result.txt"));
Scanner in = new Scanner(new File(s1));
String temp = "";
while (in.hasNextLine()) {
temp = in.nextLine().substring(4, 7);
for (int i = 0; i < arr.length; i++) {
if (arr[i] == temp) {
outfile.println(temp + ": " + WordsOf3[i]);
}
}
}
outfile.close();
}
public static void Print4(String[] WordsOf4, String[] arr, String s1) throws IOException {
PrintWriter outfile = new PrintWriter(new FileWriter("result.txt"));
Scanner in = new Scanner(new File(s1));
String temp = "";
while (in.hasNextLine()) {
temp = in.nextLine().substring(7, 11);
for (int i = 0; i < arr.length; i++) {
if (arr[i] == temp) {
outfile.println(temp + ": " + WordsOf4[i]);
}
}
}
outfile.close();
}
public static void Print7(String[] WordsOf7, String[] arr, String s1) throws IOException {
PrintWriter outfile = new PrintWriter(new FileWriter("result.txt"));
Scanner in = new Scanner(new File(s1));
String temp = "";
while (in.hasNextLine()) {
temp = in.nextLine().substring(4);
for (int i = 0; i < arr.length; i++) {
if (arr[i] == temp) {
outfile.println(temp + ": " + WordsOf7[i]);
}
}
}
outfile.close();
}
}
The problem is that you do not count right. You miss the number line of 3, 4 or 7 characters. Let's look at your code, method ThreeCharacters:
public static int ThreeCharacters(String s2) throws IOException {
Scanner in = new Scanner(new File(s2));
int count = 0;
while (in.hasNextLine()) {
in.nextLine();
if (in.nextLine().length() == 3) {
count++;
}
}
in.close();
return count;
}
in.nextLine() reads and skips one line, then if (in.nextLine().length() == 3) again reads and skips another line. At the end, you check only one line over two. The suggestion is to remove the in.nextLine() that is not doing anything, I guess. And if for any reason you put it on purpose, add the same line in Store3Words so that you also process only one line over two. This will solve the ArrayIndexOutOfBoundsException, but you will possibly have other problem in your code, because as beginner, you did not follow the path you are supposed to follow in programming: write one method, test and make sure it is working and move to the next method.
Altogether, I suggest you write a single method to count and a single one to store, your code can become as compact as this:
import java.io.IOException;
import java.util.Scanner;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
class TestApp{
final static char[][] DIG_CHAR = {{}, {}, {'A', 'B', 'C'}, {'D', 'E', 'F'},
{'G', 'H', 'I'}, {'J', 'K', 'L'}, {'M', 'N', 'O'}, {'P', 'Q', 'R', 'S'},
{'T', 'U', 'V'}, {'W', 'X', 'Y', 'Z'}};
public static void main(String[] args) throws IOException {
String s1 = "telephone.txt";
String s2 = "sample.txt";
Process(s1, s2);
}
public static void Process(String s1, String s2) throws IOException {
int size43 = count(s2, 3);
int size44 = count(s2, 4);
int size47 = count(s2, 7);
/////
System.out.println("lines of 3: "+size43 );
System.out.println("lines of 4: "+size44 );
System.out.println("lines of 7: "+size47 );
/////
String[] WordsOf3 = store(s2, size43, 3);
String[] WordsOf4 = store(s2, size44, 4);
String[] WordsOf7 = store(s2, size47, 7);
/////
System.out.println("lines of 3" );
for(int i = 0; i<size43; i++){
System.out.println( WordsOf3[i] );
}
System.out.println("lines of 4" );
for(int i = 0; i<size44; i++){
System.out.println( WordsOf4[i] );
}
System.out.println("lines of 7" );
for(int i = 0; i<size47; i++){
System.out.println( WordsOf7[i] );
}
/////
String[] s = Char2Dig(WordsOf3);
String[] p = Char2Dig(WordsOf4);
String[] q = Char2Dig(WordsOf7);
Print3(WordsOf3, s, s1);
Print4(WordsOf4, p, s1);
Print7(WordsOf7, q, s1);
}
/** Single method that returns the number of lines of given number of char
* With this single method, no need to write ThreeCharacters, FourCharacters
* and SevenCharacters
*/
public static int count(String fName, int nChar) throws IOException {
Scanner in = new Scanner(new File(fName));
int count = 0;
String tmp; // Note the tmp variable, so that we do not advance twice
while (in.hasNextLine()) {
if (in.nextLine().length() == nChar) {
count++;
}
}
in.close();
return count;
}
/** Single method that returns all the lines of given number of char
* With this single method, no need to write Store3Words, Store4Words
* and Store7Words
*/
public static String[] store(String fName, int size, int nChar) throws IOException {
String[] words = new String[size];
String temp = "";
Scanner in = new Scanner(new File(fName));
int i = 0;
while (in.hasNextLine()) {
temp = in.nextLine();
if (temp.length() == nChar) {
words[i] = temp;
i++;
}
}
in.close();
return words;
}
public static String[] Char2Dig(String[] arr) { // ||
String temp = "";
String q = "";
String str = "";
for (int i = 0; i < arr.length; i++) {
temp = arr[i];
str = "";
for (int j = 0; j < temp.length(); j++) {
for (int m = 2; m < DIG_CHAR.length; m++) {
for (int k = 0; k < DIG_CHAR[m].length; k++) {
if (temp.charAt(j) == DIG_CHAR[m][k]) {
q = q + DIG_CHAR[m];
str = str + q;
break;
}
}
if (q == "") {
continue;
}
break;
}
q = "";
}
arr[i] = str;
}
return arr;
}
public static void Print3(String[] WordsOf3, String[] arr, String s1) throws IOException {
PrintWriter outfile = new PrintWriter(new FileWriter("result.txt"));
Scanner in = new Scanner(new File(s1));
String temp = "";
while (in.hasNextLine()) {
temp = in.nextLine().substring(4, 7);
for (int i = 0; i < arr.length; i++) {
if (arr[i] == temp) {
outfile.println(temp + ": " + WordsOf3[i]);
}
}
}
outfile.close();
}
public static void Print4(String[] WordsOf4, String[] arr, String s1) throws IOException {
PrintWriter outfile = new PrintWriter(new FileWriter("result.txt"));
Scanner in = new Scanner(new File(s1));
String temp = "";
while (in.hasNextLine()) {
temp = in.nextLine().substring(7, 11);
for (int i = 0; i < arr.length; i++) {
if (arr[i] == temp) {
outfile.println(temp + ": " + WordsOf4[i]);
}
}
}
outfile.close();
}
public static void Print7(String[] WordsOf7, String[] arr, String s1) throws IOException {
PrintWriter outfile = new PrintWriter(new FileWriter("result.txt"));
Scanner in = new Scanner(new File(s1));
String temp = "";
while (in.hasNextLine()) {
temp = in.nextLine().substring(4);
for (int i = 0; i < arr.length; i++) {
if (arr[i] == temp) {
outfile.println(temp + ": " + WordsOf7[i]);
}
}
}
outfile.close();
}
}
If I understood the logic behind the Print3, Print4 and Print7 I would have do the same. Also notice that I added some print statement to see what is going on. That is very helpful to see if your code is doing what it is supposed to do.

Reading in integers from an input file and writing to an output file using arrays in Java

Okay, so I'm not totally sure I'm using arrays correctly or not, but here goes. I have a homework assignment and I'm trying to read from an input file and write to an output file using arrays. I have to show the high temperatures and low temperatures and find the averages for each day of the week. The problem I'm having right now is that nothing is being written to the output file.
Here is what I have so far.
package dowtemps;
import java.util.Arrays;
public class DOWTemps
{
public static void main(String[] args)
{
int index = 0;
int temp = 0;
int dow = 0;
int[] lowTempArray = new int[8];
int[] highTempArray = new int[8];
int[] countArray = new int[8];
int[] totalArray = new int[8];
InputFile in = new InputFile("input.txt");
OutputFile out = new OutputFile("output.txt");
System.out.println("DOW Temperature Started. Please Wait....");
for (index = 0; index < 8; index++)
{
lowTempArray[index] = 999;
highTempArray[index] = -999;
countArray[index] = 0;
totalArray[index] = 0;
dow++;
}
System.out.println(Arrays.toString(lowTempArray));
System.out.println(Arrays.toString(highTempArray));
while (!in.eof())
{
//read in records
dow = in.readInt();
temp = in.readInt();
//load arrays
lowTempArray[dow] = temp;
highTempArray[dow] = temp;
if (temp > highTempArray[dow])
{
highTempArray[dow] = temp;
}
else
{
lowTempArray[dow] = temp;
}
totalArray[dow] = totalArray[dow] + temp;
countArray[dow]++;
//write records
out.writeInt(dow);
out.writeInt(lowTempArray[dow]);
out.writeInt(highTempArray[dow]);
out.writeInt(totalArray[dow]);
out.writeInt(countArray[dow]);
out.writeInt((totalArray[dow] / (countArray[dow])));
out.writeEOL();
}
System.out.println(Arrays.toString(lowTempArray));
System.out.println(Arrays.toString(highTempArray));
System.out.println("DOW Temperature Completed Successfully.");
out.close();
}
}
Maybe you can change InputFile and OutFile for this:
Scanner in = new Scanner(new File("input.txt"));
PrintWriter out = new PrintWriter("output.txt", "UTF-8");
I did a little changes on your code, now it read and print.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Scanner;
public class DOWTemps
{
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException
{
int index = 0;
int temp = 0;
int dow = 0;
int[] lowTempArray = new int[8];
int[] highTempArray = new int[8];
int[] countArray = new int[8];
int[] totalArray = new int[8];
Scanner in = new Scanner(new File("input.txt"));
PrintWriter out = new PrintWriter("output.txt", "UTF-8");
System.out.println("DOW Temperature Started. Please Wait....");
for (index = 0; index < 8; index++)
{
lowTempArray[index] = 999;
highTempArray[index] = -999;
countArray[index] = 0;
totalArray[index] = 0;
dow++;
}
System.out.println(Arrays.toString(lowTempArray));
System.out.println(Arrays.toString(highTempArray));
while (in.hasNextLine())
{
//read in records
dow = in.nextInt();
temp = in.nextInt();
//load arrays
lowTempArray[dow] = temp;
highTempArray[dow] = temp;
if (temp > highTempArray[dow])
{
highTempArray[dow] = temp;
}
else
{
lowTempArray[dow] = temp;
}
totalArray[dow] = totalArray[dow] + temp;
countArray[dow]++;
//write records
out.println(dow);
out.println(lowTempArray[dow]);
out.println(highTempArray[dow]);
out.println(totalArray[dow]);
out.println(countArray[dow]);
out.println((totalArray[dow] / (countArray[dow])));
out.println();
}
System.out.println(Arrays.toString(lowTempArray));
System.out.println(Arrays.toString(highTempArray));
System.out.println("DOW Temperature Completed Successfully.");
out.close();
}
}
Just check the logic of your program if its what you need

Categories

Resources