How to assign values to an ArrayList in a class? - java

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.

Related

Is there a way to get values of stocks to Java faster?

I made a simple java program that lets you create a stocks scanner/screener. There aren't many features yet, but there is a problem with existing features. I have a class that has a method that creates an array of all stock tickers and returns it. Here it is:
package classes;
import Utility.ArrayModification;
import variables.Ticker;
import java.io.*;
import java.util.Scanner;
public class Market {
public static Ticker[] getAllTickers() throws FileNotFoundException {
Ticker[] allTickers = {};
File currentDirectory = new File(new File("").getAbsolutePath());
String allTickersDirectory = currentDirectory + "\\src\\AllTickers.txt";
Scanner scanner = new Scanner(new File(allTickersDirectory));
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if(!(line.contains("^"))) {
allTickers = ArrayModification.appendTicker(allTickers, new Ticker(line));
}
}
return allTickers;
}
}
AllTickers.txt is a text file with the names of all tickers in it. I also have another class that stores a datatype, Ticker. Here it is:
package variables;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class Ticker {
private String savedSymbol;
public Ticker(String symbol) {
savedSymbol = symbol;
}
public String getTicker() {
return savedSymbol;
}
public Ticker setTicker(String symbol) {
savedSymbol = symbol;
return this;
}
public double getPrice() throws IOException {
try {
String stringURL = "https://markets.businessinsider.com/stocks/" + savedSymbol + "-stock";
URL url = new URL(stringURL);
URLConnection urlConn = url.openConnection();
InputStreamReader inStream = new InputStreamReader(urlConn.getInputStream());
BufferedReader buff = new BufferedReader(inStream);
String stringPrice = "-1";
String line = buff.readLine();
while (line != null) {
if (line.contains("price: ")) {
int target = line.indexOf("price: ");
int deci = line.indexOf(".", target);
int start = deci;
int stop = deci;
while (line.charAt(start) != ' ') {
start--;
}
while (line.charAt(stop) != ',') {
stop++;
}
stringPrice = line.substring(start + 1, stop);
break;
}
line = buff.readLine();
}
double price = Double.parseDouble(stringPrice);
return price;
}
catch(Exception e) {
return -1;
}
}
public double getMarketCap() throws IOException {
try {
String stringURL = "https://finviz.com/quote.ashx?t=" + savedSymbol;
URL url = new URL(stringURL);
URLConnection urlConn = url.openConnection();
InputStreamReader inStream = new InputStreamReader(urlConn.getInputStream());
BufferedReader buff = new BufferedReader(inStream);
String stringMarketCap = "-1";
double finalMarketCap = -1;
String line = buff.readLine();
while (line != null) {
if (line.contains(">Market Cap<")) {
int deci = line.indexOf(".");
int start = deci;
int stop = deci;
while (line.charAt(start) != '>') {
start--;
}
while (line.charAt(stop) != '<') {
stop++;
}
stringMarketCap = line.substring(start + 1, stop - 1);
double marketCap = Double.parseDouble(stringMarketCap);
if (line.charAt(stop - 1) == 'B') {
finalMarketCap = marketCap * 1000000000;
} else if (line.charAt(stop - 1) == 'M') {
finalMarketCap = marketCap * 1000000;
}
break;
}
line = buff.readLine();
}
return finalMarketCap;
}
catch(Exception e) {
return -1;
}
}
}
Using all of these, you can create a simple scanner that scans for stocks with a price of, for example, 0 - 15. You can do this by doing this:
import classes.Market;
import variables.Ticker;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
Ticker[] allTickers = Market.getAllTickers();
for(int i = 0; i< allTickers.length; i++){
Ticker ticker = allTickers[i];
if(ticker.getPrice() > 0 && ticker.getPrice() < 15) {
System.out.println(ticker.getTicker());
}
}
}
}
It prints out all of the qualifying stocks. However, it is EXTREMELY slow. So slow that it's basically unusable. It is this way because the ticker.getPrice() method has to connect to markets.businessinsider.com, extract the HTML code, find the correct index, and get the price for every single stock out of the 6000 in AllTIckers.txt. Would there be a way to do this faster?

Split with new line and store in datastructure

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]

CharAt index error while reading through text file in Java

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
}

why my constructor isn't working

I get enclosing instance of type error in my java code and i don't know what is that error my java code is below
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 phase45 {
public class Vertex {
public Vertex(Integer na){ name = na;}
private Integer name ;
public Integer getname(){
return name;
}
ArrayList adjs = new ArrayList<Integer>();
}
public class graph {
// public Integer name ;
ArrayList Vertexes = new ArrayList<Vertex>();
public Vertex GetVertex(Integer name){
for(int i = 0; i < Vertexes.size(); i++){
if (((Vertex) Vertexes.get(i)).name == name)
return (Vertex) Vertexes.get(i);
}
return null;
}
public void AddVertex(Vertex V){
Vertexes.add(V);
}
}
public static void CreateGraph(File a , graph g) throws IOException{
String st1 , st2 , line;
Integer vs , es;
try {
BufferedReader br = new BufferedReader(new FileReader(a));
st1 = br.readLine();
st2 = br.readLine();
vs = Integer.parseInt(st1);
es = Integer.parseInt(st2);
while ((line = br.readLine()) != null) {
String[] splited = line.split("\\s+");
//Vertex vTemp = null;
Integer NameV = Integer.valueOf(splited[0]);
System.out.println("line + " + line);
//vTemp.name = NameV;
Vertex vTemp = new Vertex(NameV);
Integer AdjV = Integer.valueOf(splited[1]);
vTemp.adjs.add(AdjV);
if(g.GetVertex(NameV) == null)
g.AddVertex(vTemp);
else
g.GetVertex(NameV).adjs.add(AdjV);
}
System.out.println("vs : " + vs + " es "+ es);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
//try{
File file = new File("/Users/mehran/Desktop/filee.txt");
graph g = null;
System.out.println("hi boy");
CreateGraph(file , g);
//}catch(NullPointerException ee){;}
}
}
I get error in CreateGraph this line : Vertex vTemp = new Vertex(NameV);
and I can't understand why , please fix it?
You try to use a C++-Constructor.
In Java you have to write:
Vertex vTemp = new Vertex(NameV); // Class-names should start with a capital letter
The code you attached here compile fine for me. I tried to compile the class Vertex and found it OK.
I think the problem occurred when you try to create object of this class. Try to create Vetex object like this -
Vetex v = new Vertex(name);
Here's a little edit to your code (of course you can instantiate adjs anywhere in your methods)
package test;
import java.util.ArrayList;
public class vertex {
private Integer name ;
public vertex(Integer na){ name = na;}
public Integer getname(){
return name;
}
public static void main(String[] args) {
ArrayList adjs = new ArrayList<Integer>();
}
}
the code compiled, but didn't want to run because you didn't add the main method

Word Ladder solving program broken

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;
}
}

Categories

Resources