Input file with names and popularity Java - java

So I have a file that has names along with 11 popularity ranks which looks like this. <--- (this is a link) I am a bit confused on what I am suppose to do with this next part that I have for my assignment. Generally I have a name app that looks like this:
public class Name{
private String givenName;
private int[] ranks = new int[11];
public Name(String name, int[] popularityRanks){
givenName = name;
for (int i = 0; i < 11; i++){
ranks[i] = popularityRanks[i];
}
}
public String getName(){
return givenName;
}
public int getPop(int decade){
if (decade >= 1 && decade <= 11){
return ranks[decade];
}
else{
return -1;
}
}
public String getHistoLine(int decade){
String histoLine = ranks[decade] + ": ";
return histoLine;
}
public String getHistogram(){
String histogram = "";
for (int i = 0; i < 11; i++){
histogram += ranks[i] + ": " + this.getHistoLine(i)
+ "\n";
}
return histogram;
}
}
It is not finished for the getHistoLine but that doesn't have anything to do with what I am trying to do. Generally I want to take these names in from the file and create an array of list.
How he describes it:
Create the array in main, pass it to the readNamesFile method and let that method fill it with Name objects
Test this, by printing out various names and their popularity rankings
For example, if main named the array, list, then upon return from the readNamesFile method do something like:
System.out.println( list[0].getName() + list[0].getPop(1) );
This is what my main looks like:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class NameApp{
public static void main(String[] args){
Name list[] = new Name()
}
private static void loadFile(){
Scanner inputStream = null;
String fileName = "names.txt";
try {
inputStream = new Scanner (new File(fileName));
}
catch (FileNotFoundException e){
System.out.println("Error opening file named: " + fileName);
System.out.println("Exiting...");
}
while (inputStream.hasNext()){
}
}
}
I am just a bit confused how I can take the name have it send to the Name object list[] and then take the popularity ranks and send it to the Name object list[]. So when I call
list[0].getName()
it will just call the name for one of the lines... Sorry I am a bit new to the java language. Thanks in advance

You need to create a Name list correctly. I would use a List since you don't know how many names there will be;
public static void main(String[] args){
List<Name> list = new ArrayList<Name>();
loadFile();
System.out.println(list.get(0).getPop());
}
private static void loadFile(){
Scanner inputStream = null;
String fileName = "names.txt";
try {
inputStream = new Scanner (new File(fileName));
}
catch (FileNotFoundException e){
System.out.println("Error opening file named: " + fileName);
System.out.println("Exiting...");
}
while (inputStream.hasNext()){
// givenName = something
// ranks = something;
list.add(new Name(givenName, ranks);
}
}
Assuming each line is something like this (from your deleted comment)
A 1 234 22 43 543 32 344 32 43
Your while loop can be something like this
while (inputStream.hasNextLIne()){
String line = inputStream.nextLine();
String tokens = line.split("\\s+");
String givenName = tokens[0];
int[] numList = new int[tokens.lenth - 1];
for (int i = 1; i < tokens.length; i++){
numList[i - 1] = Integer.parseInt(tokens[i].trim());
}
list.add(new Name(givenName, numList);
}

Related

Is there any way to store the elements present in the file to the to the array of the object in java

The program is giving correct output when System.out.println(mem[i].memName); but the array of class "member" is giving output (alex alex alex alex) i.e of the last line of the file (mentioned at the END of the CODE)
it should give all the names listed in the file.
import java.io.*;
import java.util.*;
class member//CLASS TO BE USED AS ARRAY TO STORE THE PRE REGISTERED MEMBERS FED INSIDE
{ //THE FILE "member.txt"
static int memId;
static String memName, memEmail, memPh, date;
}
public class entry// file name
{
static DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
static LocalDateTime now = LocalDateTime.now();
static Scanner input = new Scanner(System.in);
static member[] mem = new member[100];
static trainer[] tr = new trainer[100];
static FileWriter fwriter = null;
static BufferedWriter bwriter = null;
static FileReader fread = null;
static BufferedReader bread = null;
static void memberEntry() {
int i = 0;
System.out.println("NEW MEMBER IS BEING ADDED");
try {
fwriter = new FileWriter("C:\\Users\\itisa\\OneDrive\\Desktop\\GYM
PROJECT\\member.txt
",true);
bwriter = new BufferedWriter(fwriter);
System.out.println("Member ID is being automatically genrated");
int autoID = 101 + getMemberRecords();//Fetching the number of members so that ID can
//Be genrated automatically
i = autoID % 100;//jumping toward the next loaction location
System.out.println("Member ID of new member is" + autoID);
mem[i].memId = autoID;
System.out.print("Enter the name of the member:");
mem[i].memName = input.next();
System.out.print("Enter the email address of memeber:");
mem[i].memEmail = input.next();
System.out.print("Enter the contact number of memeber:");
mem[i].memPh = input.next();
System.out.println("Date has been feeded automatically:" + dtf.format(now));
mem[i].date = dtf.format(now);
bwriter.write(String.valueOf(mem[i].memId));
bwriter.write("|");
bwriter.write(mem[i].memName);
bwriter.write("|");
bwriter.write(mem[i].memEmail);
bwriter.write("|");
bwriter.write(mem[i].memPh);
bwriter.write("|");
bwriter.write(mem[i].date);
bwriter.write("\n");
System.out.println("MEMBER CREATED SUCCESSFULLY");
System.out.println("---------------------------------------");
bwriter.close();
} catch (IOException e) {
System.out.print(e);
}
}
static int getMemberRecords() {
int count = 0, i = 0;
try {
fread = new FileReader("C:\\Users\\itisa\\OneDrive\\Desktop\\GYM PROJECT\\member.txt");
bread = new BufferedReader(fread);
String lineRead = null;
while ((lineRead = bread.readLine()) != null)//Just to get to know the number of member
//alreadyinside the file
{
String[] t = lineRead.split("\\|");
mem[i].memId = Integer.parseInt(t[0]);
mem[i].memName = t[1];
mem[i].memEmail = t[2];
mem[i].memPh = t[3];
mem[i].date = t[4];
i++;
count++;
}
System.out.println(mem[0].memName);//should print the 1st name present in the name
//i.e, RAVI
} catch (IOException e) {
System.out.println(e);
}
return count;
}
public static void main(String[] args) throws IOException {
System.out.println("Total number of accounts:" + getMemberRecords());
}
}
Elements stored in the file:
101|RAVI|itisadi23#gmai.com|9102019656|2020/04/30
102|aditya|adi#gmail.com|9386977983|2020/04/30
103|anurag|anu#ymail.com|10000000000|2020/04/30
104|alex|alex123#mail.com|2829578303|2020/04/30
Expected output:
RAVI
Total number of accounts = 4
My output:
alex
Total number of accounts=4
In Short it is giving last name as output no matter what index number is given to fetch the data.
Your member class members must not be static, if they are, they're shared by every member class object.
The other problem is that your member array nodes are not being initialized, you'll need:
Live demo
class member
{
int memId; //non-static
String memName, memEmail, memPh, date; //non-static
}
and
//...
while ((lineRead = bread.readLine()) != null) {
String[] t = lineRead.split("\\|");
mem[i] = new member(); // initialize every node
mem[i].memId = Integer.parseInt(t[0]);
mem[i].memName = t[1];
mem[i].memEmail = t[2];
mem[i].memPh = t[3];
mem[i].date = t[4];
i++;
count++;
}
System.out.println(mem[0].memName);
//...
Output:
RAVI
Note that you can use ArrayList or other java collection.

How to store file data lines and pass it method to calculate into letters and print letter grades in another file? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
class.txt
Reena Sam, 100, 90, 80, 100,
Donna D. Bartolome, 90, 90, 100, 100,
Chris Tui, 100, 90, 100, 70,
I'm new to java and I'm trying to figure out
how to store file data lines to calculate into letters and print letter grades in another file?
I'm trying to look into storing into multiple objects or ArrayLists…
like this:
Reena Sam: A
Donna D. Bartolome: B
Chris Tui: C
Below is my current progress towards this, but I got stuck in trying to store the data. pls help...
...
class gradeMaker{
private Scanner readFile;
private String[] argument;
private ArrayList<String> list;
private String finalGrade ="";
gradeMaker(String [] arg) {
argument = arg;
}
void readStudentScores() {
File file = new File(argument[0]);
if (!file.exists()) {
System.out.println("Input file" + argument[0] + "does not exist");
System.exit(2);
}
try{ // Create a Scanner for the file
readFile = new Scanner(file);
ArrayList<Student> list = new ArrayList<>();
// Read data from a file
System.out.println("Read data from a file");
while (readFile.hasNextLine()) {
String temp = readFile.nextLine();
//list.add(new Student ()); //Stores Student student1 = new Student(Name2, 20, 28, 60,)
//Stores Student student2 = new Student(Name2, 20, 28, 60,)
System.out.println(temp);
//String[] studentInfo = line.split(",");
}
Collections.sort(list);
for (int i = list.size(); i >= 0; i++)
System.out.print(list.get(i) + " ");
System.out.println(list.toString());
// System.out.println();
}catch (IOException e) {
System.out.println("Error Reading from file:" + file + e.getMessage());
}
}
void computeGrade() {
int Q1 = quiz1;
int Q2 = quiz2;
int M1 = mid;
int FN = finals;
int finalScore = (Q1 * .20 + Q2 * .20 + M1 * .25 + FN * .35);
if (finalScore >= .9)
finalGrade = "A";
else if (finalScore >= .8 && finalScore <= .89 )
finalGrade = "B";
else if (finalScore >= .7 && finalScore <= .79 )
finalGrade = "C";
else if (finalScore >= .6 && finalScore <= .69 )
finalGrade = "D";
else if (finalScore <= .59 )
finalGrade = "F";
//}
}
void Grades() {
File outputFile = new File(argument[1]);
try {
PrintWriter output = new PrintWriter(outputFile);
while (readFile.hasNextLine()) {
output.println(finalGrade);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
A couple things here. First, I see you have a System print set to catch unknown errors on your collections sort. printStackTrace will be more useful there.
Also your PrintWriter is returning just a grade. To get the output you want, you really want to return a constructor with a concatenated string. You can do this by making an object of your class that handles the arguments you need to return. Something like:
String finalGrade = f.toString();
public gradeMarker(String name, String finalGrade) {
this.name = name;
this.finalGrade = finalGrade;
}
You have final grade as an integer (f), but personally I find it easier to read/write data as strings. You can follow this up with your getter and setter methods, and then put a final method that returns the output you want. Something like
public String toString() {
return name + "," + finalGrade;
}
You can then put your results in a list and write it to the file using a for each loop
List<gradeMaker> grade = FileReader(//your file)
PrintWriter output = new PrintWriter(//your file)
for (gradeMaker x : grade) {
output.println(x);
}
That'll print each line, and since it's for each will only go long as an object exists to print. Hope all of that helps!
Here is fully working example as starting point. If you are using Java 7 or above you can improve it by using java.nio.file, which is a way to work with files up todays standards, instead of java.io.File. You could also consider using java 8 streams to make mapping a line to an object cleaner and more readable.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class MarksToGrades {
public static void main(String[] args){
String inputFile = "C:\\Users\\Eritrean\\Desktop\\marks.txt";
List<Student> students = readFileAndGetStudents(inputFile);
String outputFile = "C:\\Users\\Eritrean\\Desktop\\grades.txt";
writeStudentsDataToFile(students,outputFile);
}
static List<Student> readFileAndGetStudents(String inputFileName){
List<Student> students = new ArrayList<>();
try(FileReader fr = new FileReader(new File(inputFileName));
BufferedReader reader = new BufferedReader(fr);){
String line = "";
while ((line = reader.readLine()) != null) {
System.out.println(line);
students.add(new Student(line));
}
}
catch(IOException e){
e.printStackTrace();
}
return students;
}
static void writeStudentsDataToFile(List<Student> students, String outputFileName){
try (FileWriter writer = new FileWriter(outputFileName);
BufferedWriter bw = new BufferedWriter(writer)) {
for(Student stud : students){
System.out.println(stud.toString());
bw.write(stud.toString());
bw.newLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
static class Student{
String name;
int quiz1;
int quiz2;
int mid1;;
int finals;
double total;
char grade;
// getter & setter omitted as they are not important for this task. if necessary, you can add them
public Student(String line) {
String[] data = line.split(",");
this.name = data[0];
this.quiz1 = Integer.parseInt(data[1].trim());
this.quiz2 = Integer.parseInt(data[2].trim());
this.mid1 = Integer.parseInt(data[3].trim());
this.finals = Integer.parseInt(data[4].trim());
this.total = calculateTotal (quiz1,quiz2,mid1,finals);
this.grade = getGrade(total);
}
private double calculateTotal(int quiz1, int quiz2, int mid1, int finals) {
return quiz1 * .20 + quiz2 * .20 + mid1 * .25 + finals * .35;
}
private char getGrade(double total) {
if (total >= 90)
return 'A';
else if (total >= 80)
return 'B';
else if (total >= 70)
return 'C';
else if (total >= 60)
return 'D';
else
return 'F';
}
#Override
public String toString() {
return name + ": " + grade ;
}
}
}

When I run my code I get (0, null) and cant figure out why

I am creating a program that is reading a file of names and ages then printing them out in ascending order. I am parsing through the file to figure out the number of name age pairs and then making my array that big.
The input file looks like this:
(23, Matt)(2000, jack)(50, Sal)(47, Mark)(23, Will)(83200, Andrew)(23, Lee)(47, Andy)(47, Sam)(150, Dayton)
When I am running my code I get the output of (0,null) and I am not sure why. I have been trying to fix it for a while and am lost. If anyone can help that would be great My code is below.
public class ponySort {
public static void main(String[] args) throws FileNotFoundException {
int count = 0;
int fileSize = 0;
int[] ages;
String [] names;
String filename = "";
Scanner inputFile = new Scanner(System.in);
File file;
do {
System.out.println("File to read from:");
filename = inputFile.nextLine();
file = new File(filename);
//inputFile = new Scanner(file);
}
while (!file.exists());
inputFile = new Scanner(file);
if (!inputFile.hasNextLine()) {
System.out.println("No one is going to the Friendship is magic Party in Equestria.");
}
while (inputFile.hasNextLine()) {
String data1 = inputFile.nextLine();
String[] parts1 = data1.split("(?<=\\))(?=\\()");
for (String part : parts1) {
String input1 = part.replaceAll("[()]", "");
Integer.parseInt(input1.split(", ")[0]);
fileSize++;
}
}
ages = new int[fileSize];
names = new String[fileSize];
while (inputFile.hasNextLine()) {
String data = inputFile.nextLine();
String[] parts = data.split("(?<=\\))(?=\\()");
for (String part : parts) {
String input = part.replaceAll("[()]", "");
ages[count] = Integer.parseInt(input.split(", ")[0]);
names[count] = input.split(", ")[1];
count++;
}
}
ponySort max = new ponySort();
max.bubbleSort(ages, names, count);
max.printArray(ages, names, count);
}
public void printArray(int ages[], String names[], int count) {
System.out.print("(" + ages[0] + "," + names[0] + ")");
// Checking for duplicates in ages. if it is the same ages as one that already was put in them it wont print.
for (int i = 1; i < count; i++) {
if (ages[i] != ages[i - 1]) {
System.out.print("(" + ages[i] + "," + names[i] + ")");
}
}
}
public void bubbleSort(int ages[], String names[], int count ){
for (int i = 0; i < count - 1; i++) {
for (int j = 0; j < count - i - 1; j++) {
// age is greater so swaps age
if (ages[j] > ages[j + 1]) {
// swap the ages
int temp = ages[j];
ages[j] = ages[j + 1];
ages[j + 1] = temp;
// must also swap the names
String tempName = names[j];
names[j] = names[j + 1];
names[j + 1] = tempName;
}
}
}
}
}
output example
File to read from:
file.txt
(0,null)
Process finished with exit code 0
What your code does is to Scan the file twice.
In the first loop you do
String data1 = inputFile.nextLine();
Code reads first line and then scanner goes to the next (second) line.
Later you do again inputFile.nextLine(); The second line is empty and the code never goes into the second loop and content is never read.
If you can use Lists, you should create two array lists and add ages and names into the arraylists in the first scan, so you scan the file once. When done, you could get the Array out of the arraylist.
If you should only use arrays and you want a simple update, just add another Scanner before the second loop:
ages = new int[fileSize];
names = new String[fileSize];
inputFile = new Scanner(file); // add this line

Specified text file not found for File I/O in Eclipse

I am trying to do a file I/O in eclipse. Here is the code:
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.StringTokenizer;
public class TextDB {
public static final String SEPARATOR = "|";
// an example of reading
public static ArrayList readProfessors(String filename) throws IOException {
// read String from text file
ArrayList stringArray = (ArrayList) read(filename);
ArrayList alr = new ArrayList();// to store Professors data
for (int i = 0; i < stringArray.size(); i++) {
String st = (String) stringArray.get(i);
// get individual 'fields' of the string separated by SEPARATOR
StringTokenizer star = new StringTokenizer(st, SEPARATOR); // pass in the string to the string tokenizer using delimiter ","
String name = star.nextToken().trim(); // first token
String email = star.nextToken().trim(); // second token
int contact = Integer.parseInt(star.nextToken().trim()); // third token
// create Professor object from file data
Professor prof = new Professor(name, email, contact);
// add to Professors list
alr.add(prof);
}
return alr;
}
// an example of saving
public static void saveProfessors(String filename, List al) throws IOException {
List alw = new ArrayList();// to store Professors data
for (int i = 0; i < al.size(); i++) {
Professor prof = (Professor) al.get(i);
StringBuilder st = new StringBuilder();
st.append(prof.getName().trim());
st.append(SEPARATOR);
st.append(prof.getEmail().trim());
st.append(SEPARATOR);
st.append(prof.getContact());
alw.add(st.toString());
}
write(filename, alw);
}
/**
* Write fixed content to the given file.
*/
public static void write(String fileName, List data) throws IOException {
PrintWriter out = new PrintWriter(new FileWriter(fileName));
try {
for (int i = 0; i < data.size(); i++) {
out.println((String) data.get(i));
}
} finally {
out.close();
}
}
/**
* Read the contents of the given file.
*/
public static List read(String fileName) throws IOException {
List data = new ArrayList();
Scanner scanner = new Scanner(new FileInputStream(fileName));
try {
while (scanner.hasNextLine()) {
data.add(scanner.nextLine());
}
} finally {
scanner.close();
}
return data;
}
public static void main(String[] aArgs) {
TextDB txtDB = new TextDB();
String filename = "professor.txt";
try {
// read file containing Professor records.
ArrayList al = TextDB.readProfessors(filename);
for (int i = 0; i < al.size(); i++) {
Professor prof = (Professor) al.get(i);
System.out.println("Name " + prof.getName());
System.out.println("Contact " + prof.getContact());
}
Professor p1 = new Professor("Joseph", "jos#ntu.edu.sg", 67909999);
// al is an array list containing Professor objs
al.add(p1);
// write Professor record/s to file.
TextDB.saveProfessors(filename, al);
} catch (IOException e) {
System.out.println("IOException > " + e.getMessage());
}
}
}
And my Professor class:
import java.io.Serializable;
public class Professor implements Serializable {
private String name;
private String email;
private int contact;
public Professor(String n, String e, int c) {
name = n;
email = e;
contact = c;
}
public String getName() {
return name;
}
public int getContact() {
return contact;
}
public String getEmail() {
return email;
}
public boolean equals(Object o) {
if (o instanceof Professor) {
Professor p = (Professor) o;
return (getName().equals(p.getName()));
}
return false;
}
}
However, when I run it, the compiler told the the specified file "professor.txt" is not found. I thought the compiler will create the text file automatically based on these code?
Thanks in advance.
Before attempting to read the file in your application, create it if it doesn't exist, either directly :
String filename = "professor.txt" ;
File file = new File(fileName);
if(!file.exists()){
file.createNewFile();
}
Or by calling your write method.
String filename = "professor.txt" ;
File file = new File(fileName);
if(!file.exists()){
TextDB.saveProfessors(filename, new ArrayList());
}
The PrintWriter will create the file for you, even though nothing is written to it (like with this empty list).
In your main you are firstly reading the file and then write it: if the file doesn't exist it will throw you the exception. Probably, the first time you ran it, the file was present (maybe you have write the code to write the file first and then you have launch it).
so, two solutions...
First: change the order of your main.
public static void main(String[] aArgs) {
TextDB txtDB = new TextDB();
String filename = "professor.txt";
try {
Professor p1 = new Professor("Joseph", "jos#ntu.edu.sg", 67909999);
// al is an array list containing Professor objs
al.add(p1);
// write Professor record/s to file.
TextDB.saveProfessors(filename, al);
// read file containing Professor records.
ArrayList al = TextDB.readProfessors(filename);
for (int i = 0; i < al.size(); i++) {
Professor prof = (Professor) al.get(i);
System.out.println("Name " + prof.getName());
System.out.println("Contact " + prof.getContact());
}
} catch (IOException e) {
System.out.println("IOException > " + e.getMessage());
}
}
Second: check if the file exist or not and then skip the read of it if it doesn't
public static void main(String[] aArgs) {
TextDB txtDB = new TextDB();
String filename = "professor.txt";
try {
//check if the file exist
File oFile = new File(filename);
if(oFile.exist()) {
// read file containing Professor records.
ArrayList al = TextDB.readProfessors(filename);
for (int i = 0; i < al.size(); i++) {
Professor prof = (Professor) al.get(i);
System.out.println("Name " + prof.getName());
System.out.println("Contact " + prof.getContact());
}
}
Professor p1 = new Professor("Joseph", "jos#ntu.edu.sg", 67909999);
// al is an array list containing Professor objs
al.add(p1);
// write Professor record/s to file.
TextDB.saveProfessors(filename, al);
} catch (IOException e) {
System.out.println("IOException > " + e.getMessage());
}
}
UPDATE after comment:
public static void main(String[] aArgs) {
TextDB txtDB = new TextDB();
String filename = "professor.txt";
try {
//check if the file exist
File oFile = new File(filename);
if(!oFile.exist()) {
oFile.mkdirs(); //optional
oFile.createNewFile();
}
// read file containing Professor records.
ArrayList al = TextDB.readProfessors(filename);
for (int i = 0; i < al.size(); i++) {
Professor prof = (Professor) al.get(i);
System.out.println("Name " + prof.getName());
System.out.println("Contact " + prof.getContact());
}
Professor p1 = new Professor("Joseph", "jos#ntu.edu.sg", 67909999);
// al is an array list containing Professor objs
al.add(p1);
// write Professor record/s to file.
TextDB.saveProfessors(filename, al);
} catch (IOException e) {
System.out.println("IOException > " + e.getMessage());
}
}

Scanner from file doesn't seem to be reading file

I'm doing a Phone Directory project and we have to read from a directory file telnos.txt
I'm using a Scanner to load the data from the file telnos.txt, using a loadData method from a previous question I asked here on StackOverflow.
I noticed attempts to find a user always returned Not Found, so I added a few System.out.printlns in the methods to help me see what was going on. It looks like the scanner isn't reading anything from the file. Weirdly, it is printing the name of the file as what should be the first line read, which makes me think I've missed something very very simple here.
Console
run:
telnos.txt
null
loadData tested successfully
Please enter a name to look up: John
-1
Not found
BUILD SUCCESSFUL (total time: 6 seconds)
ArrayPhoneDirectory.java
import java.util.*;
import java.io.*;
public class ArrayPhoneDirectory implements PhoneDirectory {
private static final int INIT_CAPACITY = 100;
private int capacity = INIT_CAPACITY;
// holds telno of directory entries
private int size = 0;
// Array to contain directory entries
private DirectoryEntry[] theDirectory = new DirectoryEntry[capacity];
// Holds name of data file
private final String sourceName = "telnos.txt";
File telnos = new File(sourceName);
// Flag to indicate whether directory was modified since it was last loaded or saved
private boolean modified = false;
// add method stubs as specified in interface to compile
public void loadData(String sourceName) {
Scanner read = new Scanner("telnos.txt").useDelimiter("\\Z");
int i = 1;
String name = null;
String telno = null;
while (read.hasNextLine()) {
if (i % 2 != 0)
name = read.nextLine();
else
telno = read.nextLine();
add(name, telno);
i++;
}
}
public String lookUpEntry(String name) {
int i = find(name);
String a = null;
if (i >= 0) {
a = name + (" is at position " + i + " in the directory");
} else {
a = ("Not found");
}
return a;
}
public String addChangeEntry(String name, String telno) {
for (DirectoryEntry i : theDirectory) {
if (i.getName().equals(name)) {
i.setNumber(telno);
} else {
add(name, telno);
}
}
return null;
}
public String removeEntry(String name) {
for (DirectoryEntry i : theDirectory) {
if (i.getName().equals(name)) {
i.setName(null);
i.setNumber(null);
}
}
return null;
}
public void save() {
PrintWriter writer = null;
// writer = new PrintWriter(FileWriter(sourceName));
}
public String format() {
String a;
a = null;
for (DirectoryEntry i : theDirectory) {
String b;
b = i.getName() + "/n";
String c;
c = i.getNumber() + "/n";
a = a + b + c;
}
return a;
}
// add private methods
// Adds a new entry with the given name and telno to the array of
// directory entries
private void add(String name, String telno) {
System.out.println(name);
System.out.println(telno);
theDirectory[size] = new DirectoryEntry(name, telno);
size = size + 1;
}
// Searches the array of directory entries for a specific name
private int find(String name) {
int result = -1;
for (int count = 0; count < size; count++) {
if (theDirectory[count].getName().equals(name)) {
result = count;
}
System.out.println(result);
}
return result;
}
// Creates a new array of directory entries with twice the capacity
// of the previous one
private void reallocate() {
capacity = capacity * 2;
DirectoryEntry[] newDirectory = new DirectoryEntry[capacity];
System.arraycopy(theDirectory, 0, newDirectory,
0, theDirectory.length);
theDirectory = newDirectory;
}
}
ArrayPhoneDirectoryTester.java
import java.util.Scanner;
public class ArrayPhoneDirectoryTester {
public static void main(String[] args) {
//create a new ArrayPhoneDirectory
PhoneDirectory newTest = new ArrayPhoneDirectory();
newTest.loadData("telnos.txt");
System.out.println("loadData tested successfully");
System.out.print("Please enter a name to look up: ");
Scanner in = new Scanner(System.in);
String name = in.next();
String entryNo = newTest.lookUpEntry(name);
System.out.println(entryNo);
}
}
telnos.txt
John
123
Bill
23
Hello
23455
Frank
12345
Dkddd
31231
In your code:
Scanner read = new Scanner("telnos.txt");
Is not going to load file 'telnos.txt'. It is instead going to create a Scanner object that scans the String "telnos.txt".
To make the Scanner understand that it has to scan a file you have to either:
Scanner read = new Scanner(new File("telnos.txt"));
or create a File object and pass its path to the Scanner constructor.
In case you are getting "File not found" errors you need to check the current working directory. You could run the following lines and see if you are indeed in the right directory in which the file is:
String workingDir = System.getProperty("user.dir");
System.out.println("Current working directory : " + workingDir);
You need to also catch the FileNotFoundException in the function as follows:
public void loadData(String sourceName) {
try {
Scanner read = new Scanner(new File("telnos.txt")).useDelimiter("\\Z");
int i = 1;
String name = null;
String telno = null;
while (read.hasNextLine()) {
if (i % 2 != 0)
name = read.nextLine();
else {
telno = read.nextLine();
add(name, telno);
}
i++;
}
}catch(FileNotFoundException ex) {
System.out.println("File not found:"+ex.getMessage);
}
}
You are actually parsing the filename not the actual file contents.
Instead of:
new Scanner("telnos.txt")
you need
new Scanner( new File( "telnos.txt" ) )
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

Categories