Java-Greatest number of friends (from .txt file) - java

I'm trying to create a program that reads in a .txt file with multiple lines containing lists of names. A sample of the test file is below:
Joe Sue Meg Ry Luke
Kay Trey Phil George
I have three classes(also below). Everything works fine, but I would like to know which friend-set has the greatest number of friends (i.e. in the test file Joe would have the greatest number of friends)
The data isn't limited to only two friend-sets though...
import java.io.*;
//Finds the file
public class ReadFileLine {
public static void main(String[] args) throws Exception {
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in),1);
System.out.println("Hello! " + "Please enter the name of your test file: " +
"\n**Hint** for this assignment the file name is: friendsFile.txt\n");
String fileName= keyboard.readLine();
System.out.println(fileName);//
FileLine doLine = new FileLine();
doLine.readList(fileName);
}
}
Class 2:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class InStringFile {
//read the file
private BufferedReader in;
//read each line
private String nextLine;
//handle exceptions
public InStringFile(String filename) {
//line by line input
try {
in = new BufferedReader(new FileReader(filename));
nextLine = in.readLine();
}
catch (FileNotFoundException ee){
System.out.println("We're sorry,\n" +"File " + filename + " cannnot be found.");
System.exit(0);
}
catch (IOException e){
System.out.println("We're sorry,\n" +"File " + filename + " cannot be read.");
System.exit(0);
}
}
//reads the file as string
public String read() {
String current = nextLine;
try {
nextLine = in.readLine();
}
//catch exception
catch (IOException e){
System.out.println("We're sorry, this file cannot be read.");
System.exit(0);
}
return current;
}
public boolean endOfFile() {
return (nextLine == null);
}
//close the file
public void close(){
try {
in.close();
in = null;
}
//catch if file cannot be closed
catch (IOException e){
System.out.println("Problem closing file.");
System.exit(0);
}
}
}
Class 3:
import java.util.StringTokenizer;
public class FileLine {
public void readList (String fileName) throws Exception {
//opens the file and controls file reading
InStringFile reader = new InStringFile(fileName);
System.out.println("\nFile Found!" +
" Now reading from file: " + fileName + "\n");
// line by line read
String line;
do {
line = (reader.read());
//print the friend list
System.out.println("The following friend-set exists: " + line);
this.TokenizeString(line);
}while (!reader.endOfFile());
reader.close();
}
//number of friends
public void TokenizeString(String nameList){
StringTokenizer tokens = new StringTokenizer(nameList);
System.out.println("The number of friends in this friend-set is: " + tokens.countTokens());
}
}
Okay, so I modified the fileLine class to be the following:
import java.util.StringTokenizer;
public class FileLine {
public void readList (String fileName) throws Exception {
//opens the file and controls file reading
InStringFile reader = new InStringFile(fileName);
System.out.println("\nFile Found!" +
" Now reading from file: " + fileName + "\n");
// line by line read
String line;
do {
line = (reader.read());
//print the friend list
System.out.println("The following friend-set exists: " + line);
this.TokenizeString(line, line);
}while (!reader.endOfFile());
reader.close();
}
//number of friends
public void TokenizeString(String nameList, String nameByName) {
StringTokenizer tokens = new StringTokenizer(nameList);
System.out.println("The number of friends in this friend-set is: " + tokens.countTokens());
StringTokenizer st = new StringTokenizer(nameByName, " ");
String firstName = st.nextToken();
System.out.println("Friend-set Leader: " + firstName);
}
}
So now the code returns the first name in each line... I still am stuck on how to store the number of tokens. IF I could do that then I could compare and return the greatest number (right?)...

Let tokenizeString(..) return the number of friends. Then:
int maxFriends = 0;
int maxFriendsLine = 0;
int currentLine = 0;
while (..) {
int friends = tokenizeString(..);
if (friends > maxFriends) {
maxFriendsLine = currentLine;
maxFriends = friends;
}
currentLine++;
}
A few notes:
see if you can use commons-lang FileUtils.readLines(..) or guava Files.readLines(..)
prefer str.split(" ") instead of StringTokenizer
use lower-case methods - that's what the java convention prescribes.

Related

Read CSV containing Strings & int to arraylist with try/catch

I'm hoping some might be able to suggest an alternate method to a program I'm working on. I've done the below test code to display my query without having to post my full code.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class Main {
ArrayList<Students> chemistry = new ArrayList<>();
public void loadClass() {
try (BufferedReader br = new BufferedReader(new FileReader("Chemistry.csv"))) {
String line;
line = br.readLine();
while ((line = br.readLine()) != null) {
String[] values = line.split(",");
try {
chemistry.add(new Students(values[0], values[1], Integer.parseInt(values[2]),
Integer.parseInt(values[3]), Integer.parseInt(values[4])));
} catch (NumberFormatException e) {
System.out.println("You have some text in a number field for entry: " + values[0] + " " + values[1]);
}
}
} catch (FileNotFoundException e) {
System.out.println("The file has not been found in the path \"" + (new File(".").getAbsoluteFile()) + "\"");
System.out.println("Please place the CSV file at this location");
} catch (IOException e) {
System.out.println("Sorry an input/output error has occured.");
e.printStackTrace();
}
System.out.println("students loaded from the file are:");
for (Students pupils : chemistry) {
System.out.println("Student " + pupils.getFirstName() + " " + pupils.getSurname() + " was born in "
+ pupils.getBirthYear() + "/" + pupils.getBirthMonth() + " /"
+ pupils.getBirthDay());
}
System.out.println("\nThe number of students in the class is: " + chemistry.size());
}
public static void main(String[] args) {
Main main = new Main();
main.loadClass();
}
}
public class Students {
private String firstName;
private String surname;
private int birthYear;
private int birthMonth;
private int birthDay;
// All-args constructor, getters and setters omitted for brevity
}
Here is the CSV data I'm using in the Chemistry.csv file
First Name,Surname,Year of Birth,Month of Birth,Day of Birth
Joe,Bloggs,2002,12,8
Jane,Bloggs,2003,11,15
Harry,Smith,2004,10,2
William,Wallace,2001,9,7
Philip,Jones,2002,Aug,9th
As you can see in my CSV file, I've deliberately put a string entry for the month and day in the last line. This is to test my NumberFormatException try/catch.
It works and the user gets prompted that there's an error with that line entry, but this is a small dataset. I'm wondering what I can do when there may be hundreds of lines.
I was thinking that in the catch I could have something that would replace the invalid String with a valid int number. I know in this case I would have to engineer an if/else or switch statement to account for the 12 months and 30(ish) days, however I would just like '0' to be entered for now.
I'm not sure how to pass int 0 as a default value for this as my chemistry.add line parses the file.
I also thought there may be an alternate way of entering the values into my ArrayList so I can put the try/catch around just the Integer.parseInt bits, but again, I'm not sure of another method.
Can anyone suggest a good option to investigate?
EDIT:
After the comment by g00se below, I used this instead and it seemed to work:
while ((line = br.readLine()) != null) {
int third, fourth, fifth;
String[] values = line.split(",");
String first = values[0];
String second = values[1];
try {
third = Integer.parseInt(values[2]);
} catch (NumberFormatException e3) {
third = 0;
}
try {
fourth = Integer.parseInt(values[3]);
} catch (NumberFormatException e4) {
fourth = 0;
}
try {
fifth = Integer.parseInt(values[4]);
} catch (NumberFormatException e5) {
fifth = 0;
}
chemistry.add(new Student(first, second, third, fourth, fifth));
}
Needs some tidying up but at least I have a way forward...

Call the exact value from text File

Hi guys need help for my mini project for schools. How do i compare the user input and match to my database in text file. this is like validity for username and password. I want to call the second line on my data base using account Number and pin.
this is my data base.
0,admin,adminLastName,123456,123456
1,user,userLastName,1234567,123456
0 = id
admin = name
adminLastName = Last Name
1234567 = accountNumber
123456 = pin
and this is my code.
package atm;
import java.io.File;
import java.util.Scanner;
public class Login {
static void verifyLogin(String name, String lastName, String userAccountNumber, String userPin, String filePath){
Scanner inputData = new Scanner(System.in);
boolean isFound = false;
String tempAccountNumber = "";
String tempPin = "";
System.out.print("\nAccount Number: ");
userAccountNumber = inputData.next();
System.out.print("\nPIN: ");
userPin = inputData.next();
try{
Scanner readTextFile = new Scanner(new File("myDataBase.txt")).useDelimiter("[,\n]");
while (readTextFile.hasNext() && !isFound){
tempAccountNumber = readTextFile.next();
tempPin = readTextFile.next();
if (tempAccountNumber.trim().equals(userAccountNumber.trim()) && tempPin.trim().equals(userPin.trim())){
isFound = true;
System.out.println("Welcome " + name+ " " +lastName);
System.out.println("\nLogin Successfully!");
}
else {
System.out.println("You have entered your PIN or ACCOUNT NUMBER incorrectly. Please check your PIN or ACCOUNT NUMBER and try again.\n If you don't have account yet please go to SignUp page!\n");
myMain mainMenu = new myMain();
mainMenu.inputKeyboard();
}
}
readTextFile.close();
}
catch (Exception e){
}
inputData.close();
}
}
If your textfile contains 1 user per line, and you split it with ',' then you can take each line like you do, then split that line into a string[] array and check if i.e. the name corresponds to 'admin'.
public class Main {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
Boolean loggedin = false;
String fileName = "accounts.txt";
String line = null;
System.out.println("What's your username?");
String tempUsername = input.nextLine();
System.out.println("What's your password?");
String tempPassword = input.nextLine();
try {
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
String[] currAccount = line.split(",");
if (currAccount[1].equals(tempUsername) && currAccount[4].equals(tempPassword)) {
loggedin = true;
System.out.println("You have successfully logged in!");
}
}
bufferedReader.close();
}
catch(FileNotFoundException ex) {
ex.printStackTrace();
// Let's create it if file can't be found or doesn't exist, but let's ask first.
String answer;
System.out.print("File not found, do you want to create it? [Y/n]: ");
answer = input.nextLine();
if (answer.equalsIgnoreCase("y")) {
try {
FileWriter fileWriter = new FileWriter(fileName);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
System.out.println("File has been created!");
} catch (IOException exc) {
exc.printStackTrace();
}
} else {
System.out.println("File was not created!");
}
}
catch(IOException ex) {
ex.printStackTrace();
}
if (!loggedin) {
System.out.println("Your login combination did not exist.");
}
}
}
Please note, I haven't commented a lot, but it should still make sense.
After splitting remember that you start at array index 0, and not 1. So at index 1 the name on the account will be.
Goodluck.

NumberFormatException with File IO

I keep getting a NumberFormatException, which I understand arises due to a string conversion. I am converting st.nexttoken to a double with Double.parseDouble.
Any help would be much appreciated!
import java.io.*;
import java.util.*;
public class FileIO {
public static void main(String[] args) throws Exception {
double sum = 0, next ;
int ctr = 0;
String line;
String filename = "numbers.txt";
StringTokenizer st;
PrintWriter outFile = new PrintWriter("output.txt");
outFile.println("Output File");
try{
Scanner inFile = new Scanner(new FileReader (filename));
while (inFile.hasNext())
{
line = inFile.nextLine();
st = new StringTokenizer(line);
while (st.hasMoreTokens()){
next = Double.parseDouble(st.nextToken());
sum += next;
ctr++;
System.out.println(next);
outFile.println(next);
}
}
System.out.println("number of doubles read is " + ctr);
System.out.println("average is " + sum/(double)ctr);
outFile.println("number of doubles read is " + ctr);
outFile.println("average is " + sum/(double)ctr);
outFile.close();
}
catch(FileNotFoundException e){
System.out.println("The file numbers.txt was not found");
}
catch(NumberFormatException e){
System.out.println("sorry - number format error");
System.out.println(e);
}
}
}
The error from NetBeans reads sorry - number format error
java.lang.NumberFormatException: For input string: "Output"
numbers.txt has some integers as well as doubles with decimal points.
output.txt is blank, but saved in the same file path as numbers.txt
Here is the body of numbers.txt as requested.
13 12 15 3
74.4 67.3 43.8 77.7 233.4 678.9
public static void main(String[] args) throws Exception {
double sum = 0, next ;
int ctr = 0;
String line;
String filename = "numbers.txt";
StringTokenizer st;
PrintWriter outFile = new PrintWriter("output.txt");
outFile.println("Output File");
try{
Scanner inFile = new Scanner(new FileReader(filename));
while (inFile.hasNext())
{
line = inFile.nextLine();
st = new StringTokenizer(line);
while (st.hasMoreTokens()){
next = Double.parseDouble(st.nextToken());
sum += next;
ctr++;
System.out.println(next);
outFile.println(next);
}
}
System.out.println("number of doubles read is " + ctr);
System.out.println("average is " + sum/(double)ctr);
outFile.println("number of doubles read is " + ctr);
outFile.println("average is " + sum/(double)ctr);
outFile.flush();
inFile.close();
outFile.close();
}
catch(FileNotFoundException e){
System.out.println("The file numbers.txt was not found");
}
catch(NumberFormatException e){
System.out.println("sorry - number format error");
System.out.println(e);
}
}
Above is modified version of your code and it works fine with the below given number.txt.
You need use the flush() write it to the final destination.
Here is the number.txt
12 12.0 12
12 32 56
34
34.0

Store 100 strings and search file i/o java

In this program I am trying write a program that reads the first 100 strings from a set of text files and then counts how many times those strings appear in the whole of each file. Well I keep getting a crazy output and I asked this question earlier but butchered it. One thing has changed but now my output is null = 0. for 100 times
my output: http://i.imgur.com/WVZJnTp.png
package program6;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class Program6 {
public static final String INPUT_FILE_NAME = "myths.txt";
public static final String INPUT_FILE_NAME2 = "pnp.txt";
public static final String INPUT_FILE_NAME3 = "tsawyer.txt";
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
Scanner in = null;
Scanner fin = null;
Scanner fin2 = null;
Scanner fin3 = null;
String[] character = new String[100];
int[] counter = new int[100];
try {
fin = new Scanner(new File(INPUT_FILE_NAME));
} catch (FileNotFoundException e) {
System.err.println("Error opening the file " + INPUT_FILE_NAME);
System.exit(1);
}
try {
fin2 = new Scanner(new File(INPUT_FILE_NAME2));
} catch (FileNotFoundException e) {
System.err.println("Error opening the file " + INPUT_FILE_NAME2);
System.exit(1);
}
try {
fin3 = new Scanner(new File(INPUT_FILE_NAME3));
} catch (FileNotFoundException e) {
System.err.println("Error opening the file " + INPUT_FILE_NAME3);
System.exit(1);
}
for (int i = 0; i < character.length; i++) {
}
System.out.println("Word: Count:");
for (int i = 0; i < 100; i++) {
System.out.println(character[i] + " " + counter[i]);
}
}
}
Simply replace
System.out.println(character + " " + counter);
by
System.out.println(character[i] + " " + counter[i]);
On this line System.out.println(character + " " + counter);
It should be:
System.out.println(character[i] + " " + counter[i]);

Main method input file keeps giving me IndexOutOfBoundsException (even with right arguments)

I'm trying to use args[0] as an input file, but when I run the program, I keep getting an IndexOutOfBoundsException, although I'm quite sure that args[0] is the correct argument. I ran into this problem with my last program as well, but I can't figure out what I'm doing wrong.
Code:
import java.io.*;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class SortTest {
public static void main(String args[]) throws FileNotFoundException {
try {
Scanner read = new Scanner(new File(args[0]));
while (read.hasNextLine()) {
String name = read.nextLine();
read.nextLine();
String line1 = read.nextLine();
int sh = Integer.parseInt(line1.substring(0,2));
int sm = Integer.parseInt(line1.substring(3));
read.nextLine();
String line2 = read.nextLine();
int fh = Integer.parseInt(line2.substring(0,2));
int fm = Integer.parseInt(line2.substring(3));
if (fh<sh) {
System.out.println("Times not in correct order.");
return;
} else if (fh==sh) {
if (fm<sm) {
System.out.println("Times not in correct order.");
return;
}
} else {
System.out.println(name + "\n" + sh + ":" + sm + "\n" + fh + ":" + fm);
}
}
read.close();
}
catch (FileNotFoundException e) {
System.out.println("Invalid file path.");
}
catch (NoSuchElementException n) {
System.out.println("No readable text in file.");
}
catch (IndexOutOfBoundsException x) {
System.out.println("Proper format is java LectureSortTest <input>");
}
catch (NumberFormatException num) {
System.out.println("File contents not formatted correctly");
}
}
}

Categories