executing code which reads from file and outputs data - java

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

Related

Reading a CSV in Java / Jython

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

Why does this program terminate when I enter user input?

The program is supposed to compare a user-inputted string to a text document. If the program finds a match in the file and in part of the string, it should highlight or change the font color of the matching string in what the user inputted. The thing is, once I enter something for user input, the program terminates. Examples of inputs that could have a match in the file are MALEKRQ, MALE, MMALEKR, MMMM, and MALEK. How do I fix this problem? I'm using Eclipse Neon on Mac OS X El Capitan.
import java.util.*;
import java.io.*;
public class ScienceFair
{
public static void main(String[] args) throws FileNotFoundException
{
java.io.File file = new java.io.File("/Users/Kids/Desktop/ScienceFair/src/MALEKRQsample.txt");
try
{
Scanner fileInput = new Scanner(file);
Scanner userInput = new Scanner(System.in);
System.out.println("Enter Protein Sequence");
String userProteinSequence = userInput.nextLine().toUpperCase();
int len = userProteinSequence.length();
int size = 4;
int start = 0;
int indexEnd = size;
while (indexEnd < len - size)
{
for (int index = start; index <= len - size; index++)
{
String search = userProteinSequence.substring(index, indexEnd);
System.out.println(search);
while (fileInput.hasNext())
{
String MALEKRQ = fileInput.nextLine();
// System.out.println(MALEKRQ);
int found = MALEKRQ.indexOf(search);
if (found >= 0)
{
System.out.println("Yay.");
}
else
{
System.out.println("Fail.");
}
}
indexEnd++;
}
size++;
if (size > 8) {
size = 8;
start++;
}
}
}
catch (FileNotFoundException e)
{
System.err.format("File does not exist.\n");
}
}
}
import java.util.*;
import java.io.*;
public class ScienceFair
{
public static void main(String[] args) throws FileNotFoundException
{
java.io.File file = new java.io.File("/Users/Kids/Desktop/ScienceFair/src/MALEKRQsample.txt");
try
{
Scanner userInput = new Scanner(System.in);
System.out.println("Enter Protein Sequence");
String userProteinSequence = userInput.nextLine().toUpperCase();
for (int size = userProteinSequence.length(); size >= 4; size--) {
for (int start = 0; start <= userProteinSequence.length()-size; start++) {
boolean found = false;
String search = userProteinSequence.substring(start, size);
System.out.println(search);
Scanner fileInput = new Scanner(file);
while (fileInput.hasNext()) {
String MALEKRQ = fileInput.nextLine();
int found = MALEKRQ.indexOf(search);
if (found >= 0) {
found = true;
}
}
if (found) {
System.out.println(search+" found (index "+start+")");
fileInput = new Scanner(file);
while (fileInput.hasNext()) {
String MALEKRQ = fileInput.nextLine();
MALEKRQ = MALEKRQ.replaceAll(search, "[["+search+"]]");
System.out.println(MALEKRQ);
}
return;
}
}
}
System.out.println(search+" not found");
Scanner fileInput = new Scanner(file);
while (fileInput.hasNext()) {
String MALEKRQ = fileInput.nextLine();
System.out.println(MALEKRQ);
}
} catch (FileNotFoundException e) {
System.err.format("File does not exist.\n");
}
}
}

Trying to read a file and put values in an array

I need to read certain portions of a file and put them into their correct array.
public static void load(String fileName, String[] itemNumbers,
String[] itemNames, double[] priceOfItem, int[] quantity) throws IOException{
int i = 0;
File inFile = new File(fileName);
Scanner reader = new Scanner(inFile);
while(reader.hasNext()){
itemNumbers[i] = reader.next();
itemNames[i] = reader.next();
priceOfItem[i] = reader.nextDouble();
quantity[i] = reader.nextInt();
i++;
}
//This is just to see if it worked
System.out.println(itemNumbers[i]);
System.out.println(itemNames[i]);
System.out.println(priceOfItem[i]);
System.out.println(quantity[i]);
}
Here is the file I'm reading.
E3233 CordlessDrill 129.99 12
W2321 WindowSealer 3.39 84
The arrays are in order with the file portions.
When I run this I receive the following
null
null
0.0
0
Make sure it says
while(reader.hasNextLine())
have you tried using FileReader?
public static void load(String fileName, String[] itemNumbers,
String[] itemNames, double[] priceOfItem, int[] quantity) throws IOException{
File inFile = new File(fileName);
char[] cbuf = new char[(int) inFile.length()];
FileReader r = new FileReader(inFile);
r.read(cbuf);
String finalString = String.valueOf(cbuf);
String[] lines = finalString.split("\n");
itemNumbers = new String[lines.length];
itemNames = new String[lines.length];
priceOfItem = new double[lines.length];
quantity = new int[lines.length];
for(int i = 0; i < lines.length; i++){
String line = lines[i].replace("\n", "");
String[] values = line.split(" ");
String itemNumber = values[0];
String itemName = values[1];
double price = Double.parseDouble(values[2]);
int quant = Integer.parseInt(values[3].replace(String.valueOf((char)13), "").replace(" ", "").replace("\"", ""));
itemNumbers[i] = itemNumber;
itemNames[i] = itemName;
priceOfItem[i] = price;
quantity[i] = quant;
}
r.close();
for(int i = 0; i < itemNames.length; i++){
System.out.println(itemNumbers[i]);
System.out.println(itemNames[i]);
System.out.println(priceOfItem[i]);
System.out.println(quantity[i]);
System.out.println("\n");
}
}
this method relies on using spaces in your file, I would add comma's and end lines with semicolons to be safe, but if you maintain the same format this should work.

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

Why is my mode program not printing anything?

Sorry for click bait title, but it is my problem, and I can't really change to wording without losing the question.
I have the following code which is meant to select a file, read it, and find it's mode, and I think I got it done, but I have one issue
public class ModeFinder
{
public static int countDoubles(File file) throws FileNotFoundException
{
Scanner reader = new Scanner(file);
int count = 0;
while (reader.hasNextDouble())
{
count++;
reader.nextDouble();
}
reader.close();
return count;
}
public static void main(String args[]) throws FileNotFoundException
{
String filename;
FileDialog filePicker = new FileDialog(new JFrame());
filePicker.setVisible(true);
filename = filePicker.getFile();
String folderName = filePicker.getDirectory();
filename = folderName + filename;
System.out.println("filename = " +filename);
File inputFile = new File(filename);
Scanner fileReader = new Scanner (inputFile);
int maxValue = 0,
maxCount = 0;
int[] a = new int[countDoubles(inputFile)];
while (fileReader.hasNextInt())
{
for (int i = 0; i < a.length; i++)
{
int count = 0;
for (int j = 0; j < a.length; j++)
{
if (a[j] == a[i])
count++;
}
if (count > maxCount)
{
maxCount = count;
maxValue = a[i];
}
}
}
System.out.println("The most common grade is: " +maxValue);
}
}
The last bit with the most common grade doesn't even print and I don't know why.
You aren't calling nextInt to get the value from the file so your while loop is going to loop forever. You need something like:
while (fileReader.hasNextInt())
{
int value = fileReader.nextInt();
...

Categories

Resources