INPUT FILE VALIDAT DATA - java

I cannot seem to figure out a problem. here is what I'm trying to do open and read the content of a .txt file. If there is a problem with one of the lines of data in the file skip it and continue reading the file
I cannot find a method to skip the line that does not contain a valid value and continue to read the file. Here is my code.
int theValue = 0;
try {
Scanner input = new Scanner(file);
while (input.hasNextLine()) {
String value = input.next();
theValue = Integer.parseInt(value);
}
input.close();
} catch (IllegalArgumentException error) {
System.out.println(error.getMessage());
}
}
thanks for all the help in advance.

Well, maybe not the best idea, but a simple solution would be to encapsulate parseInt in a try/catch:
int theValue = 0;
try {
Scanner input = new Scanner(file);
while (input.hasNextLine()) {
String value = input.next();
try{
theValue = Integer.parseInt(value);
}catch (Exception e){
//Just ignore it and carry on.
}
}
input.close();
} catch (IllegalArgumentException error) {
System.out.println(error.getMessage());
}
}

Related

How to check for duplicate String in a java String array

I am trying to find duplicates values from the first column 0 in array that's been loaded in a string and split, and then throw an exception when this is found.
Here is my code.
public void loadTrueFalseQuestions() throws Exception {
try {
Scanner input = new Scanner(new FileInputStream(TRUE_FALSE_FILE));
while (input.hasNextLine()) {
line = input.nextLine();
String[] split = line.split(",");
int chapterNumber = Integer.parseInt(split[1]);
String correctAnswer = (split[3]);
String questionID = (split[0]);
if (split.length != TRUE_FALSE_FIELDS) {
throw new Exception();
} else if ((!correctAnswer.matches("TRUE")) & (!correctAnswer.matches("FALSE"))) { //throw new Exception();
} else if (true) {
}
}
} catch (FileNotFoundException e) {
System.out.println("Could not open a file.");
System.exit(0);
}
}
This is the CSV file.
TF001,8,Java allows an instance of an abstract class to be instantiated.,FALSE
TF001,8,Downcasting should be used only in situations where it makes sense.,TRUE
TF003,9,The throw operator causes a change in the flow of control.,TRUE
TF004,9,When an exception is thrown the code in the surrounding try block continues executing
and then the catch block begins execution.,FALSE
I'm not sure how to go about it. I cannot get past the logic. I'm trying an if statement and contains(questionID) string method, but not sure how to combine these two. (if that makes sense).
Appreciate any advice.
I use a hash map and put the key field as the key in the hash map. You can check if you already put the key in the hash and if so do something because you already have it.
public void loadTrueFalseQuestions() throws Exception {
try {
Scanner input = new Scanner(new FileInputStream(TRUE_FALSE_FILE));
Map<String, String> myHash = new HashMap<>();
while (input.hasNextLine()) {
line = input.nextLine();
String[] split = line.split(",");
int chapterNumber = Integer.parseInt(split[1]);
String correctAnswer = (split[3]);
String questionID = (split[0]);
if (myHash.containsKey(questionID)) {
// what to do here?
} else {
myHash.put(questionID, line);
}
}
} catch (FileNotFoundException e) {
System.out.println("Could not open a file.");
System.exit(0);
}
}

Return array initialized inside try/catch

I am creating a program which creates reads a file into an array separating which file into a different index value in the array.
static String[] readFile () {
int count = 0;
try {
File file = new File("input.txt"); // create file
Scanner scanner = new Scanner(file); // create scanner associated to file
// counts number of lines
while (scanner.hasNextLine()) {
scanner.nextLine();
count++;
}
// reads file into array
while (scanner.hasNextLine()) {
String[] data = new String[count];
int len = data.length;
for (int i = 0; i <= len; i++) {
data[i] = scanner.nextLine();
}
}
} catch (Exception e) {
System.out.println("File not found!!!");
System.exit(0);
}
return data;
}
The problem is that when trying to return the variable data I get an error saying 'cannot resolve symbol data" because it is initialized in a try-catch block. I have tried doing this but it returns the value null because the variable's length is determined by the variable count whose's value is also determined in a catch block. Thanks in advance!
You can use #Sweeper advice from comments. It will be looks like this.
static ArrayList<String> readFile () {
ArrayList<String> data = new ArrayList<>();
try {
File file = new File("input.txt"); // create file
Scanner scanner = new Scanner(file); // create scanner associated to file
while (scanner.hasNextLine()) {
data.add(scanner.nextLine()) ;
}
} catch (Exception e) {
e.printStackTrace();
}
return data;
}
But if you want to stay with your current code, you can initialize data by null out of try block. And also you need to reset Scanner. Your code will be looking something like this. Note, that in the for loop you must use condition <len not <=len.
static String[] readFile () {
String[] data = null;
try {
File file = new File("input.txt"); // create file
Scanner scanner = new Scanner(file); // create scanner associated to file
// counts number of lines
int count = 0;
while (scanner.hasNextLine()) {
scanner.nextLine();
count++;
}
scanner.close(); // don't forget about closing resources
data = new String[count];
// reads file into array
scanner = new Scanner(file);
for (int i = 0; i < len; i++) {
data[i] = scanner.nextLine();
}
scanner.close();
} catch (Exception e) {
e.printStackTrace();
}
return data;
}
Here are some similar questions with answers:
Java: Reading a file into an array
Read text file into an array
Also, I want to point at the try-with-resources statement - the Scanner object should be closed or initialized inside it.
Additionally, System.exit(0); is not a good way to stop a method, because all finally blocks around it wouldn't be executed in this case.
you are having 2 problems the firsthappens because the variable data is declared in the try-catch block ¿what if an instruction throws an exeption and the variable data is never declared? in this case ¿what is going to be returned?, the solution is to declare the variable data before the try-catch block, the second happens because when you invoke nextLine() the Scanner object mantains its state so when you try to invoke nextLine() again after go through the whole file it is in the last line (there is not next line), you can solve it invoking close() and then initialize the scanner object again this will reset the state:
static String[] readFile () {
Scanner scanner = null;
int count = 0;
String[] data = null;
try {
File file = new File("C:\\Users\\Mulé\\Desktop\\doc.txt"); // create file
scanner = new Scanner(file); // create scanner associated to file
// counts number of lines
while (scanner.hasNextLine()) {
scanner.nextLine();
count++;
}
scanner.close();
scanner = new Scanner(file);
// reads file into array
data = new String[count];
for (int i = 0; i < data.length; i++) {
data[i] = scanner.nextLine();
}
} catch (Exception e) {
System.out.println("File not found!!!");
System.exit(0);
}
return data;
}

Do-while loop not paying attention to the while in java

I'm trying to write a do while loop that will read a file that the user input and read it out and will loop until the user types end. The do part is working, but my while just isn't being activated and I'm struggling to figure out why.
public static void readingFiles() throws Exception {
BufferedReader reader = null;
Scanner input = null;
boolean fileFound = true;
do {
System.out.print("Enter a file name or Type END to exit: ");
input = new Scanner(System.in);
if(input.hasNextLine())
{
try {
File f = new File(input.nextLine());
reader = new BufferedReader(new FileReader(f));
String str = null;
while((str = reader.readLine()) != null)
{
System.out.println(str);
}
}
catch (FileNotFoundException e)
{
System.out.println("File Not Found. Please try again.");
fileFound = false;
continue;
}
catch (IOException e)
{
System.out.println("There was an IOException. Please try again.");
continue;
}
catch (Exception e)
{
System.out.println("There was an exception. Please try again.");
continue;
}
finally
{
{
if(fileFound)
reader.close();
}
}
}
} while(!input.nextLine().equalsIgnoreCase("end"));
}
I've tried using an if statement before my input.hasNextLine() but then it would ignore the rest of the whole program and do nothing and only typing end would work. I've tried using && in my current if statement too but that didn't work. And I tried using a boolean that I set to true if string contained end. I think the problem may be in the input.hasNextLine but I'm not sure why or what to change it to?
Thanks for any help
Calling input.nextLine() again will not preserve your previous input string.
Store it in a variable, and compare that
public static void readingFiles() throws Exception {
BufferedReader reader = null;
String filename = null;
Scanner input = new Scanner(System.in);
boolean fileFound = true;
do {
System.out.print("Enter a file name or Type END to exit: ");
if(input.hasNextLine()) {
filename = input.nextLine();
try {
File f = new File(filename);
// reader =
...
} while (!filename.equalsIgnoreCase("end");

Using try/catch for files in java

I'm having issues with using try-catch blocks in java. I'm writing a method that reads a user input file and prints it out to the console. This is what I have -
static Scanner input = new Scanner(System.in);
public static String readingFiles(String fileout) {
boolean find = false;
while(!find) {
try {
File f = new File(input.nextLine());
Scanner scan = new Scanner(f);
} catch (FileNotFoundException e) {
System.out.println("File Not Found.");
}
}
ArrayList<String> list = new ArrayList<String>();
while (input.hasNext())
{
list.add(input.nextLine());
}
String output = list.toString();
return output;
}
It just seems like a mess and I have no idea what to do with it at this point. I had it working a few times, in that it would output what the file said but then if I purposefully entered the wrong file name it would loop "file not found" endlessly and I couldn't figure out how to return the loop to the beginning so the user could input a different file name.
Now it just does nothing even when i enter the correct file name, it returns nothing until i press enter again and it'll return file not found.
I call it using this in my main menu method -
case 1:
System.out.println("You chose Read File. Enter your file name: ");
System.out.println(Question4.readingFiles(input.nextLine()));
pressEnter();
break;
edit: I now have this, which works but only prints the first line of my file?
public static String readingFiles(String fileout) {
boolean find = false;
String result = "";
while (!find) {
try {
File read = new File(fileout);
Scanner check = new Scanner(read);
result = check.nextLine();
find = true;
check.close();
} catch (FileNotFoundException e) {
System.out.println("File Not Found. Please try again.");
break;
}
}
return result;
}
Check the following code.
public static void readFiles() throws Exception {
int i = 1;
BufferedReader reader = null;
Scanner input = null;
boolean fileFound = true;
while(i <= 5){
System.out.print("Enter a file name::::");
input = new Scanner(System.in);
if(input.hasNextLine()){
try {
File f = new File(input.nextLine());
reader = new BufferedReader(new FileReader(f));
String str = null;
while((str = reader.readLine()) != null){
System.out.println(str);
}
} catch (FileNotFoundException e) {
System.out.println("File Not Found");
fileFound = false;
i++;
continue;
} catch (IOException e) {
System.out.println("IOException");
i++;
continue;
} catch (Exception e) {
System.out.println("Some Other Exception");
i++;
continue;
} finally{
if(fileFound)
reader.close();
}
}
i++;
}
}
Please note this method will read files 5 times. If you want to change it, you can pass an int parameter to the method and accordingly change the first while condition. Ensure you give complete path of the file with escape characters. For example, if file location is 'C:\abc.txt', you need to input 'C:\\abc.txt'. Else, it will display 'File Not Found' in console.
public class readingFiles {
public static String readingFiles(String fileout) {
try {
//find a file with the same name as the value of "fileout"
File f = new File(fileout);
Scanner scan = new Scanner(f);
//create a list to hold the file output
ArrayList<String> list = new ArrayList<String>();
//loop through the output line by line and add to the list
while (scan.hasNext())
{
list.add(scan.nextLine());
}
//convert the list into a String value to pass back to the caller
String output = list.toString();
scan.close();
return output;
} catch (FileNotFoundException e) {
//if file is not found, return a value of -1
System.out.println("File Not Found.");
return("-1");
}
}
Okay a few things:
Your first while loop is unnecessary. I think you are trying to loop through files in the folder to look for a specific file name. However the Scanner scan = new Scanner(f); line already does this.
The reason your code infinitely prints "File not found." is because you never set the find condition to true to exit the loop.
You never use the fileout value you pass into the method. And your code asks the user for the filename input twice (once in the main method, once in the readingFiles method).
Using a list, then converting to String results in an output of [line1, line2, line3, etc] not sure if this is what you want.
As for why your second attempt prints only the first line, You have removed the while loop which loops through the file reading every line, therefore it only reads one line before stopping.

variable can not be found after try block

I am trying to process text from a user entered file when compiled the scanner in cannot be found. I am assuming it is being caught. what can I do to make this work?
String namef = getf.nextLine();
File inPut = new File(namef);
try {
Scanner in = new Scanner(inPut);
}
catch (FileNotFoundException e) {
System.out.println("file not found");
}
while(in.hasNextLine()) { // process file
String line = in.nextLine();
String pLine = parse(count, namef);
}
#Tom is right. You must declare the scanner outside the try block.
String namef = getf.nextLine();
Scanner in = new Scanner();
File inPut = new File(namef);
try
{
in = new Scanner(inPut);
while(in.hasNextLine()) // process file
{
String line = in.nextLine();
String pLine = parse(count, namef);
}
}
catch (FileNotFoundException e)
{
System.out.println("file not found");
}

Categories