I have two classes, one with instance variables and the other will read a file. The file with one main loop will store an array of workers. I don't know when the getMethods should be placed.
the file has looks a bit like this:
Joames peter 5 15.00
Laura Kelly 30 12.00
Tim McAdam 18 15.00
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class PayRoll {
private static Scanner kbd;
public static void main(String[] args) {
final int NUMBER_OF_WORKERS = 15;
final String INPUT_FILE = "data.txt";
Worker[] worker_ar = new Worker[NUMBER_OF_WORKERS];
try{
kbd = new Scanner(new File(INPUT_FILE));
}
catch(FileNotFoundException e){
System.err.println("File Not Found!");
}
String line = null;
int i = 0 ;
while((kbd.hasNextLine()) && (i < worker_ar.length))
{
// these are the variables I have in the other class. I need these so I can
// later reverse the file data and comute total pay and average pay.
line = kbd.nextLine();
worker_ar[i] = (getfName(), getlName(), getHours(), gethrly_pay());
i++;
}
kbd.close();
}
// I will put two methods here to make the file reverse
}
Use StringTokenizer with space separator.
Nitpick: Use Employee instead of Worker. It's has more sense, and Worker used in Java for something else.
Related
I am trying to write a program that inputs a text file through the command line and then prints out the number of words in the text file. I've spent around 5 hours on this already. I'm taking an intro class using java.
Here is my code:
import java.util.*;
import java.io.*;
import java.nio.*;
public class WordCounter
{
private static Scanner input;
public static void main(String[] args)
{
if (0 < args.length) {
String filename = args[0];
File file = new File(filename);
}
openFile();
readRecords();
closeFile();
}
public static void openFile()
{
try
{
input = new Scanner(new File(file));
}
catch (IOException ioException)
{
System.err.println("Cannot open file.");
System.exit(1);
}
}
public static void readRecords()
{
int total = 0;
while (input.hasNext()) // while there is more to read
{
total += 1;
}
System.out.printf("The total number of word without duplication is: %d", total);
}
public static void closeFile()
{
if (input != null)
input.close();
}
}
Each way I've tried I get a different error and the most consistent one is "cannot find symbol" for the file argument in
input = new Scanner(new File(file));
I'm also still not entirely sure what the difference between java.io and java.nio is so I have tried using objects from both. I'm sure this is an obvious problem I just can't see it. I've read a lot of similar posts on here and that is where some of my code is from.
I've gotten the program to compile before but then it freezes in command prompt.
java.nio is the New and improved version of java.io. You can use either for this task. I tested the following code in the command line and it seems to work fine. The "cannot find symbol" error message is resolved in the try block. I think you were confusing the compiler by instantiating a File object named file twice. As #dammina answered, you do need to add the input.next(); to the while loop for the Scanner to proceed to the next word.
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class WordCounter {
private static Scanner input;
public static void main(String[] args) {
if(args.length == 0) {
System.out.println("File name not specified.");
System.exit(1);
}
try {
File file = new File(args[0]);
input = new Scanner(file);
} catch (IOException ioException) {
System.err.println("Cannot open file.");
System.exit(1);
}
int total = 0;
while (input.hasNext()) {
total += 1;
input.next();
}
System.out.printf("The total number of words without duplication is: %d", total);
input.close();
}
}
Your code is almost correct. Thing is in the while loop you have specified the terminating condition as follows,
while (input.hasNext()) // while there is more to read
However as you are just increment the count without moving to the next word the count just increases by always counting the first word. To make it work just add input.next() into the loop to move to next word in each iteration.
while (input.hasNext()) // while there is more to read
{
total += 1;
input.next();
}
In this program I am just getting input from a file and trying to get the boys name and the girls name out of it, and also put them in separate files. I have done everything just as the book has stated. And I've also searched everywhere online for help with this but cant seem to find anyone with the same problem. Ive seen problems where its not -1 but a positive number because they went to far out of the string calling a substring over the strings length. But cant seem to figure out this giving me -1 since i's value is 1.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.ArrayList;
public class Homework_11_1 {
public static void main(String[] args)throws FileNotFoundException
{
File inputFile = new File("babynames.txt");
Scanner in = new Scanner(inputFile);
PrintWriter outBoys = new PrintWriter("boys.txt");
PrintWriter outGirls = new PrintWriter("girls.txt");
while (in.hasNextLine()){
String line = in.nextLine();
int i = 0;
int b = 0;
int g = 0;
while(!Character.isWhitespace(line.charAt(i))){ i++; }
while(Character.isLetter(line.charAt(b))){ b++; }
while(Character.isLetter(line.charAt(g))){ g++; }
String rank = line.substring(i);
String boysNames = line.substring(i, b);
String girlsNames = line.substring(b, g);
outBoys.println(boysNames);
outGirls.println(girlsNames);
}
in.close();
outBoys.close();
outGirls.close();
System.out.println("Done");
}
}
Here is the txt file
1 Jacob Sophia
2 Mason Emma
3 Ethan Isabella
4 Noah Olivia
5 William Ava
6 Liam Emily
7 Jayden Abigail
8 Michael Mia
9 Alexander Madison
10 Aiden Elizabeth
I would have written it an other way, using split.
public static void main(String[] args)throws FileNotFoundException
{
File inputFile = new File("babynames.txt");
Scanner in = new Scanner(inputFile);
PrintWriter outBoys = new PrintWriter("boys.txt");
PrintWriter outGirls = new PrintWriter("girls.txt");
while (in.hasNextLine()){
String line = in.nextLine();
String[] names = line.split(" "); // wile give you [nbr][boyName][GirlName]
String boysNames = names[1];
String girlsNames = names[2];
outBoys.println(boysNames);
outGirls.println(girlsNames);
}
in.close();
outBoys.close();
outGirls.close();
System.out.println("Done");
}
Rather than fuss with loops and substring(), I'd just use String.split(" "). Of course, the assignment may not permit you to do this.
But anyway, without giving you the answer to the assignment, I can tell you that your logic is wrong. Walk through it and find out why. If you try running this code on just the first line of the input file, you'll get these values: i=1, b=0, and g=0. Calling line.substring(1,0) is obviously not going to work.
i am currently doing a small task in java which i am very new to so please excuse any silly mistakes i have made. Basically i am trying to take 2 values from a text document, import them into my java document and then multiply them together. These 2 numbers are meant to represent the hourly pay and amount of hours worked, then the output is the total amount the member of staff has earned. This what i have so far ...
import java.util.*;
import java.io.*;
public class WorkProject
{
Scanner inFile = new Scanner(new FileReader("staffnumbers.txt"));
double Hours;
double Pay;
Hours = inFile.nextDouble();
Pay = inFile.nextDouble();
double earned = Length * Width;
System.out.println(earned);
}
What i have so far is basically me trying to get the .txt document into my java file. I'm not sure if this is right and then i'm not sure where to go to get the values to multiply and have it outputted. I understand what i have so far is probably just the very start of what i need but any help will be massively appreciated as i am keen to learn. Thanks so much .... Hannah
I don't know what Amount earned is. So my guess is you need to change the last line to
double amountEarned = Hours * Pay; //this multiplies the values
System.out.println(amountEarned); //this outputs the value to the console
EDIT:
Putting code inside a main method:
public class WorkProject {
public static void main(String[] args) throws FileNotFoundException {
Scanner inFile = new Scanner(new FileReader("C:\\staffnumbers.txt"));
double Hours;
double Pay;
Hours = inFile.nextDouble();
Pay = inFile.nextDouble();
double amountEarned = Hours * Pay;
System.out.println(amountEarned);
}
}
// Matt Stillwell
// April 12th 2016
// File must be placed in root of the project folder for this example
import java.io.File;
import java.util.Scanner;
public class Input
{
public static void main(String[] args)
{
// declarations
Scanner ifsInput;
String sFile;
// initializations
ifsInput = null;
sFile = "";
// attempts to create scanner for file
try
{
ifsInput = new Scanner(new File("document.txt"));
}
catch(FileNotFoundException e)
{
System.out.println("File Doesnt Exist");
return;
}
// goes line by line and concatenates the elements of the file into a string
while(ifsInput.hasNextLine())
sFile = sFile + ifsInput.nextLine() + "\n";
// prints to console
System.out.println(sFile);
}
}
I just started to code a while back and I'm in the process of dealing with arrays on my own, I understand them in theory but I need some help when it comes to getting practical. I asked my instructor to give me a couple of practices problems and he gave me the following.
using this as your main:
public static void main(String[] args) {
DatosPalabras datos = new DatosPalabras( "words.txt" );
JOptionPane.showMessageDialog(null, datos );
datos.sort();
JOptionPane.showMessageDialog(null, datos);
}
(its in spanish so bear with me) create a class named DatosPalabras and words.txt and make sure your code can:
Read and display words.txt
Display the words in "words.txt" in alphabetical order
I really appreciate the help, I'm a bit stumped but I'm curious to know how I can accomplish this. Thank you!
EDIT:
public class DatosPalabras {
public DatosPalabras(String string) {
// read and display the content of words.txt
}
public void sort() {
// need info on what to use in order to sort words instead of doubles and integers.
}
}
In this example I have 1 file named Q19505617.java. Java only allows you to have 1 public class per file. It is the class that defines the main method. So this example works only because the DatosPalabras class is contained in that file. If you need DatosPalabras to be its own class then put the DatosPalabras in its own file named DatosPalabras.java and change the class signature to be public class DatosPalabras.
import java.io.InputStream;
import java.util.Arrays;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Q19505617 {
public static void main(String[] args) {
DatosPalabras datos = new DatosPalabras("words.txt");
JOptionPane.showMessageDialog(null, datos);
datos.sort();
JOptionPane.showMessageDialog(null, datos);
}
}
class DatosPalabras {
private String[] lines;
public DatosPalabras(String filename) {
lines = new String[1];
int lineCounter = 0;
InputStream in = Q19505617.class.getResourceAsStream(filename);
Scanner scanner = new Scanner(in);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
if(lineCounter == lines.length) {
lines = Arrays.copyOf(lines, lines.length * 2);
}
lines[lineCounter] = line;
lineCounter++;
}
}
public void sort() {
// put your real sort algorithm here. until then use this:
}
public String toString() {
StringBuilder b = new StringBuilder();
for (String line : lines) {
b.append(line).append("\n");
}
return b.toString();
}
}
You can create a reading Array like this:
String[] Array = new String[number of lines in you txt file];
int i = 0;
// Selecting the txt file
File theFile = new File("bla.txt");
//Creating a scanner to read the file
scan = new Scanner(theFile);
//Reading all the words from the txt file
while (scan.hasNextLine()) {
line = scan.nextLine();
Array[i] = line; // gets all the lines
i++;
Then you create a method for sorting.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.ArrayList;
/**
* Write a description of class ReadInCsv here.
*
* #author (Kevin Knapp)
* #version (10-10-2013)
*/
public class ReadInCsv
{
public static void main(String[] args)
{
String csvName = "Countries.csv";
File csvFile = new File(csvName);
ArrayList<String> nameList = new ArrayList<>();
ArrayList<String> popList = new ArrayList<>();
ArrayList<String> areaList = new ArrayList<>();
ArrayList<String> gdpList = new ArrayList<>();
ArrayList<String> litRateList = new ArrayList<>();
try
{
Scanner in = new Scanner(csvFile).useDelimiter(",");
while (in.hasNext())
{
String name = in.next();
nameList.add(name);
String pop = in.next();
popList.add(pop);
String area = in.next();
areaList.add(area);
String gdp = in.next();
gdpList.add(gdp);
String litRate = in.next();
litRateList.add(litRate);
}
in.close();
System.out.println(nameList);
System.out.println(popList);
System.out.println(areaList);
System.out.println(gdpList);
System.out.println(litRateList);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
So im trying to read from a csv file and as it goes through it should add each scanned instance into a array list (im going to reference each element from these lists at a later point), but my outputs show that as soon as it reads something and adds it, it skips to the next line before reading the next string, i need it to read straight across, not diagonally
im sure im just missing something very simple, I just began learning java about a week ago, thanks for the help
A big problem with this method is that unless each line in the file ends in a comma, newlines will not be delimited. A better way is to read each line in, split on commas, and add the values to the ArrayLists one line at a time:
Scanner in = new Scanner(csvFile);
while (in.hasNextLine()) {
String[] fields = in.nextLine().split(",");
if (fields.length == 5) {
nameList.add(fields[0]);
popList.add(fields[1]);
areaList.add(fields[2]);
gdpList.add(fields[3]);
litRateList.add(fields[4]);
} else {
// Bad line...do what you want to show error here
}
}
An even better way is to use a Java library dedicated to reading CSV files. A quick Google search should turn up some good ones.