i am here with another problem in my code since i am new to java. my task is to read a text file that contains some 300 records and record has 13 fields . i am trying to calculate the sum of each field for example, if age is my first field them sum of the age of all 300 people and then store it in an array index.
import java.io.*;
import java.util.Vector;
public class Mean
{
private static Vector contents;
private static BufferedReader br;
private static FileInputStream inputstream;
private static FileOutputStream outputstream;
public Mean()
{
contents = new Vector();
}
public void doDuplicationRemoval(String filename)
{
try{
inputstream = new FileInputStream(filename);
br = new BufferedReader(new InputStreamReader(inputstream));
String string = "";
while((string = br.readLine())!= null)
{
String[] split = string.split(",");
Vector vector = new Vector();
for(int i=0; i<split.length; i++)
vector.add(split[i].trim());
if(!vector.contains("?"))
{
contents.add(split);
}
}
}
catch(Exception err){
System.out.println(err);
}
}
public void doDataConv(String filename)
{
DataConversion.readFile(contents);
DataConversion.writeFile(filename);
}
public static void doDataConversion(Vector contents)
{
DataConversion.readFile(contents);
for(int i=0; i<contents.size(); i++)
{
String string = "";
String[] split = (String[])contents.get(i);
split[0] += getAge(split[0]);
System.out.println(split[0]);
}
}
private static String getAge(String src)
{
String age = src;
return age;
}
public static void main(String [] args) {
Mean dr;
dr = new Mean();
dr.doDuplicationRemoval("input.txt");
dr.doDataConv("inp_out.txt");
dr.doDataConversion(contents);
}
}
the input is
63
67
50
my aim is to get output as 180
but am getting
6363
6767
5050
can someone help me to fix the problem.
This looks like the first problem to me:
private static String getAge(String src)
{
String age = src;
return age;
}
You're treating the age as a string. If you want to treat it as a number, you should be parsing it (e.g. with Integer.parseInt).
Here's the second problem:
String string = "";
String[] split = (String[])contents.get(i);
split[0] += getAge(split[0]);
System.out.println(split[0]);
That's only ever changing the value of split[0], which is then overwritten when you reassign it in the next iteration. You need something like:
int sum = 0;
for(int i=0; i<contents.size(); i++)
{
String[] split = (String[])contents.get(i);
sum += getAge(split[0]); // After changing getAge to return an int
}
System.out.println(sum);
Your not adding numbers but concatenating Strings:
split[0] += getAge(split[0]);
To sum up the values (e.g. the numeric content of your first column fields)
Define a local variable, like int sum = 0; outside the loop
parse the values from the Strings (Integer.parseInt(split[0])) and
add every parsed value to sum.
The problem is you line
split[0] += getAge(split[0]);
As the type of your split table is String, it will concatenate the values. You need a result table, like:
int[] result = new int[];
And then:
result[0] += getAge(split[0]);
I will try to formulate a good design for your purpose:
Create a class with the structure of a record. Let's name it Record
Instanciate a Record object with each line you read
Put in a Record table
You can create another Record with all the sums
Don't use Vector. If you need a list, use ArrayList (except in a multithreaded context). Vector is just a legacy class from before Java 2. It's obsolete.
your actual error is here as you are using + to add two string which contains integer
split[0] += getAge(split[0]);//here split[0] is String 63, getAge(split[0])
//retuns also String 63 hence addition gives "63" + "63" = "6363"
doing string addition that is concatenation
Integer.parseInt()
so make conversion as follow:
split[0] = new Integer (Integer.parseInt(split[0]) +
Integer.parseInt( getAge(split[0]))).toString()
if you want to store values in integer array then make another array of integer to store values.
if you want to store result in int array then do as follow:
int agesum[] = new int[]
agesum[0] += Integer.parseInt( getAge(split[0]));
Related
I want to design a code that can read a file that looks like this:
Jake 12.00 13.24 6
Sarah 11.23 24.01 8
Alex 10.65 19.45 4
I need to make separate arrays for the Strings, the first float, the second float, and the int.
How do I go about doing this?
This is what I have so far: I'm not sure how to make separate arrays for the two floats. I also keep getting an exception IndexOutOfBoundsException: 0 at EmployeePay.main..
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);
}
final String inputFileName = args[0];
final File input = new File (inputFileName);
final Scanner scanner = new Scanner(new BufferedReader(new FileReader(input)));
String Id = "Employee Id:";
String Hours = "Hours worked:";
String WageRate = "Wage Rate:";
String Deductions = "Deductions:";
System.out.printf("%s %-10s %-20s %-30s", Id, Hours, WageRate, Deductions);
int lineNumber = 0;
while (scanner.hasNextLine()){
lineNumber =lineNumber +1;
String [] Identification= new String [lineNumber-1];
int [] TotalDeductions = new int [lineNumber-1];
float [] WorkTime = new float[lineNumber-1];
if(scanner.hasNextInt()){
TotalDeductions[lineNumber-1] = scanner.nextInt();
System.out.println(TotalDeductions[lineNumber-1]);
}
else if (scanner.hasNextFloat()){
WorkTime[lineNumber-1]= scanner.nextFloat();
}
else {
Identification[lineNumber-1] = scanner.next();
System.out.println(Identification[lineNumber-1]);
}
}
}
}
I will assume your String value doesn't contain space. This is kind of pseudo code, Try yourself and explore each line why I did so:
String s[] = new String[size];
float f1[] = new float[size];
float f2[] = new float[size];
for(int i=0; i<numberOfLines;i++) {
String x = "Jake 12.00 13.24 6";
String[] arr = x.split(" ");
s[i] = arr[0];
f1[i] = Float.valueOf(arr[1]);
f2[i] = Float.valueOf(arr[2]);
}
This error exception IndexOutOfBoundsException: 0 at EmployeePay.main. is occuring due to this statement if (args.length != 1).
It should be if(args.length!=0)
If no arguements are passed at command prompt then args.length is 0. So, this statement will throw an exception final String inputFileName = args[0];
Thus, you need to check for args.length
If your data file is indeed as you show in your post with blank lines between the data lines then you will need to take care of those as well while reading the file and processing the information obtained. You obviously want to skip past those particular lines. If this isn't the case then it only goes to show you how important it is to provide full and accurate information when asking a question here. No one here wants to really assume anything.
When creating arrays it's always nice to know how big an array needs to be beforehand so that you can properly initialize it to its required size. This is where List or ArrayList is better, you can just add to them when needed. Never the less, to properly initialize all your different arrays (String[], float[], float[], and int[]) you need to know how many valid data line are contained within your data file. By valid data lines I mean lines that actually contain data, not blank lines. So the first natural step would be to count those lines. Once you have the count then you can initialize all your arrays to that line count.
Now all you need to do is re-read the file data line by line, split each line to acquire the data segments , then convert each numerical segment to its respective Array data type. Once you have all your arrays filled from the file you can then do whatever you like with the data contained within those arrays. The code to carry out this task might look something like this:
String inputFileName = "MyDataFile.txt";
Scanner scanner;
int linesCount = 0;
try {
// Count the total number of valid data lines
// within the file (blank line are skipped).
scanner = new Scanner(new File(inputFileName));
while (scanner.hasNextLine()) {
String strg = scanner.nextLine().trim();
if (!strg.equals("")) { linesCount++; }
}
// Declare our different Arrays and size them to
// the valid number of data lines in file.
String[] employeeID = new String[linesCount];
float[] hours = new float[linesCount];
float[] wageRate = new float[linesCount];
int[] deductions = new int[linesCount];
// Read through the file again and place the data
// into their respective arrays.
scanner = new Scanner(new File(inputFileName));
int counter = 0;
while (scanner.hasNextLine()){
// Get the next line in file...
String strg = scanner.nextLine().trim();
// If the file line is blank then skip it.
if (strg.equals("")) { continue; }
// otherwise split the line by its space
// delimiter ("\\s+" takes care of 1 OR more
// spaces just in case).
String[] values = strg.split("\\s+");
// Add to the employeeID string array.
employeeID[counter] = values[0];
// Control what is placed into the elements of each
// float or integer array. If there is no value data
// supplied in file for the employee Name then make
// sure 0.0 (for floats) or 0 (for integers) is placed
// there after all, you can't parse a null string ("").
if (values.length >= 2) { hours[counter] = Float.parseFloat(values[1]); }
else { hours[counter] = 0.0f; }
if (values.length >= 3) { wageRate[counter] = Float.parseFloat(values[2]); }
else { wageRate[counter] = 0.0f; }
if (values.length == 4) { deductions[counter] = Integer.parseInt(values[3]); }
else { deductions[counter] = 0; }
counter++;
}
scanner.close();
// Now that you have all your arrays you can
// do whatever you like with the data contained
// within them:
String Id = "Employee Id:";
String Hours = "Hours worked:";
String WageRate = "Wage Rate:";
String Deductions = "Deductions:";
System.out.printf("%-15s %-15s %-15s %-15s%n", Id, Hours, WageRate, Deductions);
for (int i = 0; i < employeeID.length; i++) {
System.out.printf("%-15s %-15s %-15s %-15s%n", employeeID[i], hours[i], wageRate[i], deductions[i]);
}
}
catch (FileNotFoundException ex) { ex.printStackTrace(); }
This is a bit of a tricky and long question, so please bear with me.
I have a finite number of lines in an input file of the form:
2015000,Advanced YouTube Commenting,Department of Comp Sci,3
2015001,Basket Weaving,Department of Fine Arts,1,, etc...
The main method sets the constructor:
FileUtil fUtil1 = new FileUtil("input.txt",1,"output1.txt");
The "input.txt" is the file it's getting these lines from, and "ouput1.txt" is the file where these lines will be written on.
The number "1" tells me if
I want to either arrange these lines by their crns (represented by 0), their names (1), their departments (2), or their year (3).
So the hard part is, I don't just have to arrange these lines in ascending order, but I have to arrange their ELEMENTS in ascending order.
My question is; is there a more efficient way to do this than what I currently have? We haven't learned how to tokenize ArrayLists yet, but perhaps that's a much better way to do this.
This is what I have so far:
private ArrayList<String> memFile; // sorted lines from input file
private int column;
....
public void sort(){
BufferedReader inFile;
String readLine;
// I read in each line of the text file and add it to the `ArrayList<String> memFile`
try{
inFile = new BufferedReader(new FileReader(inputFile));
while((readLine = inFile.readLine()) != null){
memFile.add(readLine);
insertSorted(readLine);
}//while
inFile.close();
}//try
catch(IOException e){
System.out.println(e.getMessage());
}//catch
}//sort
private void insertSorted(String line){
// I tokenize the given line to get each element
String[] tokens = line.trim().split(",");
int registration = Integer.parseInt(tokens[0]); //crn number
String title = tokens[1]; // course name
String department = tokens[2]; // course department
int year = Integer.parseInt(tokens[3]); // course year
String word = "";
//I look at the lines already in the list, and then tokenize them
int index = memFile.size() - 1;
String otherLine = memFile.get(index);
String[] tokens2 = otherLine.trim().split(",");
int registration2 = Integer.parseInt(tokens2[0]); //crn number
String title2 = tokens2[1]; // course name
String department2 = tokens2[2]; // course department
int year2 = Integer.parseInt(tokens2[3]); // course year
String otherWord = "";
// if the given column equals the token position in the line, then make a new word
for(int i = 0; i < tokens.length; i++){
if(column == i){
word = (String)tokens[i];
otherWord = (String)tokens2[i];}
else{
word = null;}
}
//sort the list
while(index >= 0 && (otherWord).compareTo(word) > 0)
index--;
memFile.add(index+1,line);
}//insertSorted
A better way to do this (especially given that you're in Java) is to create a class to represent the data, rather than trying to work with strings all the way through. Consider the class:
public class Data{
public final int crns;
public final String name;
public final String department;
public final int year;
public Data(int crns, String name, String department, int year){
this.crns = crns;
this.name = name;
this.department = department;
this.year = year;
}
public String toString(){
return crns + "," + name + "," + department + "," + year;
}
}
Then you can simply convert each line to a Data as you read it in, perform operations on the ArrayList of Data, and convert them back to strings afterwards.
private ArrayList<Data> memFile;
private int column;
....
public void sort(){
memFile.clear(); //Make sure that calling sort twice doesn't break it
BufferedReader inFile;
String readLine;
try{
inFile = new BufferedReader(new FileReader(inputFile));
while((readLine = inFile.readLine()) != null){
try{
//Read and split the next line
String[] tokens = readLine.trim().split(",");
int registration = Integer.parseInt(tokens[0]); //crn number
String title = tokens[1]; // course name
String department = tokens[2]; // course department
int year = Integer.parseInt(tokens[3]); // course year
//Convert to a data instance and add to the arrayList
memFile.add(new Data(registration, title, department, year));
}catch(NumberFormatException e){
System.err.println("Found badly formatted line: " + readLine);
}
}
inFile.close();
//Sort according to the correct field
Collections.sort(memFile, new Comparator<Data>(){
public int compare(Data d1, Data d2){
switch(column){
case 0: return d1.crns - d2.crns;
case 1: return d1.name.compareTo(d2.name);
case 2: return d1.department.compareTo(d2.department);
case 3: return d1.year - d2.year;
default: return 0;
}
}
});
}
catch(IOException e){
System.out.println(e.getMessage());
}
}
If you're doing this for learning, then you should expand upon this by making the Data class better. Such as:
Add a constructor public Data(String line) that does the parsing to fields internally, throwing exceptions when needed. Then you can just pass the read line into the constructor
Add equals and hashcode methods that work for the Data class. Hint - use Objects.equals and Objects.hashcode for easy implementations.
Try TreeMap
TreeMap<String, String> treemap = new TreeMap<>();
private void insertSortedOn(String line, int fieldIndex){
String[] tokens = line.trim().split(",");
treemap.put(tokens[fieldIndex], line);
}
You could actually keep a different TreeMap for every "element". It sorts based on whatever you use as the key. Since your elements are always 4 you could have 4 TreeMaps using exactly the right types for each key. Since they only hold references there wont be much memory duplication.
I am "attempting" to make a method that will take my string array and compare it to an answer key that I have imported from a data file. Every time I compile I get this incompatible data type error and it is saying that:
Found: java.lang.String
Required: java.lang.String[][]
Am I not doing that?
I have had no luck searching for a solution on here and on Google. They seem to be irrelevant to what I am trying to accomplish.
import java.util.*; // Allows for the input of a scanner method.
import java.io.*; // Allows for the inputting and outputting of a data file.
import java.lang.*; // Allows for the use of String Methods.
//////////////////////////////////////////////////////////////////////////////////////
public class TESTY
{
static Scanner testanswers;
static PrintWriter testresults;
public static void main(String[] args) throws IOException
{
testanswers = new Scanner(new FileReader("TestInput.dat"));
testresults = new PrintWriter("TestOutput.dat");
String StudentID;
String answers;
// Reads first two lines first to know how many records there are.
String answerKey = testanswers.nextLine();
int count = Integer.parseInt(testanswers.nextLine());
// Allocate the array for the size needed.
String[][] answerArray = new String[count][];
for (int i = 0; i < count; i++)
{
String line = testanswers.nextLine();
answerArray[i] = line.split(" ", 2);
}
for(int row = 0; row < answerArray.length; row++)
{
for(int col = 0; col < answerArray[row].length; col++)
{
System.out.print(answerArray[row][col] + " ");
}
System.out.println();
}
gradeData(answerArray, answerKey);
testanswers.close();
testresults.close();
}
///////////////////////////////////////////////////////////
//Method: gradeData
//Description: This method will grade testanswers showing
//what was missed, skipped, letter grade, and percentage.
///////////////////////////////////////////////////////////
public static double gradeData(String[][] answerArray, String answerKey)
{
String key;
double Points = 0;
StringBuilder[] wrongAnswers = new StringBuilder[answerArray.length];
for(int rowIndex = 0; rowIndex < answerArray.length; rowIndex++)
{
String studAnswers[][] = answerArray[rowIndex][1].replace(" ", "S");
for(int charIndex = 0; charIndex < studAnswers[rowIndex][1].length; charIndex++)
{
if(studAnswers[rowIndex][1].charAt(charIndex).equals(key.charAt(charIndex)))
{
Points += 2;
}
if(!studAnswers[rowIndex][1].charAt(charIndex).equals('S'))
{
Points --;
}
else
{
wrongAnswers.setcharAt(charIndex, 'X');
}
}
}
return Points;
}
To get a better idea of what I am doing here is my .dat file:
TFFTFFTTTTFFTFTFTFTT
5
ABC54301 TFTFTFTT TFTFTFFTTFT
SJU12874 TTTFFTFFFTFTFFTTFTTF
KSPWFG47 FT FT FTFTFFTTFFTF
PAR38501 FFFFFFFFFFFFFFFFFFFF
MCY19507 TTTT TTTT TTTT TT TT
This statement, for instance,
String studAnswers[][] = answerArray[rowIndex][1].replace(" ", "S");
gives the compilation error
Type mismatch: cannot convert from String to String[][]
because
answerArray[rowIndex][1].replace(" ", "S"); returns a String.
answerArray is a 2D String array.
answerArray[rowIndex][1] gets
a element from the array which is a string
answerArray[rowIndex][1].replace... replaces a character in that
String with another character, ending up as another String (with
the replaced character)
You are trying to assign it to a String array.
Also, you cannot use equals on primitives (int, char...). You need to use == for comparison.
String studAnswers[][] = answerArray[rowIndex][1].replace(" ", "S");
Here, studAnswers is declared as an array of arrays of Strings, and you initialize it with a String. Indeed, answerArray is an array of arrays of Strings, and answerArray[rowIndex][1] is thus a String. And you replace every white space in this String by an S, which returns another String.
That doesn't make sense.
I am trying to get the last element from the end of each line of my ArrayList/array.
For example i have these records int my list: (don't mind the language, Greek names)
Nikos Pappas : 321/2012999, C,8.53
Marios Athanasiou : 321/2012001, A,6.89
Stavroula Markou : 321/2011001, D,7.00
Giannis Kallogirou : 321/2009005, ST, 6.89
Nikoletta Stefanou : 321/2010001, D, 7.25
Stathis Petrou : 321/2011002, E, 8.10
Kostas Tzovalis : 321/2007667, C, 5.00
Michalis Kotsis : 321/2009723, D, 7.12
Maria Katsanou : 321/2012002, C, 5.50
And I want to take: 8.53, 6.89,....,5.50 (marks of students)
This is what I've made so far (the file is the file which contains the above info)
public static void main(String[] args) {
BufferedReader br = null;
ArrayList <String> list = new ArrayList <> ();
try
{
br = new BufferedReader(new FileReader("C:/Users/Stefi/Desktop/java_ask3.txt"));
String str;
//System.out.print("mpika");
while((str = br.readLine()) != null)
{
list.add(str);
System.out.println(str);
}
}
catch(IOException e)
{
System.out.println("Κάτι πήγε στραβά! Προσπάθησε πάλι.");
}
finally
{
try
{
if (br != null)
{
br.close();
}
}
catch(IOException e2)
{
System.out.println("Δεν μπορεσα να κλείσω το αρχείο.");
}
}
int x = list.size();
String [] array = new String[x];
array = list.toArray(array);
for(int i=0; i<array.length; i++)
{
System.out.println(array[i]);
}
String [] f = new String[list.size()];
String vathmos;
for(int i=0; i<array.length; i++)
{
vathmos = list.get(i).replaceAll("\\D+", "");
f[i] = vathmos;
}
System.out.println("\n\n\n Float Print\n");
for(int i=0; i<array.length; i++)
{
System.out.println(f[i]);
}
}
this is an example of my output:
3212012999853
3212012001689
3212011001700
3212009005689
It takes all the numbers it finds. But I don't know how to take only the last float number.
I know it's totally wrong to work like this, and work like this because I'll never get the float i want.
I also tried to convert my list into array and take the last element but didn't work out.
You can try this
String s = line.replaceAll(".*(\\d+\\.\\d+)$", "$1");
Split the line by a comma then get the last element of the resulting array
String[] splitArr = line.split(",");
String lastNumber = splitArr[splitArr.length - 1];
But best solution would be to have a Student class as suggested in comments
If you store your records as Strings, you can use the substring method:
grade = Double.parseDouble(array[i].substring(array[i].length() - 3)); if you are sure the grade is always in x.xx form at the end of each String.
Also consider creating a class that would contain all the information about students in seperate fields, for example:
public class Student{
public String name;
public String surname;
public int age;
public double grade;
}
Of course this is just an example, you may hide implementation and provide methods you want as well. Then you could create any kind of collection of Student objects, so getting the specified value of any field for any student would be easy.
I can suggest couple String functions to add to your code. This is not tested code though -
Using String.split();
//This will hold all the numbers as String
List<String> masterList = new ArrayList<String>();
while((str = br.readLine()) != null)
{
String [] lineValues = String.split(",");
int countElements = lineValues.Length();
masterList.Add(lineValues[countElements - 1]);
}
Using lastIndexOf();
//This will hold all the numbers as String
List<String> masterList = new ArrayList<String>();
while((str = br.readLine()) != null)
{
int lastIndex = str.lastIndexOf(",");
masterList.Add(str.substring(lastIndex, str.length() - 1));
}
Once you have the masterList populated, you can loop through it and extract the float using
Float.valueOf(masterList.get(i));
Right now I want to store a text file that goes like this:
1 apple
2 banana
3 orange
4 lynx
5 cappuccino
and so on into a data structure. Would the best way of doing this be mapping the int to the string somehow, or should I make an arraylist? I'm supposed to, when I store the words themselves, disregard the int and any whitespace, and keep only the word itself. How do I disregard the int when reading in lines? Here is my hacked together code right now:
public Dictionary(String filename) throws IOException {
if (filename==null)
throw new IllegalArgumentException("Null filename");
else{
try {
BufferedReader in = new BufferedReader(new FileReader(filename));
String str;
int numLines=0;
while ((str = in.readLine()) != null) {
numLines++;
}
String[] words=new String[numLines];
for (int i=0; i<words.length;i++){
words[i]=in.readLine();
}
in.close();
} catch (IOException e) {
}
}
}
Thank you in advance for the help!!
Just implement the power of the regular expression:
List texts<String> = new ArrayList<String>();
Pattern pattern = Pattern.compile("[^0-9\\s]+");
String text = "1 apple 2 oranges 3 carrots";
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
texts.add(matcher.group(0));
}
regular expressions are very much popular these days. the compile method is used for compiling your search pattern, with the numbers you see in the parameter is to prevent getting them on your search. So it's completely safe. use apache's IOUtilities to convert a text file to String
This won´t work because you are already at the end of the file, so the in.readLine() methode will return null.
I would use a Map to store the name and the amount...something like this:
HashMap<String, Integer> map = new HashMap<String, Integer>();
while( (line = br.readLine() !=null){
//also check if the array is null and the right size, trim, etc.
String[] tmp = line.split(" ");
map.put(tmp[1], Integer.parseInt(tmp[0]) );
}
Otherwise you can try it with the Scanner class. Good luck.
You can give regular expressions a try.
Pattern p = Pattern.compile("[^0-9\\s]+");
String s = "1 apple 2 oranges";
Matcher m = p.matcher(s);
while (m.find()) {
System.out.println(m.group(0));
}
Output =
apple
oranges
To get a idea about regular expressions Java regex tutorial.
I suggest you use a List of items to store the results parsed from the file. One way to parse every text line is to use the String.split(String) method. Also note that you should handle exceptions in the code properly and do not forget to close the Reader when you are done (no matter whether flawlessly or with an exception => use a finally block). The following example should put you on track... Hope this helps.
package test;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
Main m = new Main();
m.start("test.txt");
}
private void start(String filename) throws IOException {
System.out.println(readFromFile(filename));
}
private final class Item {
private String name;
private int id;
public Item(String name, int id) {
this.name = name;
this.id = id;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
#Override
public String toString() {
return "Item [name=" + name + ", id=" + id + "]";
}
}
private List<Item> readFromFile(String filename) throws IOException {
List<Item> items = new ArrayList<Item>();
Reader r = null;
try {
r = new FileReader(filename);
BufferedReader br = new BufferedReader(r);
String line = null;
while ((line = br.readLine()) != null) {
String[] lineItems = line.split(" ");
if (lineItems.length != 2) {
throw new IOException("Incorrect input file data format! Two space separated items expected on every line!");
}
try {
int id = Integer.parseInt(lineItems[0]);
Item i = new Item(lineItems[1], id);
items.add(i);
} catch (NumberFormatException ex) {
throw new IOException("Incorrect input file data format!", ex); // JDK6+
}
}
} finally {
if (r != null) {
r.close();
}
}
return items;
}
}
If your words don't contain spaces, you could use String.split( " " ) to split up the String into an array of Strings delimited by spaces.
Then just take the second element of the array (the first will be the number).
Also, the String.trim( ) method will remove any whitespace before or after the String.
Note: there's probably some error checking that you'd want to perform (what if the String isn't formatted as you expect). But this code snippet gives the basic idea:
...
String s = in.readLine( );
String[] tokens = s.split( " " );
words[i] = tokens[1].trim( );
...
If you want to do something easy just substring the original work by counting digits:
int t = 0;
while (word.charAt(t) >= '0' && word.charAt(t) <= '9')
++t;
word = word.substring(t);
If words NEVER contain spaces you can also use word.split(" ")[1]
Instead of using a buffer reader use the Scanner class and instead of using an Array use an ArrayList, like so :
import java.util.Scanner;
import java.util.ArrayList;
public class Dictionary {
private ArrayList strings = new ArrayList();
code...
public Dictionary(String fileName) throws IOException {
code...
try {
Scanner inFile = new Scanner(new fileRead(fileName));
ArrayList.add("Dummy"); // Dummy value to make the index start at 1
while(inFile.hasNext()) {
int n = inFile.nextInt(); // this line just reads in the int from the file and
// doesn't do anything with it
String s = inFile.nextLine().trim();
strings.add(s);
}
inFile.close(); // don't forget to close the file
}
and then since your data goes 1, 2, 3, 4, 5, you can just use the index to retrieve each item's number.
By doing this:
for(int i = 1; i < strings.size(); i++) {
int n = i;
String s = n + " " + strings.get(i);
System.out.println(s);
}