I'm getting some confusing errors when I iterate through this entire enable1 txt file (https://raw.githubusercontent.com/dolph/dictionary/master/enable1.txt) to check if it meets the "I before E except after C" English word 'rule'. I noticed the code succeeds when I remove the "-1" from charAt(indexEI - 1) that I starred below (****).
Any ideas why this might be? The errors just say "at java.lang.String.charAt (String.java: 658)", "Main.ibeforeE", and "at Main.main" in seemingly random spots in the "e" section of the iteration. Then it says var\cache\executor-snippets\run.xml:53: Java returned: 1 BUILD FAILED at the very end.
I'm quite new to Java so any other constructive criticism is appreciated as well. Thanks!
Main:
import java.util.Scanner;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
EnableWord test = new EnableWord();
test.EnableWords();
Scanner read = new Scanner(System.in);
ArrayList<String> list = new ArrayList<String>();
list = test.getList();
int x = 0;
int falseCounter = 0;
while (x < list.size()) {
System.out.print(list.get(x) + ": ");
String input = list.get(x);
if (input.equals("x")) {
break;
} else {
System.out.println(iBeforeE(input));
if(!iBeforeE(input)) {
falseCounter++;
}
x++;
}
}
System.out.println(falseCounter);
}
public static boolean iBeforeE(String input) {
if (!input.contains("ie") && !input.contains("ei")) {
return true;
}
if (input.contains("ie")) {
int indexIE = input.indexOf("ie");
Character searchIE = input.charAt(indexIE - 1);
if (!searchIE.toString().equals("c")) {
return true;
}
} else if (input.contains("ei")) {
int indexEI = input.indexOf("ei");
****Character searchEI = input.charAt(indexEI - 1);****
if (searchEI.toString().equals("c")) {
return true;
}
}
return false;
}
Class EnableWord:
}
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
public class EnableWord {
private ArrayList<String> list;
private Scanner s;
private File file;
public EnableWord() {
}
public void EnableWords() {
try {
this.s = new Scanner(this.file = new File("enable1.txt"));
} catch (FileNotFoundException ex) {
Logger.getLogger(EnableWord.class.getName()).log(Level.SEVERE, null, ex);
}
this.list = new ArrayList<>();
while (s.hasNext()) {
list.add(s.next());
}
s.close();
}
public void printWords() {
for (String word : list) {
System.out.println(word);
}
}
public ArrayList<String> getList() {
ArrayList<String> newList = new ArrayList<String>();
for (String word : list) {
newList.add(word);
}
return list;
}
}
There are words in your list that start with ei (ex: eicosanoid)
When your program gets to these words, it finds the index of 'ei' to be 0. So the value of "indexEI - 1" is negative 1, an invalid index.
you could fix it by checking if indexEI is > 0 before trying to check the previous character is a 'c':
if (indexEI == 0 || input.charAt(indexEI - 1).toString().equals("c")) {
return true;
}
As soon as a word starts with 'ie' or 'ei' then input.charAt(indexIE - 1) will generate an error since indexIE then is 0.
I am not sure what you want to do in your code but some kind of check is needed
if (indexIE == 0) {
} else {
//current code
}
Related
I have this code snippet that uses OpenCSV:
class Pojo {
#CsvBindByName(column="point")
Integer point;
#CsvBindByName(column="name")
String name;
}
And:
class Main {
readFile(){
CsvReader reader = new Csv(.....);
CsvToBean<Pojo> bean = new CsvToBeanBuilder<Pojo>(reader)...;
List<Pojo> list = bean.parse();
}
}
Why is it - while parsing - not considering header coming with zwnbsp and that column value I am getting as null?
Example input data:
ZWNBSPpoint
Not a real answer, yet a potential workaround for you, in case all CSV files to be processed share the extra zwnbsp character at the very beginning of the input (file).
In Pojo switch to:
#CsvBindByName(column="\uFEFFpoint")
Integer point;
Given input data
var input = "\uFEFFpoint,name\n1,A";
And
CSVReader csvReader = new CSVReader(new StringReader(input));
List<Pojo> beans = new CsvToBeanBuilder<Pojo>(csvReader)
.withType(Pojo.class)
.withIgnoreLeadingWhiteSpace(true)
.build()
.parse();
System.out.println(beans);
This will produce a valid Pojo[point = 1, name = A].
I tested the above scenario with OpenCSV version 5.7.1, with Java 17 under MacOS.
Without the above adjustment to the mapping annotation ("point" -> "\uFEFFpoint"), CSVReader will interpret the extra UTF-8 symbol \uFEFF as an extra character for the mapping to the field point which will produce a mismatch finally resulting in a non-populated field value.
However, it seems to be incorrect/invalid CSV input, as others already pointed out in the comments below your question. OpenCSV does not seem to have a flag or switch for HeaderColumnNameMappingStrategy to circumvent such cases as reported by you.
Apologies for misleading you and for some strange reason, missing the BOM problem. This is not extensively tested, but works:
package com.technojeeves.opencsvbeans;
import com.opencsv.bean.CsvToBeanBuilder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Objects;
import java.util.List;
import java.io.IOException;
import java.io.Reader;
import java.io.FilterReader;
public class App {
public static void main(String[] args) {
try {
System.out.println(new App().read(Path.of(args[0])));
} catch (Throwable t) {
t.printStackTrace();
}
}
public List<Pojo> read(Path path) {
try (Reader reader = new BomFilterReader(Files.newBufferedReader(path))) {
//try (Reader reader = Files.newBufferedReader(path)) {
return new CsvToBeanBuilder(reader).withType(Pojo.class).build().parse();
} catch (IOException e) {
throw new RuntimeException("Cannot read file: " + path.toFile().getName() + e);
}
}
}
class BomFilterReader extends FilterReader {
public static final char BOM = '\uFEFF';
private boolean haveReadBOM = false;
public BomFilterReader(Reader in) {
super(in);
}
#Override
public int read() throws IOException {
int c = super.read();
if (!haveReadBOM && ((char)c == BOM)) {
return super.read();
}
haveReadBOM = true;
return c;
}
#Override
public int read(char[] a) throws IOException {
return read(a, 0, a.length);
}
#Override
public int read(char a[], int off, int len) throws IOException {
Objects.checkFromIndexSize(off, len, a.length);
if (len == 0) {
return 0;
}
int c = read();
if (c == -1) {
return -1;
}
a[off] = (char) c;
int i = 1;
try {
for (; i < len; i++) {
c = read();
if (c == -1) {
break;
}
a[off + i] = (char) c;
}
} catch (IOException ee) {
}
return i;
}
}
I have text file data like :
2,2,1
data1,123,89,1
data2,124,90,2
data3,125,91,3
data4,126,92,4
data5,127,93,5
data6,128,94,6
data7,129,95,7
data8,130,96,8
data9,131,97,9
data10,132,98,10
The first line 2,2,1 indicate 2 lines from 1st set of lines and store it in nodeFile, 2 lines from 2nd set of lines store it in linkFile and 1 line from 3rd set of lines store it in moduleFile. However for example purpose I have shows small number of lines but its a larger file.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ReadFile {
static List<String> moduleFile = new ArrayList<>();
static List<String> linkFile = new ArrayList<>();
static List<String> nodeFile = new ArrayList<>();
static int a[];
public static void main(String[] args) {
File file11 = new File("/home/madhu/Desktop/node.txt");
Scanner scAll = null;
try {
scAll = new Scanner(file11);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String[] numberOfLines = (scAll.nextLine()).split(",");
int flag = 0;
int counter = 1;
while (scAll.hasNext()) {
if (flag == 0 && "\\n\\n".equals(scAll.nextLine()) && counter <= Integer.parseInt(numberOfLines[0].trim())) {
for (int i = 0; i < Integer.parseInt(numberOfLines[0].trim()); i++) {
System.out.println(scAll.nextLine());
nodeFile.add(scAll.nextLine());
counter++;
}
if (counter > Integer.parseInt(numberOfLines[0].trim())) {
flag = 1;
counter = 1;
}
} else if (flag == 1 && "\\n\\n".equals(scAll.nextLine())
&& counter <= Integer.parseInt(numberOfLines[1].trim())) {
for (int i = 0; i < Integer.parseInt(numberOfLines[1].trim()); i++) {
System.out.println(scAll.nextLine());
linkFile.add(scAll.nextLine());
counter++;
}
if (counter > Integer.parseInt(numberOfLines[1].trim())) {
flag = 2;
counter = 1;
}
} else if (flag == 2 && "\\n\\n".equals(scAll.nextLine())
&& counter <= Integer.parseInt(numberOfLines[2].trim())) {
for (int i = 0; i < Integer.parseInt(numberOfLines[2].trim()); i++) {
System.out.println(scAll.nextLine());
moduleFile.add(scAll.nextLine());
counter++;
}
} else {
continue;
}
}
scAll.close();
}
}
I have written the above code, but this code gets terminated during execution. How to get the desired result? Please help.
Hopefully I am not misunderstanding, but this is what I'd do.
I didn't check to see if this is fully working example, but it should work more or less.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
class ReadFile {
// basically just do what you did
static List<String> nodeFile;
static List<String> linkFile;
static List<String> moduleFile;
public static void main(String[] args) throws FileNotFoundException {
final File file = new File("/home/madhu/Desktop/node.txt");
final Scanner scanner = new Scanner(file);
// make it a little better for indexing
final List<Integer> selections = Arrays
.stream(scanner.nextLine().split(","))
.map(Integer::parseInt)
.collect(Collectors.toList());
// this is the meat of the code
// basically each split up block of lines is a block
final List<List<String>> blocks = new ArrayList<>();
while (scanner.hasNextLine()) {
List<String> lines = new ArrayList<>();
String line;
while (!(line = scanner.nextLine()).equals("\n")) {
lines.add(line);
}
if (!lines.isEmpty()) {
blocks.add(lines);
}
}
// allocate your files now
nodeFile = blocks.get(0).subList(0, selections.get(0));
linkFile = blocks.get(1).subList(0, selections.get(1));
moduleFile = blocks.get(2).subList(0, selections.get(2));
scanner.close();
}
}
try this code , i use BufferedReader because its more cleaner :
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ReadFile {
static List<String> moduleFile = new ArrayList<>();
static List<String> linkFile = new ArrayList<>();
static List<String> nodeFile = new ArrayList<>();
public static void main(String[] args) {
File file = new File("/home/madhu/Desktop/node.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String data[] = reader.readLine().split(",");
String s;
int nbline=0, i=0,block =0;
while ((s = reader.readLine())!=null && block < data.length) {
if(s.equals("")){
block++;
nbline = Integer.parseInt(data[block-1]);
i = 0;
}
for(;i<nbline;i++){
s = reader.readLine();
if(s == null) break;
else if(s.equals("")){
block++;
break;
}
switch(block){
case 1 :
nodeFile.add(s);
break;
case 2:
linkFile.add(s);
break;
default: moduleFile.add(s);
}
}
}
} catch (IOException | NumberFormatException ex) {
System.err.println(ex.getStackTrace());
}
finally{
closeReader(reader);
}
System.out.println("nodeFile : "+nodeFile);
System.out.println("linkFile : "+linkFile);
System.out.println("moduleFile : "+moduleFile);
}
public static void closeReader(BufferedReader reader) {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
}
}
}
}
output :
nodeFile : [data1,123,89,1, data2,124,90,2]
linkFile : [data5,127,93,5, data6,128,94,6]
moduleFile : [data8,130,96,8]
Every time the user logins.I'm reading till the SECOND LAST LINE OF THE FILE .I want to know what changes i need to make to the code so that i can read only till the second last line of the file.
public static boolean User(String usid) {
try {
String acc = usid;
File file = new File("C:\\Temp\\logs\\bank.log");
Scanner myReader = new Scanner(file);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
String[] substrings = data.split("[:]");
if (substrings[5].contains(acc) && substrings[4].contains("Login Successful for user")) {
a = true;
} else {
a = false;
}
}
} catch (Exception e) {
e.printStackTrace();
}
Could anyone please guide me what changes i need to make to the above code to read till the second last line of the file.[NOTE:-The contents of this file keeps adding once the user logins or logout.]
Try this, you can modify as per your requirement
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class Test{
public static boolean User(String usid) {
boolean a=false;
String fileName = "c://lines.txt";
List<String> list = new ArrayList<>();
String acc = usid;
try (BufferedReader br = Files.newBufferedReader(Paths.get(fileName))) {
//br returns as stream and convert it into a List
list = br.lines().collect(Collectors.toList());
for(int i=0; i<list.size()-1; i++){
String data = list.get(i);
String[] substrings = data.split("[:]");
if (substrings[5].contains(acc) && substrings[4].contains("Login Successful for user")) {
a = true;
} else {
a = false;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return a;
}
}
This is already answered at Link
I have been having trouble for the longest time on figuring out why you seemingly cannot assign values to an ArrayList without getting an error.
The first block of code is the main method which gets line by line from a textfile and splits the line using a delimiter. The first string is stored in one variable as a long, then other 9 strings are stored in an ArrayList. It does this for every line in the file.
I have debugged this code many times and it shows that the array is getting the right values.
The issues is when the code reaches the part where it calls insert, which I have commented in the code.
It first goes to create the node, but when it reaches the part when it is going to add the values from the first ArrayList to the newly created ArrayList, everything breaks. The for loop stops functioning as it should and it continues to increment even though the limit was reached.
I have decided to omit the BinaryTree Class which I also use for this project because it works as it should.
So how would I go about properly assigning the values from the ArrayList that I pass to the Node ArrayList?
package assignment7;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import static java.lang.Long.parseLong;
import java.util.Scanner;
import java.util.ArrayList;
public class Assignment7 {
public static void main(String[] args) throws IOException {
boolean headerLine = true;
String firstLine = "";
String catchLine;
String token;
long s_cid;
ArrayList<String> Arr = new ArrayList<String>();
Scanner delimS;
int count = 0;
BinaryTree snomedTree = new BinaryTree();
try(BufferedReader br = new BufferedReader(new FileReader("Data.txt"))) {
while ((catchLine = br.readLine()) != null) {
for(int i = 0; i < 9; i++){
Arr.add("");
}
if(headerLine){
firstLine = catchLine;
headerLine = false;
}
else{
delimS = new Scanner(catchLine);
delimS.useDelimiter("\\|");
s_cid = parseLong(delimS.next());
while(delimS.hasNext()){
token = delimS.next();
Arr.set(count, token);
count++;
}
//Runs fine up to here then this insert function is called
snomedTree.insert(new Node(s_cid, Arr));
}
Arr.clear();
}
}
try (PrintWriter writer = new PrintWriter("NewData.txt")) {
writer.printf(firstLine);
snomedTree.inorder(snomedTree.root, writer);
}
}
}
Here is the Node class:
package assignment7;
import java.util.ArrayList;
class Node {
public long cid;
public ArrayList<String> Satellite;
public Node l;
public Node r;
public Node(long cid, ArrayList<String> Sat) {
this.Satellite = new ArrayList<String>();
this.cid = cid;
//This for loop continues to run even after i = 9
for(int i = 0; 0 < 9; i++){
Satellite.add(Sat.get(i));
}
}
}
And this is the Binary Tree class:
package assignment7;
import java.util.ArrayList;
import java.io.PrintWriter;
public class BinaryTree {
public Node root;
public BinaryTree() {
this.root = null;
}
public void insert(Node x) {
if (root == null) {
root = x;
}
else {
Node current = root;
while (true) {
if (x.cid > current.cid) {
if (current.r == null) {
current.r = x;
break;
}
current = current.r;
}
else {
if (current.l == null) {
current.l = x;
break;
}
current = current.l;
}
}
}
}
public void inorder(Node x, PrintWriter out) {
if (x != null) {
inorder(x.l, out);
out.printf(String.valueOf(x.cid) + "|");
for(int i = 0; i < 9; i++){
if(i != 8){
out.printf(x.Satellite.get(i) + "|");
}
else{
out.printf(x.Satellite.get(i) + "\n");
}
}
inorder(x.r, out);
}
}
}
public Node(long cid, ArrayList<String> Sat) {
this.Satellite = new ArrayList<String>();
this.cid = cid;
for(int i = 0; i < Sat.size()-1; i++){
Satellite.add(Sat.get(i));
}
}
here 0<9 is wrong,
what error are u getting ??
Thanks to Miller Cy Chan's comment it works perfect now.
I changed the Node class to:
package assignment7;
import java.util.ArrayList;
import java.util.List;
class Node {
public long cid;
public ArrayList<String> Satellite;
public Node l;
public Node r;
public Node(long cid, ArrayList<String> Sat) {
this.Satellite = new ArrayList<String>(Sat.subList(0, Math.min(9, Sat.size())));
this.cid = cid;
}
}
I also made sure to change the "count" variable in the main back to 0 after each iteration.
I'm trying to make a program to print out a word ladder between any two words in the standard dictionary text file, but it keeps getting stuck on a single word. When I try "angel" and "demon", it's always "vegie".
Here's the code:
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Queue;
import java.util.LinkedList;
import java.util.Stack;
class WordLadder
{
static ArrayList words=new ArrayList();
public static void main(String[] args)
{
EasyReader dictFile=new EasyReader("C:\\dict.txt");
EasyReader input=new EasyReader();
String o;
while ((o = dictFile.readWord()) != null)
{
words.add(o.toLowerCase());
}
System.out.println("What is the starting word?");
String start=input.readLine();
System.out.println("What is the ending word?");
String end=input.readLine();
if(start.length()!=end.length())
{
System.out.println("The words have to be the same length!");
System.exit(0);
}
boolean isfound=false;
LinkedList q = new LinkedList();
LinkedList procq = new LinkedList();
Stack starter=new Stack();
starter.push(start);
q.add(starter);
ArrayList used=new ArrayList();
used.add(start);
while(!isfound)
{
Stack process=(Stack)q.removeLast();
System.out.println("finding one-offs for "+process.peek());
ArrayList oneoffs=findOneOffWords(process.peek().toString(), used);
System.out.println(oneoffs);
if(!oneoffs.isEmpty())
{
for(int i=0;i<oneoffs.size();i++)
{
Stack toproc=process;
System.out.println("processing stack: "+toproc);
toproc.add(oneoffs.get(i));
while(q.removeFirstOccurrence((Object)toproc))
{
}
boolean isused=false;
for (Object temp : used)
{
if(toproc.peek().toString().equalsIgnoreCase(temp.toString()))
{
isused=true;
}
}
if(!isused)
{
q.add(toproc);
}
used.add(oneoffs.get(i));
if(toproc.peek().toString().equalsIgnoreCase(end))
{
System.out.println("found solution!");
while(!toproc.empty())
{
System.out.println(toproc.pop().toString());
}
}
}
}
}
}
public static ArrayList findOneOffWords(String word, ArrayList used)
{
ArrayList oneoff=new ArrayList();
for(int i=0;i<167964;i++)
{
if(word.length()==words.get(i).toString().length())
{
int counter=0;
for(int h=0; h<word.length(); h++)
{
if(!word.substring(h,h+1).equalsIgnoreCase(words.get(i).toString().substring(h,h+1)))
{
counter++;
}
}
boolean isused=false;
for (Object temp : used)
{
if(words.get(i).toString().equalsIgnoreCase(temp.toString()))
{
isused=true;
}
}
if(counter==1&&isused==false)
{
oneoff.add(words.get(i));
}
}
}
return oneoff;
}
}