Java CSV read file validation doesnt work - java

Background : The code is supposed to go through a csv file (second link), find the username and password and either confirm and display all the info or write error. But now it only says error. Cheers in advance.
http://pastebin.com/YBpKRKe2
http://pastebin.com/9K3nwYG3
import java.io.*;
import java.util.*;
public class CSVRead
{
public static void main(String[] args)
throws Exception
{
BufferedReader CSVFile =
new BufferedReader(new FileReader("test123.csv"));
int invalidvar = 1;
Scanner input = new Scanner(System.in);
System.out.println("Enter your email");
String email =input.nextLine();
System.out.println("Enter your password");
String password =input.nextLine();
String dataRow = CSVFile.readLine(); // Read first line.
// The while checks to see if the data is null. If
// it is, we've hit the end of the file. If not,
// process the data.
while (dataRow != null)
{
String[] dataArray = dataRow.split("\\t");
if ((dataArray[0].equals(email))
&&(dataArray[1].equals(password)))
{
System.out.println("You email is " +dataArray[0]+".");
System.out.println("You password is " +dataArray[1]+".");
System.out.println("You first name is " +dataArray[2]+".");
System.out.println("You second name is " +dataArray[3]+".");
System.out.println("You street name is " +dataArray[4]+".");
System.out.println("You city name is " +dataArray[5]+".");
System.out.println("You postcode is " +dataArray[6]+".");
}
else
{
System.out.println("Error");
break;
}
dataRow = CSVFile.readLine();
}
// Close the file once all data has been read.
CSVFile.close();
// End the printout with a blank line.
System.out.println();
} //main()
} // CSVRead

You are only checking the first record after the CSV header. You need to continue checking the records until the EOF is reached:
boolean found = false;
while (!found && dataRow != null) {
String[] dataArray = dataRow.split("\\t");
if ((dataArray[0].equals(email)) && (dataArray[1].equals(password))) {
System.out.println("You email is " + dataArray[0] + ".");
...
found = true;
}
dataRow = csvFile.readLine();
}
System.out.println("Result of CSV search: " + found);
Some side notes:
IO Streams should be closed in a finally block.
Java Naming Conventions indicate variables should start with a lowercase letter.

Related

Parsing string generating my generated error message when nothing is entered

I am currently working on an assignment to parse strings and I am running into an issue.
It appears, that if nothing is entered, it is generating my error message I have created when a comma is not inputted.
According to the assignment in zybooks, it should not be outputting anything. Below is my code.
import java.util.Scanner;
public class ParseStrings {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in); // scanner for input
//local variables
String lineString;
String firstWord;
String secondWord;
int commaLocation;
boolean inputDone;
//checks to end the program
inputDone = false;
//keeps the loop running until q is entered
while (!inputDone) {
System.out.println("Enter input string: ");
lineString = scnr.nextLine();
//checks comma
commaLocation = lineString.indexOf(',');
if (commaLocation == -1) {
System.out.println("Error: No comma in string");
}
else {
firstWord = lineString.substring(0, commaLocation);
firstWord = firstWord.replace(" ", "");
secondWord = lineString.substring(commaLocation + 1, lineString.length());
secondWord = secondWord.replace(" ", "");
System.out.println("First word: " + firstWord);
System.out.println("Second word: " + secondWord);
System.out.println();
System.out.println();
}
if (lineString.equals("q")) {
inputDone = true;
}
}
return;
}
}
It happens because when nothing is entered, comma cannot be found, therefore indexOf returns -1.
I would add something like
if (lineString.isEmpty()) {
continue;
}
right after lineString = scnr.nextLine();
EDIT:
I just noticed, that your error message will be printed in case, when your input equals 'q'. I assume this is not an expected behaviour, so I recommend to place
if (lineString.equals("q")) {
inputDone = true;
}
right after assignment of lineString or the if block I suggested above.

Exception in thread ... : null - trying to convert String from file to Integer

like in the title , I'm stuck with this error for a while .I get the value from the file normally but when I try to convert it the error poops out. I read many topics ,but couldn't find any similar case to mine(with file) or any good tips. I tried adding an assert ,but it didn't help. The full description of error is :
Exception in thread "main" java.lang.NumberFormatException: null
at java.base/java.lang.Integer.parseInt(Integer.java:620)
at java.base/java.lang.Integer.parseInt(Integer.java:776)
at EnergyMeasure_needs_to_be_completed.main(EnergyMeasure_needs_to_be_completed.java:85)
Also I'm beginner (but I guess you already know that heh ;))
import java.util.Scanner;
import java.io.*;
public class EnergyMeasure_needs_to_be_completed {
public static void main(String[] args) throws IOException {
//int work_of_energy;
Scanner input = new Scanner(System.in);
System.out.println("\t\t\t\t Hi , this program will count how many kWh you're using");
//asks about number of devices
System.out.println("First of all, how many the same devices do you have in your house ?");
int devices = input.nextInt();
boolean bool = false;
do {
if (devices < 0) {
System.out.println("You can't have less than 0 devices in your home!\nMake input once again :");
devices = input.nextInt();
} else {
System.out.println("Okay, so you've got " + devices + " same devices.");
bool = true;
break;
}
}while(bool = true);
//asks about time of use
System.out.println("\nHow many hours you use them per day?");
int time_use = input.nextInt();
do {
if (time_use > 24 || time_use < 0) {
System.out.println("Wrong!\nMake input once again :");
time_use = input.nextInt();
}
else{
System.out.println("You use your devices for " + time_use + "h");
bool = true;
break;
}
}while(bool = true);
/*else if(!input.hasNextInt()){
System.out.println("Invalid input! \nEnter an integer : ");
time_use = input.nextInt();
} */
//downloads value of power from file
String power_dev; //path to the file
power_dev = null; //reference to one line at a time
try {
FileReader fileReader = //reads text files in the default encoding
new FileReader("power_monitors");
BufferedReader bufferedReader = //deal with a line at a time
new BufferedReader(fileReader);
while((power_dev = bufferedReader.readLine()) != null) {
System.out.println("\nThe power of your devices is " + power_dev + "W");
}
bufferedReader.close(); //close file
}
catch (FileNotFoundException e) { //if file doesn't exist catch the except
System.out.println("Unable to open file");
}
//assert power_dev != null;
int power_dec = Integer.parseInt(power_dev); //change the String ,to Integer
int power_of_devices = power_dec * devices; //summary devices power
//count the cost of work (W = P * t) [kWh]
int work_of_energy = (power_of_devices / 1000) * time_use;
System.out.println("The work of energy equals : " + work_of_energy);
}
}
If you print power_dev, what do you get? What format is it? Because the readLine() returns a textual line, so depending on the source you are reading from, you might get more than an int.
Why not use the read() method? It returns an int, so you wouldn't have to parse power_dev.
Again, hard to answer your question without seeing the file or having a reproductible code, but my best guess is that power_dev returns null or something that can't be parsed by Integer.parseInt() method.

Filtering specific team from text file and displaying results

I want my program to allow a user to enter a team name and based on that name it will distribute the pertinent team information to the console for viewing. So far, the program allows the user to input a text file that contains unformatted team data. It then formats that data, stores it and prints the information to the console. It is at this point in my program where I want the user to be able to start her/his filtering based on a team name. I am not necessarily looking for an exact answer but some helpful tips or suggestions would be appreciated.
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
// Allow the user to enter the name of text file that the data is stored in
System.out.println("This program will try to read data from a text file ");
System.out.print("Enter the file name: ");
String filename = keyboard.nextLine();
System.out.println();
Scanner fileReader = null;
//A list to add results to, so they can be printed out after the parsing has been completed.
ArrayList<LineResult> results = new ArrayList<>();
try {
File Fileobject = new File (filename);
fileReader = new Scanner (Fileobject);
while(fileReader.hasNext()) {
String line = fileReader.nextLine();// Read a line of data from text file
// this if statement helps to skip empty lines
if ("".equals(line)) {
continue;
}
String [] splitArray = line.split(":");
// check to make sure there are 4 parts in splitArray
if(splitArray.length == 4) {
// remove spaces
splitArray[0] = splitArray[0].trim();
splitArray[1] = splitArray[1].trim();
splitArray[2] = splitArray[2].trim();
splitArray[3] = splitArray[3].trim();
//This section checks if each line has any corrupted data
//and then display message to the user.
if("".equals(splitArray[0]))
{
System.out.println(line + " > The home or away team may be missing");
System.out.println();
}else if ("".equals(splitArray[1])) {
System.out.println(line + " > The home or away team may be missing");
System.out.println();
}
try {
// Extract each item into an appropriate variable
LineResult result = new LineResult();
result.homeTeam = splitArray[0];
result.awayTeam = splitArray[1];
result.homeScore = Integer.parseInt(splitArray[2]);
result.awayScore = Integer.parseInt(splitArray[3]);
results.add(result);
} catch(NumberFormatException e) {
System.out.println(line + " > Home team score may not be a valid integer number ");
System.out.println(" or it may be missing");
System.out.println();
}
}else {
System.out.println(line + " > The field delimiter may be missing or ");
System.out.println(" wrong field delimiter is used");
System.out.println();
}
}
System.out.println();
System.out.println();
//Print out results
System.out.println("Home team Score Away team Score");
System.out.println("========= ===== ========= =====");
//Loop through each result printing out the required values.
//TODO: REQ4, filter results based on user requested team
try (BufferedReader br = new BufferedReader(new File(filename));
BufferedWriter bw = new BufferedWriter(new FileWriter("data.txt"))) {
String line;
while ((line = br.readLine()) != null) {
String[] values = line.split(" ");
if (values.length >= 3)
bw.write(values[0] + ' ' + values[1] + ' ' + values[2] + '\n');
}
}
for (LineResult result : results) {
System.out.println(
String.format("%-15s %1s %-15s %1s",
result.homeTeam,
result.homeScore,
result.awayTeam,
result.awayScore));
}
// end of try block
} catch (FileNotFoundException e) {
System.out.println("Error - File does not exist");
System.out.println();
}
}
//Data object for holding a line result
static class LineResult {
String homeTeam, awayTeam;
int homeScore, awayScore;}
}

jump out of recursive function in a loop but let the loop continue

I am trying to read from a text file that have names and phone numbers that can also have other text files in it (including it self)
myBook.txt:
7
name1 123-456-7890
name2 098-765-4321
name3 135-792-4680
name4 246-801-3579
PHONEBOOK-FILE myBook2.txt
name5 147-025-8369
name6 150-263-7495
myBook2.txt:
1
Name7 000-222-3332
The first line is the number of items in the file, then it has PHONEBOOK-FILE to signify another file.
I cannot use arrays, I cannot change myBook.txt, I cannot use try / catch, and I have to use recursion
This is the code I have:
import java.util.*;
import java.io.*;
public class Phonebook
{
private boolean DEBUG = true;
private Scanner scan;
private Scanner input;
private File file;
private File holder;
private String query;
private boolean bottomOut;
private int nameCount;
private String fileNameHold;
// entry point for class
public void run()throws IOException
{
input = new Scanner(System.in);
//Gets file name and checks if it exists valid file
while(true)
{
System.out.print("Name of phone book to read in: ");
fileNameHold = input.next();
file = new File(fileNameHold);
if(file.exists())
break;
else
System.out.println("That file does not exist!");
}
System.out.println("Phonebook successfully read in!");
//Main control loop
while(true)
{
bottomOut = false;
System.out.print("Please enter person to search for: ");
query = input.next();
if(query.equals("."))
break;
file = new File(fileNameHold);
System.out.println(doWork(query, file, 0));
}
System.out.print("Thank you for using this program!");
}
//Does the searching and recursive stuff
private String doWork(String query, File fileName, int level)throws IOException
{
scan = new Scanner(fileName);
//Grabs item count fom begining of file
//if(!bottomOut)
nameCount = Integer.parseInt(scan.nextLine());
String line = "";
//Runs through entries
for(int i=0; i<nameCount; i++)
{
line = scan.nextLine();
debug("file: " +file);
debug("line: " + line);
debug("nameCount: " + nameCount);
if(line.toLowerCase().contains(query.toLowerCase()))
{
return line;
}
//Recursion is used to searth through linked files
else if(line.contains("PHONEBOOK-FILE"))
{
//System.out.println("Sanity Check");
holder = new File(line.replace("PHONEBOOK-FILE ", ""));
if(level < 2 || (level > 0 && bottomOut))
return doWork(query, holder, ++level);
else if(level >= 2 && !bottomOut)
bottomOut = true;
else
return "not found (REC)";
}
}
return "not found";
}
private void debug(String stuff)
{
if(DEBUG)
System.out.println("[[--DEBUG--]] " + stuff);
}
}
I assume the issue is in doWork but I could be wrong. What it is doing is it recurses through the file until it hits a specified bottom where if it hasn't found the name it should break out of the recursion and continue passed the PHONEBOOK-FILE line.
Currently if you search for a name passed that line if returns not found. It doesn't seem to be coming out of the recursion.
As you can probably tell I an not great with this.
Thanks for any help.
For each line in your file, you are going to compute a value. Either not found, or a line of your phonebook. If you get a line, you can break out of the loop. Either way, after the loop you return the value: either the line you got or not found;
What is trickier is how you compute a line which references another phonebook, the answer is that you just call your method with that phonebook. That's the recursion part.
import java.util.*;
import java.io.*;
public class Phonebook
{
private Scanner input;
private File file;
private String query;
// entry point for class
public void run()throws IOException
{
input = new Scanner(System.in);
//Gets file name and checks if it exists valid file
while(true)
{
System.out.print("Name of phone book to read in: ");
fileNameHold = input.next();
file = new File(fileNameHold);
if(file.exists())
break;
else
System.out.println("That file does not exist!");
}
System.out.println("Phonebook successfully read in!");
//Main control loop
while(true)
{
bottomOut = false;
System.out.print("Please enter person to search for: ");
query = input.next();
if(query.equals("."))
break;
file = new File(fileNameHold);
System.out.println(doWork(query, file));
}
System.out.print("Thank you for using this program!");
}
//Does the searching and recursive stuff
private String doWork(String query, File fileName)throws IOException
{
Scanner scan = new Scanner(fileName);
int nameCount;
File recurFile;
nameCount = Integer.parseInt(scan.nextLine());
String line = "";
String value = "Not found";
//Runs through entries
for(int i=0; i<nameCount; i++)
{
line = scan.nextLine();
// if the line is a file, then the value of that line
// is the result to your function applied to that new file
if(line.contains("PHONEBOOK-FILE")) {
recurFile = new File(line.replace("PHONEBOOK-FILE ", ""));
line = doWork(query, holder, ++level);
}
// the file will either return Not found or
// a line corresponding to your query
if(line.toLowerCase().contains(query.toLowerCase()))
{
// Your line is correct. The function doesn't care where it comes from
value = line;
break;
}
}
return value;
}
}

Broken else statement within a while loop

I am currently been working on a program to parse CSV's and then check an inputted email adress against the CSV and if it is valid display their personnel information. The problem I am coming across is the else statement to say that your email is invalid. My current code;
import java.io.*;
import java.util.*;
public class CSVReader123{
public static void main(String[] arg) throws Exception {
BufferedReader CSVFile = new BufferedReader(new FileReader("testa453.csv"));
String dataRow = CSVFile.readLine();
//String email = "ojones#coldmail.net";
//String password = "ocrabc";
Scanner input = new Scanner(System.in);
System.out.println("Please input an email adress");
String email = input.nextLine();
System.out.println("Please input you password");
String password = input.nextLine();
while (dataRow != null){
String[] dataArray = dataRow.split(",");
if ((dataArray[0].equals(email)) && (dataArray[1].equals(password))) {
System.out.println("Your email is valid");
System.out.println("Do you want to display you personel data?(Y or N)");
String personeldata = input.nextLine();
if ((personeldata.equals("yes")) || (personeldata.equals("Yes")) || (personeldata.equals("Y"))){
System.out.println("You email is " +dataArray[0]+".");
System.out.println("You password is " +dataArray[1]+".");
System.out.println("You first name is " +dataArray[2]+".");
System.out.println("You second name is " +dataArray[3]+".");
System.out.println("You street name is " +dataArray[4]+".");
System.out.println("You city name is " +dataArray[5]+".");
System.out.println("You postcode is " +dataArray[6]+".");
}
else if ((personeldata.equals("no")) || (personeldata.equals("No")) || (personeldata.equals("N"))) {
System.out.println("Shutting down.");
break;
}
}
else {
System.out.println("BROKEN");
break;
}
System.out.println();
dataRow = CSVFile.readLine();
}
CSVFile.close();
System.out.println();
}
}
The problem which I am having is that if I try to enter a valid or invalid email it will always print out broken and stop. Although if I remove said if statement the program runs perfectly and the rest of it works correctly. Have I somehow declared it in the incorrect place since the first else statement works perfectly? Any help would be appreciated.
You shouldn't break from the loop. You must use continue, because there can be other rows which will pass the email check. I mean, because the first row does not pass the check, it doesn't mean that the second row won't pass it. You must check all rows.
Make it like this:
else {
System.out.println("BROKEN");
dataRow = CSVFile.readLine();
continue;
}
Or just remove the whole else section like this:
}
//here was the else section
System.out.println();
dataRow = CSVFile.readLine();

Categories

Resources