I created a java file called Product.java. I also created a text file called Items.txt. Basically when the user enter the word using sequential search to search the data what they are looking from Items.txt. My main problem is when I enter 3 to display all the records or enter x to exit the program, it keeps on looping. But I don't how to resolve this problem. Can anyone solved this for me?
Items.txt
1000|Cream of Wheat|Normal Size|Breakfast|NTUC|5|3.00
1001|Ayam Brand|Small Size|Canned|NTUC|4|4.00
Product.java
import java.io.*;
import java.util.*;
public class Product {
public static void main(String[] args) {
ArrayList<Item> prdct = new ArrayList<Item>();
String inFile = "items.txt";
String line = "";
FileReader fr = null;
BufferedReader br = null;
StringTokenizer tokenizer;
int quantity;
String id, brandname, desc, category, supplier;
float price;
try{
fr = new FileReader(inFile);
br = new BufferedReader(fr);
line = br.readLine();
while(line!=null)
{
tokenizer = new StringTokenizer(line,"|");
id = tokenizer.nextToken();
brandname = tokenizer.nextToken();
desc = tokenizer.nextToken();
category = tokenizer.nextToken();
supplier = tokenizer.nextToken();
quantity = Integer.parseInt(tokenizer.nextToken());
price = Float.parseFloat(tokenizer.nextToken());
Item itm = new Item(id,brandname,desc,category,supplier,quantity,price);
prdct.add(itm);
line = br.readLine();
}
br.close();
}
catch(FileNotFoundException e){
System.out.println("The file " + inFile + " was not found.");
}
catch(IOException e){
System.out.println("Reading error!");
}
finally
{
if (fr!=null){
try
{
fr.close();
}
catch(IOException e)
{
System.out.println("Error closing file!");
}
}
}
String INPUT_PROMPT = "\nPlease enter 3 to display all records, 4 to insert record, 5 to remove old records " + "or enter 'x' to quit.";
System.out.println(INPUT_PROMPT);
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader (System.in));
line = reader.readLine();
while(reader != null)
{
for(int i=0; i<prdct.size(); i++)
{
if(prdct.get(i).id.contains(line) || prdct.get(i).brandname.contains(line) || prdct.get(i).desc.contains(line)
|| prdct.get(i).category.contains(line) || prdct.get(i).supplier.contains(line))
{
System.out.println(prdct.get(i));
}
System.out.println(INPUT_PROMPT);
line = reader.readLine();
}
}
while("3".equals(line))
{
for(int i=0; i<prdct.size(); i++)
{
System.out.println(prdct.get(i));
}
System.out.println(INPUT_PROMPT);
line = reader.readLine();
}
while(!line.equals("x"))
{
System.out.println(INPUT_PROMPT);
line=reader.readLine();
}
}
catch(Exception e){
System.out.println("Input Error!");
}
}
}
The problem is with this loop:
while(reader != null)
{
for(int i=0; i<prdct.size(); i++)
{
if(prdct.get(i).id.contains(line) || prdct.get(i).brandname.contains(line) || prdct.get(i).desc.contains(line)
|| prdct.get(i).category.contains(line) || prdct.get(i).supplier.contains(line))
{
System.out.println(prdct.get(i));
}
System.out.println(INPUT_PROMPT);
line = reader.readLine();
}
}
It keeps on looping while reader is not null and it will never be. You might want to try checking something else that suits your problem better, maybe:
While(!line.equals("3"))
While(!line.equals("x"))
While(line != null)
Otherwise, even if there is an 'x', '3' or simply nothing, still (reader != null) and therefore the loop is infinite.
I suspect that the newline character is what causes the comparison to fail.
Instead of checking if:
"3".equals(line)
Try:
"3".equals(line.trim())
Same applies to the following comparison.
Try changing this..
line = reader.readLine();
while(reader != null)
{
to this..
line = reader.readLine();
while(line != null)
{
You are looping on the reader being not null, which it always will be.
you have to define these functions:
public void showAllRecords() {
// show all record here
}
public void insertRecord() {
// insert record here
}
public void removeRecord() {
// insert record here
}
public void exit() {
// insert record here
}
then
do{
System.out.println(INPUT_PROMPT);
switch(line)
{
case "3":
showAllRecords();
break;
case "4":
insertRecord();
break;
case "5":
removeRecord();
}
}while(!line.equals('x'));
Related
So I'm trying to use a BufferedReader to split a text file into 2 different arrays, I've written some code but I'm not sure where to go from here.
I know how to populate an array, but i just cant seem to get the specific lines.
So, one array for NEW_OFFICE containing only the numbers, and one for MAIN_ADDRESS containing only the numbers below it.
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("myDelivery.txt"));
String read = null;
while ((read = in.readLine()) != null) {
String words = read.split("NEW_OFFICE")[0];
}
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
in.close();
} catch (Exception ignored) { }
}
This is the text file:
NEW_OFFICE
-92.48392883 52.96531732
-2.483984994 92.48392883
MAIN_ADDRESS
-1.207614869 52.98908196
NEW_OFFICE always is the first line, and always has two lines below
it, the same goes for MAIN_ADDRESS it always has one line below it.
NEW_OFFICE & MAIN_ADDRESS can't appear more than once.
Based on your comment mentioned above, given below is the solution:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws IOException {
String[][] office = new String[2][2];
String[][] main = new String[1][2];
try (BufferedReader in = new BufferedReader(new FileReader("myDelivery.txt"))) {
String read;
while ((read = in.readLine()) != null) {
if (read.equalsIgnoreCase("NEW_OFFICE")) {
// Read next two lines
for (int i = 0; i < 2; i++) {
if ((read = in.readLine()) != null) {
office[i] = read.split("\\s+");
}
}
} else if (read.equalsIgnoreCase("MAIN_ADDRESS")) {
// Read next line
if ((read = in.readLine()) != null) {
main[0] = read.split("\\s+");
}
}
}
}
// Display office[][]
System.out.println("Displaying office:");
for (String[] officeData : office) {
System.out.println(Arrays.toString(officeData));
}
// Display main[][]
System.out.println("Displaying main:");
for (String[] mainData : main) {
System.out.println(Arrays.toString(mainData));
}
}
}
Output:
Displaying office:
[-92.48392883, 52.96531732]
[-2.483984994, 92.48392883]
Displaying main:
[-1.207614869, 52.98908196]
Notes:
\\s+ is for splitting the line on space(s).
Use try-with-resources syntax to simplify your code.
.split() does take a string, but it should be a regex, not the substring that you want to split it on. You want to change your code like this:
try (BufferedReader in = new BufferedReader(new FileReader("x.txt"))) {
String read;
String office = "";
while ((read = in.readLine()) != null) {
if (read.contains("NEW_OFFICE")) {
office = "NEW_OFFICE";
} else if (read.contains("MAIN_ADDRESS")) {
office = "MAIN_ADDRESS";
} else {
System.out.println(office + " : " + read);
}
}
} catch (IOException e) {
e.printStackTrace();
}
I have also changed your try with try-with-resources so you don't have to worry about closing the resource.
I´d go with somethin like this.
Please be aware that I don´t have an IDE right now so this is basically pseudo code:
try (BufferedReader in = new BufferedReader(new FileReader("x.txt"))) {
String line = null;
boolean isOffice = false;
ArrayList<double> officeInts = new ArrayList<double>();
ArrayList<double> addressInts = new ArrayList<double>();
while ((line = in.readLine()) != null) {
if (line.contains("NEW_OFFICE")) {
isOffice = true;
continue;
} else if (line.contains("MAIN_ADDRESS")) {
isOffice = false;
continue;
}
for(String s : line.split(" "){
double num = Double.parseDouble(s);
if(isOffice) {
officeInts.add(num);
} else {
addressInts.add(num);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
I am trying to sort a list of user entered tasks and dates by date using comparable interface. I have the tasks in a external .txt file and am a little confused if I am accessing the correct variables. The program compiles, but when I try to sort the tasks, it seems to erase the contents of the file. Here is what I have:
public class DueDate implements Comparable<DueDate>{
public String addedTask = "";
public String enteredDueDate;
public DueDate(String addedTask, String dueDate){
this.addedTask = addedTask;
this.enteredDueDate = enteredDueDate;
}
public String toString(){
return addedTask+"\t"+enteredDueDate+"\t";
}
#Override
public int compareTo(DueDate o) {
return this.enteredDueDate.compareTo(o.enteredDueDate);
}
}
public class Main {
public static String fileName = "/Users/eringray/Desktop/tasklistjava/src/javatask.txt";
public static void main(String[] args) throws IOException {
int menuItem = -1;
while(menuItem != 0){
menuItem = menu();
switch (menuItem){
case 1:
showTaskList();
break;
case 2:
addTask();
break;
case 3:
sortList();
case 4:
deleteTasks();
break;
case 0:
break;
default:
System.out.println("Invalid Input");
}
}
}
static int menu(){
int choice;
Scanner sc = new Scanner(System.in);
System.out.println("\n Task List Menu \n");
System.out.println("0: Exit Menu");
System.out.println("1: Show Tasks in List");
System.out.println("2: Add Task to List");
System.out.println("3: Sort Tasks by Due Date");
System.out.println("4: Delete Tasks");
System.out.println();
System.out.println("Enter a choice: ");
choice = sc.nextInt();
return choice;
}
static void showTaskList(){
System.out.println("\nTask List\n");
try {
Scanner inFile = new Scanner(new FileReader(fileName));
String line;
int number = 1;
while(inFile.hasNextLine()){
line = inFile.nextLine();
System.out.println(number + ". " + line);
++number;
}
System.out.println();
inFile.close();
} catch (FileNotFoundException ioe) {
System.out.println(ioe);
}
}
static void addTask(){
System.out.println("\nAdd Task\n");
try {
Scanner input = new Scanner(System.in);
PrintWriter outFile = new PrintWriter(new FileWriter(fileName, true));
System.out.println("Enter a Task: ");
String addedTask = input.nextLine();
System.out.println("Set Due Date for this Task(yyyy-mm-dd): ");
String dueDate = input.nextLine();
outFile.println(addedTask + "\t" + dueDate);
outFile.close();
} catch (IOException ioe) {
System.out.println(ioe);
}
}
static void sortList() throws IOException {
System.out.println("\nSorted List\n");
try {
BufferedReader br = new BufferedReader(new FileReader(fileName));
BufferedWriter bw = new BufferedWriter(new FileWriter(fileName, true));
ArrayList<DueDate> tasks = new ArrayList<DueDate>();
String line = "";
while((line = br.readLine()) != null) {
String[] values = line.split("\t");
if(values.length == 2) {
String addedTask = values[0];
String enteredDueDate = values[1];
DueDate d = new DueDate(addedTask, enteredDueDate);
tasks.add(d);
}
}
Collections.sort(tasks);
for(int i = 0; i < tasks.size(); i++){
DueDate date = tasks.get(i);
String lineText = date.toString();
bw.write(lineText);
bw.newLine();
}
br.close();
bw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private static void deleteTasks(){
PrintWriter writer = null;
try {
writer = new PrintWriter(fileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
assert writer != null;
writer.print("");
writer.close();
}
}
Sorry for the extra code, but thought it might help you see what I'm trying to do. Any suggestions would be great. I am new to Java, so please be patient with me! Thanks!
The problem is a missing break statement in your switch which is calling the deleteTasks() method after calling sortList(). Change your code to this and it should work fine:
int menuItem = -1;
while(menuItem != 0){
menuItem = menu();
switch (menuItem){
case 1:
showTaskList();
break;
case 2:
addTask();
break;
case 3:
sortList();
break; //The missing break
case 4:
deleteTasks();
break;
case 0:
break;
default:
System.out.println("Invalid Input");
}
}
And the constructor of the DueDate class is missing the assignment of the enteredDueDate variable since the parameter was named dueDate and not enteredDueDate. You should change it to something like this:
public DueDate(String addedTask, String enteredDueDate){
this.addedTask = addedTask;
this.enteredDueDate = enteredDueDate;
}
since you are currently assigning the member variable to it's own value.
You should also consider changing the sortList method, especially the BufferedWriter or it will duplicate the list each time you call it. Something like this sould do it:
BufferedReader br = new BufferedReader(new FileReader(fileName));
ArrayList<DueDate> tasks = new ArrayList<DueDate>();
String line = "";
while((line = br.readLine()) != null) {
String[] values = line.split("\t");
if(values.length == 2) {
String addedTask = values[0];
String enteredDueDate = values[1];
DueDate d = new DueDate(addedTask, enteredDueDate);
tasks.add(d);
}
}
Collections.sort(tasks);
br.close();
//Changed it to not append but overwrite the old file so it only contains the sorted list
BufferedWriter bw = new BufferedWriter(new FileWriter(fileName, false));
for (DueDate date : tasks) {
String lineText = date.toString();
bw.write(lineText);
bw.newLine();
}
bw.flush();
bw.close();
EDIT:To print the sorted list out there are a few things you could do.
The easiest way would probably be to append a call of the showTaskList method to the end of the sortList method like this
//...
bw.flush();
bw.close();
showTaskList();
} catch (FileNotFoundE
e.printStackTrace(
}
or you could loop through the ArrayList and print them out like this:
//...
bw.flush();
bw.close();
for (int i = 0; i < tasks.size(); i++) {
DueDate dueDate = tasks.get(i);
System.out.println(i+". "+dueDate.toString());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
EDIT 2: The easiest way to get all Tasks with empty DueDate to the bottom when sorting is to change the compareTo method in DueDate class:
#Override
public int compareTo(DueDate o) {
return -this.enteredDueDate.compareTo(o.enteredDueDate);
}
Just negate it so all entries are sorted descending and those with empty DueDate will be at the end of the list (it relays on how strings are compared by default).
But if you want to use Tasks with no due date you'll run into a problem in your sortList method since the split("\t")method will only return an array with length 1 and your if condition would fail. One way to solve it looks like this:
//...
while ((line = br.readLine()) != null) {
String[] values = line.split("\t");
//To ensure it's still valid data
if (values.length >= 1 && values.length <= 2) {
String addedTask = values[0];
String enteredDueDate;
//Check whether dueDate has a value or is empty
if (values.length == 1)
enteredDueDate = "";
else
enteredDueDate = values[1];
DueDate d = new DueDate(addedTask, enteredDueDate);
tasks.add(d);
}
}
//...
or more compact version (does exactly the same thing)
//...
while ((line = br.readLine()) != null) {
String[] values = line.split("\t");
if (values.length >= 1 && values.length <= 2)
tasks.add(new DueDate(values[0], values.length == 1 ? "" : values[1]));
}
//...
Hope this helps (:
This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 7 years ago.
EDIT: While this issue has been marked as a duplicate, the other issue is different to my situation; it seems as though the program is ignoring this line:
decision = scan.nextInt();
I'm having some trouble with my scanner. I have a program that runs off a simple menu system.
The program works, but whenever it goes back to repeating the program again (I made the program have the ability to repeat by putting it in a while loop) it throws this error:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:919)
at java.util.Scanner.next(Scanner.java:1542)
at java.util.Scanner.nextInt(Scanner.java:2172)
at java.util.Scanner.nextInt(Scanner.java:2131)
at GuardSearch.Menu(GuardSearch.java:29)
at GuardSearch.main(GuardSearch.java:8)
The program all works on the first run through the menu and its actions, but then when the call of the if statement is completed and the program returns to the while loop, it throws this exception. What am I missing?
I can post all the classes of the program if needed, however I believe my problem is within the following class:
import java.util.Scanner;
import java.lang.*;
public class GuardSearch {
public static void main(String[] args) {
Menu();
}
public static void Menu(){
Scanner scan = new Scanner(System.in);
boolean leave = false;
while(leave!=true){
final String ANSI_CLS = "\u001b[2J";
final String ANSI_HOME = "\u001b[H";
System.out.print(ANSI_CLS + ANSI_HOME);
System.out.flush();
int decision = 0;
System.out.println("Welcome to GuardSearch, our little slice of Google.\n");
while ((decision != 1) || (decision != 2)){
System.out.println("Please enter the number of what you would like to do from the following list:");
System.out.println("1. Submit knowledge.");
System.out.println("2. Search.");
System.out.println("3. Quit.");
decision = scan.nextInt();
if (decision == 1) {
Submit submit = new Submit();
submit.takeinfo();
break;
}
else if (decision == 2){
Search search = new Search();
search.takekeywords();
break;
}
else if (decision == 3){
leave = true;
break;
}
}
}
scan.close();
}
}
Thanks in advance. I have researched this issue and found no occurrences relevant to my exact issue.
EDIT: Here is my Submit and Search class as requested:
import java.io.*;
import java.util.Scanner;
public class Submit {
public static void takeinfo() {
final String ANSI_CLS = "\u001b[2J";
final String ANSI_HOME = "\u001b[H";
System.out.print(ANSI_CLS + ANSI_HOME);
System.out.flush();
System.out.println("Submit your knowledge to the system.\n");
Scanner sc = new Scanner(System.in);
int decision = 0;
while ((decision != 1) || (decision != 2)){
System.out.println("1. Change an existing article.");
System.out.println("2. Create a new article.");
System.out.println("3. Delete an article.");
System.out.println("4. Back.");
decision = sc.nextInt();
if (decision == 1) {
ChangeArticle chngArt = new ChangeArticle();
chngArt.takeinfo();
break;
}
else if (decision == 2){
CreateArticle createArt = new CreateArticle();
createArt.title();
break;
}
else if (decision == 3){
DeleteArticle deleteArt = new DeleteArticle();
deleteArt.takeinfo();
break;
}
else if (decision == 4){
GuardSearch gs = new GuardSearch();
gs.Menu();
break;
}
else {
System.out.println("Please enter a valid number.\n");
}
}
sc.close();
}
}
And the Search class:
import java.util.*;
import java.io.*;
public class Search {
Scanner sc = new Scanner(System.in);
public void takekeywords() {
final String ANSI_CLS = "\u001b[2J";
final String ANSI_HOME = "\u001b[H";
System.out.print(ANSI_CLS + ANSI_HOME);
System.out.flush();
System.out.println("Search the system.\n");
boolean fin = false;
int dec;
while (fin != true){
System.out.println("Please select which search type you want:\n");
System.out.println("1. Keywords.");
System.out.println("2. Category listing.");
System.out.println("3. Back\n");
dec = sc.nextInt();
if (dec == 1) {
// Do a keyword thing
fin = true;
}
else if (dec == 2) {
// Do a category thing
searchCategories();
fin = true;
}
else if (dec == 3) {
GuardSearch gs = new GuardSearch();
gs.Menu();
break;
}
}
}
public void searchCategories(){
// Create an empty list of subcategories, that will be added to when the user wants to add sub categories
LinkedList<Category> newSubCategories = new LinkedList<Category>();
// Create a list of .txt's relevant to the category
LinkedList<String> relevantArticles = new LinkedList<String>();
relevantArticles.add("example.txt");
LinkedList<String> dirListing = new LinkedList<String>();
//System.out.println("Please select your category:\n");
String s = "Example Category";
// Create the first category, passing in its name, an empty list of subCategories (which are of type Category), and a list of .txt's relevant to the category
Category firstCategory = new Category(s, newSubCategories, relevantArticles);
File wd = new File("/bin");
Process proc = null;
try {
proc = Runtime.getRuntime().exec("/bin/bash", null, wd);
}
catch (IOException e) {
e.printStackTrace();
}
if (proc != null) {
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
out.println("cd /var/tmp/cholland/GuardSearch/");
out.println("ls *.art");
out.println("exit");
String line;
System.out.println();
try {
int x = 1;
while ((line = in.readLine()) != null) {
System.out.println(x + ") " + line);
dirListing.add(line);
x++;
}
System.out.println("Please select the article you want:\n");
int dec = sc.nextInt();
//System.out.println(Arrays.toString(dirListing.toArray()));
System.out.println(dirListing.size());
try {
for (int y=1; y<=dirListing.size(); y++) {
if (y == dec){
boolean fin = false;
while (fin != true){
System.out.println("You chose: " + (dirListing.get(boundIndex(y))) + ". Opening file...");
System.out.println("===========================================================\n");
String text;
String filepath = ("/var/tmp/cholland/GuardSearch/" + (dirListing.get(boundIndex(y))));
BufferedReader br = null;
StringBuffer contents = new StringBuffer();
try {
br = new BufferedReader(new FileReader(filepath));
text = null;
while ((text = br.readLine()) != null) {
contents.append(text).append(System.getProperty("line.separator"));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
text = (contents.toString());
System.out.println(text);
System.out.println("\n===========================================================\n");
fin = true;
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
proc.waitFor();
out.close();
in.close();
proc.destroy();
}
catch (Exception e) {
e.printStackTrace();
}
}
sc.close();
}
public int boundIndex(int x){
if (x != 0){
return (x - 1);
}
else {
return 0;
}
}
}
I think the problem is here decision = scan.nextInt();
NoSuchElementException will be thrown if no more tokens are available. This is caused by invoking nextInt() without checking if there's any integer available. You can hasNextInt() to check if any more tokens are available.
Something like:
if(scan.hasNextInt() )
decision = scan.nextInt(); // if there is another number
else
decision = 0; // nothing added in the input
The cause of the error is that you are closing the scanner at the end of searchCategories.
I have written code of dictionary in java in which i read data from file named newFile.txt .In file world is placed on one line and its meaning is placed on nextline. User enters a world. If word is found in file it shows its meaning placed on next line and if word is not found it shows similar words (substrings).
"While searching word it should not search meaning."
import java.io.*;
import java.util.*;
public class Notepad {
public static void main(String []args) throws IOException{
BufferedReader in = null;
Scanner input = new Scanner(System.in);
String str;
boolean notfound = false;
char again = 'a';
try{
do{
notfound = false;
System.out.println("Enter word :");
str = input.next();
File f = new File("D:\\newFile.txt");
in = new BufferedReader(new FileReader(f));
String s;
while((s = in.readLine()) != null){
int x = s.indexOf(str);
if(x != -1){
int lens = s.length();
String sub = s.substring(x);
int lensub = str.length();
if(lens == lensub){
System.out.println((in.readLine()));
break;
}
else{
System.out.println(sub) ;
notfound = true;
}
}
s = in.readLine();
}
if(!notfound){
System.out.println("Try another world?(y/n):");
again = input.next().trim().charAt(0);
again = Character.toLowerCase(again);
}
}
while(notfound || again == 'y');
System.out.println("terminated!");
}
finally{
if(in != null){
in.close();
}
}
}
}
when i enters a substring of a word it searches meaning as well and then if a enter right word it does not show meaning
//This code is reading a file that is situated like this:
Hello - to greet
Circle - a round shape
//Then the code can be done like so, is this ok?
public static void main(String []args) throws IOException{
BufferedReader in = null;
Scanner input = new Scanner(System.in);
String str;
boolean notfound = false;
char again = 'a';
try{
do{
notfound = false;
System.out.println("Enter word :");
str = input.next();
File f = new File("/Folder/demo1.txt");
in = new BufferedReader(new FileReader(f));
String s;
while((s = in.readLine()) != null){
int x = s.indexOf(str);
// System.out.println("Index of dash:" + s.indexOf("-"));
// System.out.println("Index of Hello:" + x);
if(x != -1 && x<s.indexOf("-")){
String sub = s.substring(0,s.indexOf("-"));
System.out.println("Sub:" + sub);
System.out.println("Str:" + str);
if(sub.trim().equals(str.trim())){
System.out.println("Success:" +sub);
notfound = true;
break;
}
else{
System.out.println("Word is not present") ;
notfound = false;
break;
}
}
}
if(!notfound){
System.out.println("Try another word?(y/n):");
again = input.next().trim().charAt(0);
again = Character.toLowerCase(again);
}
}
while(notfound || again == 'y');
System.out.println("terminated!");
}
finally{
if(in != null){
in.close();
}
}
}
}
I've written a program that reads in a text file to show football scores, now the text file is arranged so that it has errors included and I'm trying to write a program to count these errors. The text file is arranged like so:
Hull City : Sunderland : 2 : 3
Chelsea : Manchester City :1
Fulham : Leeds United : 1 : 2
Wigan : Tottenham : 1 : x
: :2:0
So the above has missing team names, missing scores and some scores replaced with an X. I can't for the life of me figure out how to introduce a counter to count the number of errors, any idea on a starting point/solution would be much appreciated, thanks!
Here is my full code:
Main:
public class main {
public static void main(String[] args) {
String userInput;
readFile readScores = new readFile();
do
{
userInput = readScores.getUserInput();
if(userInput.equalsIgnoreCase("S"))
readScores.printScores();
readScores.totalGoals();
readScores.errorCount();
} while (!userInput.equalsIgnoreCase("E"));
System.out.println("****************Exiting application****************");
System.exit(0);
}
}
Readfile Class:
public class readFile {
String [] stringArr;
Scanner scan = new Scanner(System.in);
public String getUserInput()
{
String userInput;
System.out.println("Select your option:\nS - Show Scores \nE - Exit");
userInput = scan.nextLine();
return (userInput);
}
public void printScores()
{
String sep = ":";
File inputfile = new File ("P:/SD/Assignment1/results2.txt");
String line = "";
try {
Scanner filescan = new Scanner(inputfile);
while(filescan.hasNext())
{
line = filescan.nextLine();
stringArr = line.split(sep);
if(stringArr.length == 4)
{
System.out.println(stringArr[0]+"\t [" +stringArr[2]+"]\t|" + stringArr[1]+"\t["+ stringArr[3]+" ]\n");
}
else
{
throw new IllegalArgumentException("String " + line + " does not contain " + sep);
}
}
filescan.close();
}
catch (FileNotFoundException e)
{
System.out.println("problem " +e.getMessage());
}
}
public void totalGoals()
{
int[] num = new int[stringArr.length];
int count = 0;
for (int i = 0; i<stringArr.length; i++)
{
System.out.println(stringArr[i]);
num[i] = Integer.parseInt(stringArr[i]);
count = count + num[i];
System.out.println(count);
}
}
public void errorCount()
{
String line;
int errorCount=0;
String[] strArr;
try
{
BufferedReader br = new BufferedReader(new FileReader("P:/SD/Assignment1/results2.txt"));
while(line = br.readLine() != null)
{
strArr = line.split(":");
if(strArr.length==4){
if(strArr[1].trim().isEmpty()) errorCount++;
if(strArr[2].trim().isEmpty()) errorCount++;
if(strArr[3].trim().indexOf("x")>=0) errorCount++;
if(strArr[4].trim().indexOf("x")>=0) errorCount++;
}
}
}
catch(Exception e){
//error handling
}
System.out.println("Error count: "+errorCount);
}
}
UPDATE::
public void errorCount()
{
String line;
int errorCount=0;
String[] strArr;
String[] parts = line.split(":"); <--- ERROR IS HERE
if (parts.length != 4) {
errorCount++;
}
for (String part : parts) {
if (part.trim().isEmpty()) {
errorCount++;
break;
}
}
if (!(isNumeric(parts[2].trim()) && isNumeric(parts[3].trim()))) { //counts one error, otherwise, check each one of them and if both are not numeric, count this as two errors
errorCount++;
// continue with the following line
}
}
I would suggest something like that:
String line;
int errorCount=0;
String[] strArr;
try{
BufferedReader br = new BufferedReader(new FileReader(yourTextFile));
while((line = br.readLine()) != null){
strArr = line.split(":");
if(strArr.length==4){
if(strArr[0].trim().isEmpty()) errorCount++;
if(strArr[1].trim().isEmpty()) errorCount++;
if(strArr[2].trim().indexOf("x")>=0) errorCount++;
if(strArr[3].trim().indexOf("x")>=0) errorCount++;
}
else errorCount++;
}
}
catch(Exception e){
//error handling
}
System.out.println("Error count: "+errorCount);
You could check the lines against a regular expression. Each non matching line contains an error.
A starting point for the regular expression :
/(.+) : (.+) : (\d+) : (\d+)/
The parenthesis allow you to get the team names and the scores.
int errorCounter = 0; //initialize the errorCounter to zero
try{
BufferedReader br = new BufferedReader(new FileReader(yourTextFile));
while((line = br.readLine()) != null){ //read the file line by line
//Check that each line is split into 4 parts (delimited by ':')
String[] parts = line.split(":");
if (parts.length != 4) {
errorCounter++;
continue; //continue with the following line
}
// Then, check if some of the parts are null, like that:
for (String part : parts) {
if (part.trim().isEmpty()) {
errorCounter++;
}
}
//Finally, you can check if the last two parts contain numbers, using [this `isNumeric()` method][2], like that:
if (!(isNumeric(parts[2].trim())) { //checks if the third part is a number
errorCounter++;
}
if (!(isNumeric(parts[3].trim())) { //checks if the last part is numeric
errorCounter++;
}
} catch(IOException ex) {
System.err.println(ex);
}
The isNumeric() method can be found here.
Note that this solution counts multiple errors on the same line. If you want to count one error per line, you could simply use the one-liner that Lorenz Meyer suggests.