why my constructor isn't working - java

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

Related

I am trying to write a method that will DETECT recursion in a file but am having trouble iterating through the methods of that file

This is what my recursion detector looks like (with an error of "The method contains(String) is undefined for Method Declaration" in if (md.contains(methodName))). I am not sure how I should change this to make it work. I hope to have some advice on what I could do to iterate through each individual method and check for its methodName in it. Thank you!
RecursionDetector.java
package detectors;
import java.awt.*;
import java.util.*;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.visitor.VoidVisitorAdapter;
public class RecursionDetector extends VoidVisitorAdapter <Breakpoints> {
#Override
public void visit(MethodDeclaration md, Breakpoints collector) {
String className = getClass().getName();
String methodName = md.getName().asString();
int startline = md.getRange().get().begin.line;
int endline = md.getRange().get().end.line;
final StackTraceElement[] trace = Thread.currentThread().getStackTrace();
if (md.contains(methodName)) {
}
for (int i=0; i < trace.length-1; i++) {
if( trace[i].equals(trace[trace.length-1]) ) {
super.visit(md, collector);
collector.addEmpty(className, methodName, startline, endline);
}
}
}
}
I also have a Breakpoints.java that looks like this:
package detectors;
import java.util.ArrayList;
public class Breakpoints {
private ArrayList<String> collector = new ArrayList<String>();
public Breakpoints() { }
public void addClass(String currentClass) { }
public void addMethod(String currentMethod) { }
public ArrayList<String> returnCollector() {
return new ArrayList<String>(this.collector);
}
public void addEmpty(String currentClass, String currentMethod, int startLine, int endLine) {
String n = ("className: " + currentClass + ", methodName: " + currentMethod + ", startline : " + startLine
+ ", endline : " + endLine + "\n");
if (collector.contains(n)) {
return;
}
collector.add(n);
}
}
And a Driver.java that looks like this:
package detectors;
import java.io.*;
import java.util.Scanner;
import com.github.javaparser.*;
import com.github.javaparser.ast.CompilationUnit;
public class Driver {
public static String data;
public static String data2 = "";
public static void main(String[] args) {
try {
File myFile = new File("/Users/weihanng/Desktop/Calculator.java");
Scanner myReader = new Scanner(myFile);
while (myReader.hasNextLine()) {
data = myReader.nextLine();
data2 = data2.concat(data);
}
myReader.close();
CompilationUnit cu = JavaParser.parse(myFile);
Breakpoints collector = new Breakpoints();
cu.accept(new RecursionDetector(), collector);
System.out.println("Recursions: ");
System.out.println(collector.returnCollector());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}

How to assign values to an ArrayList in a class?

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.

Read line from a text file and call the class to my main

I am learning super class, abstract class and abstract class, so I have to read a word from a file and depends of the word I found, make my program run one of three different methods. However, I got always this exception:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - incompatible types: int cannot be converted to java.lang.String
at encryption.EncryptorFactory.create(EncryptorFactory.java:23)
at superencryptor.SuperEncryptor.main(SuperEncryptor.java:15)
C:\Users\Linda\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53:
Here is my main package where I am trying to run the program:
package superencryptor;
import encryption.EncryptorFactory;
import encryption.*;
public class SuperEncryptor
{
public static void main(String[] args)
{
String strTestData = "This is a test";
/* V3 - using a factory */
EncryptorFactory obFactory = new EncryptorFactory();
IEncryptor obEncryptor = obFactory.create();
String strOutEnc = obEncryptor.encrypt(strTestData);
System.out.println("The encrypted value is: " + strOutEnc);
String strOutDec = obEncryptor.decrypt(strOutEnc);
System.out.println("The decrypted value is: " + strOutDec);
}
}
Here is the method I am trying to run:
package encryptor;
public class BasicEncryptor implements IEncryptor
{
#Override
public String encrypt(String strData) // "abc"
{
String strEncrypted = "";
for (int nIndex = 0; nIndex < strData.length(); ++nIndex)
{
strEncrypted += strData.charAt(nIndex);
strEncrypted += "#";
}
return strEncrypted;
}
#Override
public String decrypt(String strData) // "a#b#c#"
{
String strDecrypted = "";
// Start at the first character (index = 0) and add 2 to it each time
// through to skip the accompanying # symbol.
for (int nIndex = 0; nIndex < strData.length(); nIndex += 2)
{
strDecrypted += strData.charAt(nIndex);
}
return strDecrypted;
}
}
Here is my interface:
package encryptor;
public interface IEncryptor
{
public String encrypt(String strData);
public String decrypt(String strData);
}
And the factory class:
package encryptor;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class EncryptorFactory
{
public IEncryptor create() throws IOException
{
IEncryptor obEncryptor = null;
FileReader fileReader = new FileReader ( "C:\\config.dat");
try
{
BufferedReader br = new BufferedReader(fileReader);
String line = br.readLine();
if ( line.equals ("BasicEncrypto")&& br != null)
{
obEncryptor= new BasicEncryptor ();
}
br.close();
}
catch (IOException e)
{
System.err.println("Error: " + e);
}
catch (NumberFormatException e)
{
System.err.println("Invalid number");
}
return obEncryptor;
}
}
What you really need is add the class cast in your code to transfer the type of int to the type of string. Here is the example for you:
String sTest = Integer.toString(2);

Unable to access method in arraylist class from other classes in java

I have 2 class files in my simple project - sorry another newbee here!
But I get a compilation error on the last part where I am trying to print the hopefully stored configuration settings from a file for my project that will be referred to throughout the project.
The file is just rows of values like this 'ButtonConfig,8,V,NULL,bunny,mpg'
I basically want to be able to used the contents of this arraylist to dynamicly set up the configuration of a Raspberry pi GPO pins i.e. for the above values button attached to GPO pin 8 will play video (V) "<..other value...>_bunny.mpg"
Any help greatly appreciated - just telling me why I can't access the getExtension method would be nice!
Contents of first java file is -
package bpunit;
public class ButtonConfig {
private String keyword;
private String gponumber;
private String buttontype;
private String language;
private String filename;
private String extension;
public String getKeyword() {
return keyword;
}
public void setKeyword(String keyword) {
this.keyword = keyword;
}
...............
public String getExtension() {
return extension;
}
public void setExtension(String extension) {
this.extension = extension;
}
}
The second contains this -
package bpunit;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Read_ini {
public void Read_ini_toObject()
{
String csvFileToRead = "configs/BPUnit.properties";
BufferedReader br = null;
String line;
String splitBy = ",";
List buttonList = new ArrayList();
try {
br = new BufferedReader(new FileReader(csvFileToRead));
while ((line = br.readLine()) != null) {
// split on comma(',')
String[] buttonconfig = line.split(splitBy);
// create button object to store values
ButtonConfig buttonObject = new ButtonConfig();
// add values from csv to car object
buttonObject.setKeyword(buttonconfig[0]);
buttonObject.setGponumber(buttonconfig[1]);
buttonObject.setButtontype(buttonconfig[2]);
buttonObject.setLanguage(buttonconfig[3]);
buttonObject.setFilename(buttonconfig[4]);
buttonObject.setExtension(buttonconfig[5]);
// adding button object to a list
buttonList.add(buttonObject);
}
// print values stored in buttonList
printButtonList(buttonList);
} catch (FileNotFoundException e) {
System.out.print(e);
} catch (IOException e) {
System.out.print(e);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
System.out.print(e);
}
}
}
}
public void printButtonList(List buttonListToPrint) {
for (int i = 0; i < buttonListToPrint.size(); i++) {
// THE LINE BELOW FAILS - getExtension() does not exist
// and all other attempts give me pointer references
//instead of the text //
System.out.println(buttonListToPrint.get(i).getExtension());
}
}
}
You have to add the parameterized type ButtonConfig to your ArrayList. It ends up being List<ButtonConfig> instead of just List.
package bpunit;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Read_ini {
public void Read_ini_toObject()
{
String csvFileToRead = "configs/BPUnit.properties";
BufferedReader br = null;
String line;
String splitBy = ",";
List<ButtonConfig> buttonList = new ArrayList<ButtonConfig>();
try {
br = new BufferedReader(new FileReader(csvFileToRead));
while ((line = br.readLine()) != null) {
// split on comma(',')
String[] buttonconfig = line.split(splitBy);
// create button object to store values
ButtonConfig buttonObject = new ButtonConfig();
// add values from csv to car object
buttonObject.setKeyword(buttonconfig[0]);
buttonObject.setGponumber(buttonconfig[1]);
buttonObject.setButtontype(buttonconfig[2]);
buttonObject.setLanguage(buttonconfig[3]);
buttonObject.setFilename(buttonconfig[4]);
buttonObject.setExtension(buttonconfig[5]);
// adding button object to a list
buttonList.add(buttonObject);
}
// print values stored in buttonList
printButtonList(buttonList);
} catch (FileNotFoundException e) {
System.out.print(e);
} catch (IOException e) {
System.out.print(e);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
System.out.print(e);
}
}
}
}
public void printButtonList(List<ButtonConfig> buttonListToPrint) {
for (int i = 0; i < buttonListToPrint.size(); i++) {
// THE LINE BELOW FAILS - getExtension() does not exist
// and all other attempts give me pointer references
//instead of the text //
System.out.println(buttonListToPrint.get(i).getExtension());
}
}
}
The reason why the compilation is failing is because when you add an object to the ArrayList it is upcast as an object of the class Object. Now when you extract it you simply have to typecast it back to the original type. so all you have to do is this :
public void printButtonList(List buttonListToPrint) {
for (int i = 0; i < buttonListToPrint.size(); i++) {
// THE LINE BELOW FAILS - getExtension() does not exist
// and all other attempts give me pointer references
//instead of the text
ButtonConfig buttonObject =(ButtonConfig)buttonListToPrint.get(i);
System.out.println(buttonObject.getExtension());
}
}
Or as mentioned in the comments and answers above you could use generics and create an List of type ButtonConfig
public void Read_ini_toObject()
{
String csvFileToRead = "configs/BPUnit.properties";
BufferedReader br = null;
String line;
String splitBy = ",";
List<ButtonConfig> buttonList = new ArrayList<ButtonConfig>();
and pass it in the function printButtonList
public void printButtonList(List<ButtonConfig> buttonListToPrint) {
for (int i = 0; i < buttonListToPrint.size(); i++) {
// THE LINE BELOW FAILS - getExtension() does not exist
// and all other attempts give me pointer references
//instead of the text
System.out.println(buttonListToPrint.get(i).getExtension());
}
}

The method importTeams() is undefined for the type SchedulerOutput

I'm creating a scheduler in Java. I had everything inside in one class, but now I want to split it up into separate classes. It's quite small program, so there's likely little benefit, but I want to get the concepts of it correct. Code is below.
I'm getting an error in the second class on the importTeams() method. I thought that as long as I imported the package this method was in, it would be ok. Obviously not. Any tips?
package fifa.scheduler.fileimport;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
import fifa.scheduler.output.*;
public class FileRead2 {
private String rrTeam;
public List<String> importTeams() {
ArrayList<String> teamList = new ArrayList<String>();
BufferedReader br = null;
int linecount = 0;
String teamcounter;
try {
br = new BufferedReader(new FileReader("path"));
while (br.readLine() != null){
linecount ++;
}
br.close();
br = new BufferedReader(new FileReader("path"));
setRrTeam(br.readLine());
while ((teamcounter = br.readLine()) != null) {
teamList.add(teamcounter);
}
if (linecount % 2 != 0) {
teamList.add("byeteam");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
return teamList;
}
public static void main(String args[]){
FileRead2 fr = new FileRead2();
fr.PrintTeams();
}
private void setRrTeam(String rrTeam) {
this.rrTeam = rrTeam;
}
private String getRrTeam() {
return rrTeam;
}
}
package fifa.scheduler.output;
import java.util.Collections;
import java.util.List;
import fifa.scheduler.fileimport.FileRead2;
public class SchedulerOutput {
public void PrintTeams(){
List<String> teamList = importTeams();
int tl = teamList.size();
int bh = 0;
int uh = (tl - 2);
for (int i = 0; i <=(teamList.size()-1); i++) {
System.out.println("Week " + (i+1) + " fixtures");
System.out.println(getRrTeam() + " vs " + teamList.get(tl -1));
while ((bh <= (tl / 2)) && (uh >= ((tl / 2)))) {
System.out.println(teamList.get(bh) + " vs " + teamList.get(uh));
bh++;
uh--;
}
Collections.rotate(teamList, 1);
tl = teamList.size();
bh = 0;
uh = (tl - 2);
}
}
}
When you import the class using import statement, only the class's interface is imported. In order to call member methods, you need an instance of the class.
In your case, you should create an object of type FileRead2 to call the importTeams() method on it.
// Since FileRead2 has some member variable, you should also think about
// initializing it appropriately if it is needed by importTeams method.
FileRead2 fileRead2Obj = new FileRead2();
fileRead2Obj.importTeams();
Similarly, to call static methods, you need to qualify the method name with the class name (though Java 5+ allows static import of methods as well).
If importTeams() was static method, then you should call it as follows, after importing the class:
FileRead2.importTeams();

Categories

Resources