How to make Code more efficient/clean - USACO Training First Task - java

I'm having trouble with the first problem on the USACO Training Page.
The task is asking for two strings from a text.in file, converting the strings into a number that is the product of the letters (where a=1, b=2, z=26), then seeing if the remainders of the numbers/47 are equal to each other (if they are, print "GO", if not, print "STAY").
It works great on my computer, but when I send it in, it displays
Run 1: Execution error: Your program exited with exit status `1'.
------ Data for Run 1 [length=14 bytes] ------
COMETQ
HVNGAT
----------------------------
Your program printed data to stderr. Here is the data:
-------------------
Exception_in_thread_"main"_java.io.FileNotFoundException:_test.in_(No_such_file_or_directory)
at_java.io.FileInputStream.open(Native_Method)
at_java.io.FileInputStream.<init>(FileInputStream.java:106)
at_java.io.FileInputStream.<init>(FileInputStream.java:66)
at_java.io.FileReader.<init>(FileReader.java:41)
at_ride.main(Unknown_Source)
I tried looking at this http://cerberus.delos.com:790/usacoprobfix?a=VjAAvKvQucH , but I couldn't really understand terms such as "stack usage" or "out-of-bounds".
Is the reason why it is not accepting my code because it is too slow? I would appreciate any help figuring out this problem.
/*
ID: Anon
LANG: JAVA
TASK: ride
*/
import java.io.*;
import java.util.*;
class ride
{
public static void main (String [] args) throws IOException
{
//input
BufferedReader br = new BufferedReader(new FileReader("test.in"));
//output
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("test.out")));
String nameComet = br.readLine();
String nameGroup = br.readLine();
int productComet = 1;
int productGroup = 1;
//loop through each letter in word
for(int i=0; i<nameComet.length(); i++)
{
//sets letter to char letter
char letter = nameComet.charAt(i);
//set number of letter to correspondnum
int numComet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf(letter) + 1;
productComet *= numComet;
}
for(int i=0; i<nameGroup.length(); i++)
{
//sets letter to char letter
char letter = nameGroup.charAt(i);
//set number of letter to correspondnum
int numGroup = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf(letter) + 1;
productGroup *= numGroup;
}
int modComet = productComet % 47;
int modGroup = productGroup % 47;
if (modComet == modGroup)
{
out.println("GO");
}
else
{
out.println("STAY");
}
//close everything
out.close();
System.exit(0);
}
}

Your error is on these lines:
BufferedReader br = new BufferedReader(new FileReader("test.in"));
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("test.out")));
Your code is attempting to read from a file ("test.in") that doesn't exist on the usaco servers. When you submit your code to the website, you need to read from files that have the same name as that of the problem (e.g. "ride.in" and "ride.out").
Hope that helps!

Related

Is it possible to write a text file in such a way that when read by the Java compiler, it will add a line break at certain points?

For my Java class, I'm working on a project that is essentially a database for MTG cards. I have to read from a file as part of the project, so I am reading the card information from a file, and then splitting the lines to put each different type of information together to form different object classes for the different types of cards. The main nitpicky issue I'm running into right now is that I need the card text to be on one line in the text file so I can read it line by line, but I'd prefer if it weren't all on one line when I print it to the console. Is there any way to add a character combination into the text of the file itself that will tell my compiler, "line break here," when it reads that, or am I out of luck? I know I could just use \n in the code to achieve this, but as I am looping through the file, there is no way to do so properly that I know of, as not every card's text needs line breaks inserted. If it matters, this is the chunk of my code that deals with that:
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Scanner;
public class MTG {
public static void main(String[] args) {
int creatureLength = 4;
//Prompt User
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to the Magic: the Gathering card database. This tool currently supports Rare and Mythic Rare cards from the Throne of Eldraine Expansion.");
try {
System.out.println("\nSelect the card type you'd like to view.");
System.out.println(""
+ "(1)Creatures\n"
);
int choice = Integer.parseInt(sc.next());
//Choose type
//Creatures
if(choice == 1){
Creature[] creatures = creatureGen("textfiles/Creatures.txt", creatureLength);
System.out.println("\nViewing creatures. Which card would you like to view?: \n");
for(int k = 0; k < creatureLength; k++) {
System.out.println(
"(" + (k + 1) + ") " + creatures[k].getName());
}
int creatureChoice = Integer.parseInt(sc.next());
try {
System.out.println("\n" + creatures[(creatureChoice - 1)]);}
catch(Exception e) {
System.out.println("Input was not a specified number. Exiting...");
}
}
}
catch(NumberFormatException ex){
System.out.println("Input was not a specified number. Exiting...");
}
sc.close();
}
//Read Creature text file
public static Creature[] creatureGen(String path, int length) {
Creature[] creatures = new Creature[length];
try {
FileReader file = new FileReader(path);
BufferedReader reader = new BufferedReader(file);
String name[] = new String[length];
String cost[] = new String[length];
String color[] = new String[length];
String type[] = new String[length];
String cTypes[] = new String[length];
String tags[] = new String[length];
String text[] = new String[length];
int power[] = new int[length];
int toughness[] = new int[length];
for (int i = 0; i < length; i++) {
String line = reader.readLine();
if(line != null) {
name[i] = line.split("\\|")[0];
cost[i] = line.split("\\|")[1];
color[i] = line.split("\\|")[2];
type[i] = line.split("\\|")[3];
cTypes[i] = line.split("\\|")[4];
tags[i] = line.split("\\|")[5];
text[i] = line.split("\\|")[6];
power[i] = Integer.parseInt(line.split("\\|")[7]);
toughness[i] = Integer.parseInt(line.split("\\|")[8]);
creatures[i] = new Creature(name[i], cost[i], color[i], type[i], cTypes[i], tags[i], text[i], power[i], toughness[i]);
}
}
reader.close();
}
catch (Exception e) {
System.out.println("Error reading file: " + path);
}
return creatures;
}
}
The Creature object class essentially just stores the data that I am putting into it with the creatureGen method. A sample line from the text file I am reading from looks something like this:
Charming Prince|1W|White|Creature|Human Noble||When Charming Prince enters the battlefield, choose one — • Scry 2. • You gain 3 life. • Exile another target creature you own. Return it to the battlefield under your control at the beginning of the next end step.|2|2
It would be ideal to be able to insert line breaks after each of the bullet points in this card, for example, but as I said earlier, I need the text to be in one line for my loop to read it. Is there any way around this when I print this back to the console? I appreciate any help.
Just replace those bullet points with line breaks :
text[i] = line.split("\\|")[6].replaceAll("•","\n");
Also, you should not split each time you need an element, put the result of line.split("\|") in a String[] variable and use it afterwards.
for (int i = 0; i < length; i++) {
String line = reader.readLine();
if(line != null) {
String[] elements = line.split("\\|");
name[i] = elements[0];
cost[i] = elements[1];
color[i] = elements[2];
type[i] = elements3];
cTypes[i] = elements[4];
tags[i] = elements[5];
text[i] = elements[6].replaceAll("•","\n");
power[i] = Integer.parseInt(elements[7]);
toughness[i] = Integer.parseInt(elements[8]);
creatures[i] = new Creature(name[i], cost[i], color[i], type[i], cTypes[i], tags[i], text[i], power[i], toughness[i]);
}
}
Finally, about vocabulary, the compiler is not reading your file. The compiler translates your code into binary instructions for the processor (to summarize).
Your file is read at runtime.

Counting words from a file

for this program I have to write I'm given an input file of strings that has a line (or lines) of text, for example: "The high HIGH cat High jumped (WOW 6SOFT)". From this line I have to scan the file, count the number of times a word appears (regardless of capitalization), and then output it to a formatted file. If a digit comes before a word, the word should not be counted. The format has to be started with the count right justified in three spaces, followed by another space, followed by the word counted in lower case.
package InClass;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
public class CountWords {
public static void main(String[] args) {
try {
File inputFile = new File("input.txt");
Scanner scanner = new Scanner(inputFile);
File outputFile = new File("output.txt");
PrintWriter writer = new PrintWriter(outputFile);
boolean next = scanner.hasNext();
ArrayList<String> inputWords = new ArrayList<String>();
ArrayList<String> outputWords = new ArrayList<String>();
while (next) { // Adds all the strings to an array list
inputWords.add(scanner.next());
for (int i = 0; i < inputWords.size(); i++) {
inputWords.get(i).toLowerCase();
}
}
while (next) {
for (int i = 0; i < inputWords.size(); i++) {
String word = inputWords.get(i);
int count = 1;
if (!Character.isDigit(word.charAt(0))) {
outputWords.add(inputWords.get(i));
if (outputWords.contains(word)) {
count++;
}
} else {
inputWords.remove((i));
}
for (int j = 0; i < outputWords.size(); j++) {
word = outputWords.get(i);
writer.printf("%3s" + "%1s\n", count, word);
}
}
}
scanner.close();
writer.close();
} catch (FileNotFoundException e) {
}
}
}
My tester file is giving me an error saying there is a NoSuchElementException for only one of the tester classes, which is testing two words. Here is the test class giving the error"
#Test
public void testTwoWords() {
try {
File inputFile = new File(INPUT);
File outputFile = new File(OUTPUT);
// If assert fails it is (usually) because the file was (wrongly)
// left open in an earlier run.
// Using a file manager application (e.g. explorer), go to project
// directory and delete it.
// Make sure that your program closes these files before ending.
if (inputFile.exists()) {
assertTrue("Your program left \"" + INPUT
+ "\" open in a previous test.", inputFile.delete());
}
if (outputFile.exists()) {
assertTrue("Your program left \"" + OUTPUT
+ "\" open in a previous test.", outputFile.delete());
}
// create INPUT file
PrintWriter input = new PrintWriter(inputFile);
input.println("King");
input.println("");
input.println("");
input.println("");
input.println("hill");
input.close();
// invoke program
CountWords.main(null);
// verify OUTPUT file exists and is empty
assertTrue("Output file doesn't exist", outputFile.exists());
Scanner output = new Scanner(outputFile);
String actual = output.nextLine();
assertEquals("Incorrect result", " 1 king", actual);
actual = output.nextLine();
assertEquals("Incorrect result", " 1 hill", actual);
assertFalse("There should be no more data", output.hasNext());
output.close();
// delete I/O files
assertTrue("Input file could not be deleted", inputFile.delete());
assertTrue("Output file could not be deleted", outputFile.delete());
} catch (IOException e) {
fail("No exception should be thrown");
}
}
Finally, my other testers are saying "Your program left "input.txt" open in a previous test". Any idea why? Thank you tons in advance!
The for loop for your outputWords is using the i loop counter instead of j.
for (int j = 0; i < outputWords.size(); j++) {
word = outputWords.get(i);
writer.printf("%3s" + "%1s\n", count, word);
}
Change that to
for (int j = 0; i < outputWords.size(); j++) {
word = outputWords.get(j);//NEED TO USE J HERE
writer.printf("%3s" + "%1s\n", count, word);
}
The reason the other tests are failing is because you are apparently supposed to delete the output files after each test is run.

Matching two Files in java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am new to java
Can anyone help me with the code to tell how much 2 text files match with each other?
Suppose i have two Files 'a.txt' and 'b.txt'
then i need to know the percentage of match.
thanks
Read in the two files to two Strings str1, str2.
Iterate through each, counting matching chars. Divide number of matches by number of compares, and multiply by 100 to get a percentage.
Scanner sca = new Scanner(new File ("a.txt"));
Scanner scb = new Scanner(new File ("b.txt"));
StringBuilder sba = new StringBuilder();
StringBuilder sbb = new StringBuilder();
while(sca.hasnext()){
sba.append(sca.next());
}
while(scb.hasnext()){
sbb.append(scb.next());
}
String a = sba.toString();
String b = sbb.toString();
int maxlen = Math.max(a.length,b.length);
int matches;
for(int i =0; i<maxlen; i++){
if(a.length <=i || b.length <=i){
break;
}
if(a.chatAt(i)==b.charAt(i)){
matches++;
}
return (((double)matches/(double)maxlen)*100.0)
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.StringTokenizer;
class File_meta_Data // class to store the metadata of file so that scoring can be done
{
String FileName;
long lineNumber;
long Position_In_Line;
long Position_In_Document;
File_meta_Data()
{
FileName = null;
lineNumber = 0;
Position_In_Line = 0;
Position_In_Document = 0;
}
}
public class bluestackv1 {
static int getNumberofInputFiles() // seeks number of resource files from user
{
System.out.println("enter the number of files");
Scanner scan = new Scanner(System.in);
return(scan.nextInt());
}
static List getFiles(int Number_of_input_files) // seeks full path of resource files from user
{
Scanner scan = new Scanner(System.in);
List filename = new ArrayList();
int i;
for(i=0;i<Number_of_input_files;i++)
{
System.out.println("enter the filename");
filename.add(scan.next());
}
return(filename);
}
static String getfile() // seeks the full pathname of the file which has to be matched with resource files
{
System.out.println("enter the name of file to be matched");
Scanner scan = new Scanner(System.in);
return(scan.next());
}
static Map MakeIndex(List filename) // output the index in the map.
{
BufferedReader reader = null; //buffered reader to read file
int count;
Map index = new HashMap();
for(count=0;count<filename.size();count++) // for all files mentioned in the resource list create index of its contents
{
try {
reader = new BufferedReader(new FileReader((String) filename.get(count)));
long lineNumber;
lineNumber=0;
int Count_of_words_in_document;
Count_of_words_in_document = 0;
String line = reader.readLine(); // data is read line by line
while(line!=null)
{
StringTokenizer tokens = new StringTokenizer(line, " ");// here the delimiter is <space> bt it can be changed to <\n>,<\t>,<\r> etc depending on problem statement
lineNumber++;
long Count_of_words_in_line;
Count_of_words_in_line = 0;
while(tokens.hasMoreTokens())
{
List<File_meta_Data> temp = new ArrayList<File_meta_Data>();
String word = tokens.nextToken();
File_meta_Data metadata = new File_meta_Data();
Count_of_words_in_document++; // contains the word number in the document
Count_of_words_in_line++; // contains the word number in line. used for scoring
metadata.FileName = filename.get(count).toString();
metadata.lineNumber = lineNumber;
metadata.Position_In_Document = Count_of_words_in_document;
metadata.Position_In_Line = Count_of_words_in_line;
int occurence;
occurence=0;
if(index.containsKey(word)) //if the word has occured already then update the new entry which concatenates the older and new entries
{
Map temp7 = new HashMap();
temp7 = (Map) index.get(word);
if(temp7.containsKey(metadata.FileName)) // entry of child Map is changed
{
List<File_meta_Data> temp8 = new ArrayList<File_meta_Data>();
temp8 = (List<File_meta_Data>)temp7.get(metadata.FileName); //outputs fioles which contain the word along with its location
temp7.remove(metadata.FileName);
temp8.add(metadata);
temp7.put(metadata.FileName, temp8); // updated entry is added
}
else // if the word has occured for the first time and no entry is in the hashMap
{
temp.add(metadata);
temp7.put(metadata.FileName, temp);
temp=null;
}
Map temp9 = new HashMap();
temp9 = (Map) index.get(word);
index.remove(word);
temp9.putAll(temp7);
index.put(word, temp9);
}
else // similarly is done for parent map also
{
Map temp6 = new HashMap();
temp.add(metadata);
temp6.put(metadata.FileName, temp);
index.put(word,temp6);
}
}
line = reader.readLine();
}
index.put("#words_in_file:"+(String)filename.get(count),Count_of_words_in_document);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return(index);
}
static String search(Map index,List filename) throws IOException //scores each resource file by comparing with each word in input file
{
double[] overlap = new double[filename.size()]; //stores overlap/coord scores
double[] sigma = new double[filename.size()]; // stores ∑t in q ( tf(t in d) · idf(t)^2 for each resource file
int i;
double max, maxid; // stores file info with max score
max=0;
maxid= -1;
for(i=0;i<filename.size();i++)
{
overlap[i] = 0;
sigma[i] = 0;
}
String bestfile = new String();
double maxscore;
maxscore = -1;
double total;
double cord;
total=0;
File File_to_be_matched = new File(getfile());
BufferedReader reader = new BufferedReader(new FileReader(File_to_be_matched));
String line = reader.readLine();
while(line!=null) //similar to index function
{
StringTokenizer tokens = new StringTokenizer(line, " ");
while(tokens.hasMoreTokens())
{
String word = tokens.nextToken();
double tf,idf;
tf = 0;
idf = 0;
total=total+1;
if(index.containsKey(word))
{
Map temp = new HashMap();
for(i=0;i<filename.size();i++) // for each file a score is calculated for corresponding word which afterwards added
{
int j,count,docFreq;
count=0;
docFreq=0;
temp = (Map) index.get(word);
if(temp.containsKey(filename.get(i)))
{
List l2= (List) temp.get(filename.get(i));
tf = (int) Math.pow((long) l2.size(),0.5); //calculate the term frequency
docFreq = temp.size(); // tells in how many files the word occurs in the file
overlap[i]++;
}
else
{
tf=0;
}
idf = (int) (1 + Math.log((long)(filename.size())/(1+docFreq)));// more the occurence higher similarity of file
sigma[i] = sigma[i] + (int)(Math.pow((long)idf,2) * tf);
}
}
}
line = reader.readLine();
}
double subsetRatio;
for(i=0;i<filename.size();i++) // all scores are added
{
int x = (int)index.get("#words_in_file:"+(String)filename.get(i));
subsetRatio = overlap[i]/x;
overlap[i] = overlap[i]/total;
overlap[i] = overlap[i] * sigma[i];
overlap[i] = overlap[i] * subsetRatio; // files which are subset of some have higher priority
if(max<overlap[i]) // maximum score is calculated
{
max=overlap[i];
maxid = i;
}
}
if(maxid!=-1)
return (String) (filename.get((int) maxid));
else
return("error: Matching does not took place");
}
public static void main(String[] args) throws IOException
{
List filename = new ArrayList();
int Number_of_input_files = getNumberofInputFiles();
filename = getFiles(Number_of_input_files);
Map index = new HashMap();
index = MakeIndex(filename);
//match(index);
while(1==1) //infinite loop
{
String Most_similar_file = search(index,filename);
System.out.println("the most similar file is : "+Most_similar_file);
}
}
}
The problem is to find the most similar file among several resource files.
there are 2 sub-problems to this question
first, as the question states, how to find the most similar file which is done by associating each file with a score by considering different aspects of the content of files
second, to parse each and every word of the input file with a comparatively large resource files
to solve the second problem, Reverse Indexing has been used with HashMaps in java. Since our problem was simple and not modifying i used Inherited Maps instead of Comparator based MapReduce
while searching computing complexity = o(RESOURCEFILES * TOTAL_WORDS_IN _INPUTFILE)
the first problem has been solved by following formula
score(q,d) = coord(q,d) • ∑t in q ( tf(t in d) • idf(t)^2) . subsetRatio
1) coord(q,d) = overlap / maxOverlap
Implication: of the terms in the query, a document that contains more terms will have a higher score
Rational : Score factor based on how many of the query terms are found in the specified document
2) tf(t in d) = sqrt(freq)
Term frequency factor for the term (t) in the document (d).
Implication: the more frequent a term occurs in a document, the greater its score
Rationale: documents which contains more of a term are generally more relevant
3) idf(t) = log(numDocs/(docFreq+1)) + 1 I
implication: the greater the occurrence of a term in different documents, the lower its score
Rational : common terms are less important than uncommon ones
4) SubsetRation = number of occuring words / total words
implication : suppose 2 files, both superlative of input file then file with lesser excessive data will have hiegher similarity
Rational : files with similar content must have higher priority
****************test cases************************
1) input file has no similar word than the resource files
2) input file is similar in content to any one of the file
3) input file is similar in content but different in metadata(meaning position of words is not similar)
4) input file is a subset of resource files
5) input file contains very common words like all 'a' or 'and'
6) input file is not at the location
7) input file cannot be read
Look into opening files, reading them as characters. You actually just need to get a char from each, then check if they match. If they match, then increment the total counter and the match counter. If they don't, only the total counter.
Read more on handling files and streams here: http://docs.oracle.com/javase/tutorial/essential/io/charstreams.html
An example would be this:
BufferedReader br1 = null;
BufferedReader br2 = null;
try
{
br1 = new BufferedReader(new InputStreamReader(new FileInputStream(new File("a.txt")), "UTF-8"));
br2 = new BufferedReader(new InputStreamReader(new FileInputStream(new File("b.txt")), "UTF-8"));
//add logic here
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (br1 != null)
{
try
{
br1.close();
}
catch (Exception e)
{
}
}
if (br2 != null)
{
try
{
br2.close();
}
catch (Exception e)
{
}
}
}

Trying to implement a score system while using if/else. [JAVA]

I'm a beginner at java and I'm trying to have a score system that uses my if/else statements to either increment or decrement according to right or wrong answers. The program should increment if the user matches the text that is found in the text file and decrement if incorrect. Right now, the program will display "-1" if incorrect and "1" if correct, regardless of how many times it goes through the loop. It should change the value of result but it keeps resetting to "0". I have tried already but I believe I had an issue with scope. If anyone could help I'd be very grateful.
package typetrain;
import java.util.*;
import java.io.*;
import javax.swing.*;
/**
*
* #author Haf
*/
public class Game1 {
public void Game () {
JOptionPane.showMessageDialog(null, "Please answer in the correct line of text. \n" +
"each line of text will grant you one point. "
+ "\nIncorrect answers will lead to a point being subtracted");
String fileName = "test.txt";
String line;
ArrayList aList = new ArrayList();
try {
BufferedReader input = new BufferedReader (new FileReader(fileName));
if (!input.ready()) {
throw new IOException();
}
while ((line = input.readLine()) !=null) {
aList.add(line);
}
input.close();
} catch (IOException e) {
System.out.println(e);
}
int sz = aList.size();
for (int i = 0; i< sz; i++) {
int result = 0;
String correctAnswer = aList.get(i).toString();
String userAnswer = JOptionPane.showInputDialog(null, "Copy this line of text! \n" + aList.get(i).toString());
if (correctAnswer.equals(userAnswer)) {
JOptionPane.showMessageDialog(null, "Correct!");
result++;
}
else if (!correctAnswer.equals(userAnswer)) {
JOptionPane.showMessageDialog(null, "Incorrect!");
result--;
}
JOptionPane.showMessageDialog(null, result);
}
}
}
You just need to move your int result = 0; to the line before your for loop. Otherwise, it will get reset to 0 each time.

How do I read each column of a txt file, and place them in separate arrays?

I'm doing a Programming Assignment and basically I need to read from a txt file and sort everything in there in different arrays allowing me to display everything in the cmd prompt neatly and be able to delete stuff.
h Vito 123
d Michael 234 Heart
s Vincent 345 Brain Y
n Sonny 456 6
a Luca 567 Business
r Tom 678 Talking Y
j Anthony 789 Maintenance N
d Nicos 891 Bone
n Vicky 911 7
First column needs to be the employeeRole (employee, doctor). The second column being the employeeName. Third column being the employeeNumber and some of them have have a fourth column (if it's a number it's number of patients. Y is for like sweeping, or answering calls)
So my thought process was put each column into it's own array and then writing it out that way. I was able to put each row into its own array with
public class ReadingFile {
// String test;
// char[] employeeRole = new char[9];
String[] employeeRole = new String[9];
String[] employeeName = new String[9], specialty;
String[] wholeLine = new String[9];
// String word;
int[] employeeNum = new int[9];
int r, n, l, num;
public void Reader()
{
Scanner inputStream = null;
Scanner inputStream2 = null;
Scanner inputStream4 = null;
try
{
BufferedReader inputStream3 =
new BufferedReader(new FileReader("data.txt"));
inputStream = new Scanner(new FileInputStream("data.txt"));
inputStream =
new Scanner(new FileInputStream("data.txt"));
inputStream2 =
new Scanner(new FileInputStream("data.txt"));
inputStream4 =
new Scanner(new FileInputStream("data.txt"));
System.out.println("Yeah");
}
catch(FileNotFoundException e){
System.out.println("File Not found");
System.exit(1);
}
for (l=0; l<9; l++)
{
wholeLine[l] = inputStream2.nextLine();
System.out.println(wholeLine[l]);
}
But I couldn't figure out what to do from there. Doing a split would then put an array into an array? Which means I would put each line into an array and then each word into an array?
So I tried something else, anything with the length not equal to 1 would be the employeeNum, but then they there were the N's and Y's and the number of pateints.
for(r=0; r<9; r++) //role
{
String next = inputStream4.next();
while( next.length() != 1)
{
next = inputStream4.next();
}
employeeRole[r] = next;
System.out.println(employeeRole[r]);
}
I also tried
for (r=0; r<9; r++)
{
employeeRole[r] = wholeLine[r].substring(wholeLine[r].indexOf(1));
//inputStream.nextLine();
System.out.println(employeeRole[r]);
}
I'm just not sure if I'm going the right way about it? If I'm making it more difficult than it really is? Or if there's an easier way to do this. But after everything is done, the output should be able to basically say
Doctors: 2
Name: Michael Employee Number: 234 Specialty: Heart
Name: Nicos Employee Number: 891 Specialty: Bone
Any help would be greatly appreciated, thanks!
You don't have to open 4 streams in order to read the file (I guess you wanted to open "one per column" but you shouldn't do it).
Second, you can split the string on spaces (" ") which will provide you the columns (for every line separately) exactly like you want.
Code example:
BufferedReader br = null;
String[] characters = new String[1024];//just an example - you have to initialize it to be big enough to hold all the lines!
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("data.txt"));
int i=0;
while ((sCurrentLine = br.readLine()) != null) {
String[] arr = sCurrentLine.split(" ");
//for the first line it'll print
System.out.println("arr[0] = " + arr[0]); // h
System.out.println("arr[1] = " + arr[1]); // Vito
System.out.println("arr[2] = " + arr[2]); // 123
if(arr.length == 4){
System.out.println("arr[3] = " + arr[3]);
}
//Now if you want to enter them into separate arrays
characters[i] = arr[0];
// and you can do the same with
// names[1] = arr[1]
//etc
i++;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}

Categories