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.
Related
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);
}
}
}
}
So in my codes, I am trying to read a file that is like:
100
22
123;22
123 342;432
but when it outputs it would include the ";" ( ex. 100,22,123;22,123,342;432} ).
I am trying to make the file into an array ( ex. {100,22,123,22,123...} ).
Is there a way to read the file, but ignore the semicolons?
Thanks!
public static void main(String args [])
{
String[] inFile = readFiles("ElevatorConfig.txt");
for ( int i = 0; i <inFile.length; i = i + 1)
{
System.out.println(inFile[i]);
}
System.out.println(Arrays.toString(inFile));
}
public static String[] readFiles(String file)
{
int ctr = 0;
try{
Scanner s1 = new Scanner(new File(file));
while (s1.hasNextLine()){
ctr = ctr + 1;
s1.next();
}
String[] words = new String[ctr];
Scanner s2 = new Scanner(new File(file));
for ( int i = 0 ; i < ctr ; i = i + 1){
words[i] = s2.next();
}
return words;
}
catch(FileNotFoundException e)
{
return null;
}
}
public static String[] readFiles(String file)
{
int ctr = 0;
try{
Scanner s1 = new Scanner(new File(file));
while (s1.hasNextLine()){
ctr = ctr + 1;
s1.next();
}
String[] words = new String[ctr];
Scanner s2 = new Scanner(new File(file));
for ( int i = 0 ; i < ctr ; i = i + 1){
words[i] = s2.next();
}
return words;
}
catch(FileNotFoundException e)
{
return null;
}
}
Replace this by
public static String[] readFiles(String file) {
List<String> retList = new ArrayList<String>();
Scanner s2 = new Scanner(new File(file));
for ( int i = 0 ; i < ctr ; i = i + 1){
String temp = s2.next();
String[] tempArr = se.split(";");
for(int k=0;k<tempArr.length;k++) {
retList.add(tempArr[k]);
}
}
return (String[]) retList.toArray();
}
Use regex. Read the entire file into a String (read each token as a String and append a blank space after each token in the String) and then split it at blank spaces and semi colons.
String x <--- contains all contents of the file
String[] words = x.split("[\\s\\;]+");
The contents of words[] are:
"100", "22", "123", "22", "123", "342", "432"
Remember to parse them to int before using as numbers.
Simple way to use BufferedReader Read line by line then split by ;
public static String[] readFiles(String file)
{
BufferedReader br = new BufferedReader(new FileReader(file)))
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String allfilestring = sb.toString();
String[] array = allfilestring.split(";");
return array;
}
You can use split() to split the string into array according to your requirement using regex.
String s; // string you have read from the file
String[] s1 = s.split(" |;"); // s1 contains the strings separated by space and ";"
Hope it helps
Keep the code for counting the size of the array.
I would just change the way you input your values.
for (int i = 0; i < ctr; i++) {
words[i] = "" + s1.nextInt();
}
Another option is to replace all non digit characters in your complete file string with a space. That way any non number character is ignored.
BufferedReader br = new BufferedReader(new FileReader(file)))
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
String str = sb.toString();
str = str.replaceAll("\\D+"," ");
Now you have a string with numbers separated by spaces, we can tokenize them into number strings.
String[] final = str.split("\\s+");
then convert to int datatypes.
I've been having some difficulties reading in information from a file into separate arrays. An example of the information in the file is:
14 Barack Obama:United States
17 David Cameron:United Kingdom
27 Vladimir Putin:Russian Federation
19 Angela Merkel:Germany
While I can separate the integers into an array, I am having trouble creating an array for the names and an array for the countries. This is my code thus far:
import java.util.*;
import java.io.*;
public class leadRank {
public static void main(String[] args) throws FileNotFoundException {
int size;
Scanner input = new Scanner(new File("names.txt"));
size = input.nextInt();
int[] rank = new int[size];
for (int i = 0; i < rank.length; i++) {
rank[i] = input.nextInt();
input.nextLine();
}
String[] name = new String[size];
for (int i = 0; i <name.length; i++) {
artist[i] =
I think that I would have to read in the line as a string and use indexOf to find the colon in order to start a new array but I'm unsure as to how to execute that.
I just tried to solve your problem in my ways. It was just for a time pass. Hopes this may helps you.
import java.util.*;
import java.io.*;
public class leadRank {
public static void main(String[] args) throws FileNotFoundException {
int size;
File file = new File("names.txt");
FileReader fr = new FileReader(file);
String s;
LineNumberReader lnr = new LineNumberReader(new FileReader(file));
lnr.skip(Long.MAX_VALUE);
size = lnr.getLineNumber()+1;
lnr.close();
int[] rank = new int[size];
String[] name = new String[size];
String[] country = new String[size];
try {
BufferedReader br = new BufferedReader(fr);
int i=0;
while ((s = br.readLine()) != null) {
String temp = s;
if(temp.contains(":")){
String[] splitres = temp.split(":");
String sub = splitres[0];
rank[i] = Integer.parseInt(sub.substring(0,sub.indexOf(" "))); // Adding rank to array rank[]
name[i] = sub.substring(sub.indexOf(" "), sub.length()-1); // Adding name to array name[]
country[i] = splitres[1]; // Adding the conutries to array country[]
}
i++;
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
This is a bit more efficient because it goes through the file only once.
public static void main(String[] args) throws FileNotFoundException {
// create an array list because the size of the array is still not know
ArrayList<Integer> ranks = new ArrayList<Integer>();
ArrayList<String> names = new ArrayList<String>();
ArrayList<String> countries = new ArrayList<String>();
// read the input file
Scanner input = new Scanner(new File("names.txt"));
// read each line
while (input.hasNext()) {
String wholeLine = input.nextLine();
// get the index of the first space
int spaceIndex = wholeLine.indexOf(" ");
// parse the rank
int rank;
try {
rank = Integer.parseInt(wholeLine.substring(0, spaceIndex));
} catch (NumberFormatException e) {
rank = -1;
}
// parse the name & country
String[] tokens = wholeLine.substring(spaceIndex + 1).split(":");
String name = tokens[0];
String country = tokens[1];
// add to the arrays
ranks.add(rank);
names.add(name);
countries.add(country);
}
// get your name and country arrays if needed
String[] nameArr = names.toArray(new String[]{});
String[] countryArr = countries.toArray(new String[]{});
// the rank array has to be created manually
int[] rankArr = new int[ranks.size()];
for (int i = 0; i < ranks.size(); i++) {
rankArr[i] = ranks.get(i).intValue();
}
}
I've been trying to fill an array with strings & break it into different arrays, but i must not be reading it in right because my array has nothing in it?
File inf = FileUtil.openFile(args); // open the file passedin in args
Scanner fin = new Scanner(inf);
public static File readFileInfo(Scanner kb)throws FileNotFoundException
{
String fileName = null;
File inFile = null;
do
{
System.out.print("Enter the name of the input file: ");
fileName = kb.nextLine();
inFile = new File(fileName);
}while(!inFile.exists());
return inFile;
}// end readFileInfo
public static Author[] fillArray(Scanner fin)
{
Author[] array = new Author[100];
String first_ = null;
String last_ = null;
String publisher_ = null;
int x = 0;
while(fin.hasNext())
{
first_ = fin.nextLine();
last_ = fin.nextLine();
publisher_ = fin.nextLine();
Author temp = new Author(first_, last_, publisher_);
array[x] = temp;
x++;
}
return array;
Maybe the problem is that you check if you have one more token but try to fetch three tokens
while(fin.hasNext()) // CHECK IF WE HAVE ONE MORE TOKEN
{
first_ = fin.nextLine(); // FETCH THREE
last_ = fin.nextLine();
publisher_ = fin.nextLine();
Author temp = new Author(first_, last_, publisher_);
array[x] = temp;
x++;
}
This may have lead to an exception, and the empty array.
again. im gonna ask again about counting words and how to store it in array. So far, all i got is this.
Scanner sc = new Scanner(System.in);
int count;
void readFile() {
System.out.println("Gi navnet til filen: ");
String filNavn = sc.next();
try{
File k = new File(filNavn);
Scanner sc2 = new Scanner(k);
count = 0;
while(sc2.hasNext()) {
count++;
sc2.next();
}
Scanner sc3 = new Scanner(k);
String a[] = new String[count];
for(int i = 0;i<count;i++) {
a[i] =sc3.next();
if ( i == count -1 ) {
System.out.print(a[i] + "\n");
}else{
System.out.print(a[i] + " ");
}
}
System.out.println("Number of words: " + count);
}catch(FileNotFoundException e) {
my code works. but my question is, is there a more simple way to this? And the other question is how do i count the unique words out of the total words in a given file without using hashmap and arraylist.
Heres a simpler way to go about it:
public static void main(String[] args){
File f= new File(filename);
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
String line = null;
String[] res;
while((line = br.readLine())!= null ){
String[] tokens = line.split("\\s+");
String[] both = ArrayUtils.addAll(res, tokens);
}
}