"cannot find symbol" despite correct variable name - java

In the following code snippet I really don't understand why the compiler is issuing
the "cannot find symbol" error message.
public class LU62XnsCvr extends Object
{
// these two variables (among many others) are declared here as "public"
static StringBuffer message_data = new StringBuffer();
static File Mesg_File = new File("C:\\...\\Mesg_File.txt"); // path snipped
public static void SendMesg() // This "method" is "called" from various
// sections of the LU62XnsCvr program
{
if (mesgcount == 1)
{
// On First call Connect the LU62XC Message File
FileOutputStream MesgOut = new FileOutputStream(Mesg_File);
FileChannel MesgChnl = MesgOut.getChannel();
ByteBuffer Mesg_Bufr = ByteBuffer.allocate(128);
}
// Send Message to the Message Log
String mesg_str = message_data.toString(); // convert buffer to a string
MesgWork = mesg_str.getBytes(); // Convert string to byte array
Mesg_Bufr.put( MesgWork, bufroffset, MGbuflen ); // copy MesgWork to buffer
MesgChnl.write( Mesg_Bufr ); // write message buffer out to the file channel
Mesg_Bufr.clear();
message_data.append(" "); // set message_data to 16 blanks
for ( ndx = 0; ndx < MGbuflen; ++ndx )
{
MesgWork[ndx] = 0x20; // clear MesgWork byte area using blank character
}
} // End of Send Message log write sub-routine
The above looks okay to me; BUT I get the following:
src\LU62XnsCvr.java:444: cannot find symbol
symbol : variable Mesg_Bufr
location: class APPC_LU62.java.LU62XnsCvr
Mesg_Bufr.put( MesgWork, bufroffset, MGbuflen );
^
src\LU62XnsCvr.java:445: cannot find symbol
symbol : variable Mesg_Bufr
location: class APPC_LU62.java.LU62XnsCvr
MesgChnl.write( Mesg_Bufr );
^
src\LU62XnsCvr.java:445: cannot find symbol
symbol : variable MesgChnl
location: class APPC_LU62.java.LU62XnsCvr
MesgChnl.write( Mesg_Bufr );
^
src\LU62XnsCvr.java:446: cannot find symbol
symbol : variable Mesg_Bufr
location: class APPC_LU62.java.LU62XnsCvr
Mesg_Bufr.clear();
^
Unless I'm missing something here it appears that Mesg_Bufr is "spelled" correctly.
Why can't the compiler "find" the variable?

You're declaring Mesg_Bufr in the if block so it's only visible in that block.
if (mesgcount == 1)
{
//On First call Connect the LU62XC Message File
FileOutputStream MesgOut = new FileOutputStream(Mesg_File) ;
FileChannel MesgChnl = MesgOut.getChannel() ;
ByteBuffer Mesg_Bufr = ByteBuffer.allocate(128) ;
}
Same goes for the others. I can't tell what you're trying to do (and tbh I don't care) but to make that run correctly you probably have to put all the code inside the if, or, better yet, return if mesg != 1.

Related

How to extract line with syntax error when parsing PlSQL using Antlr4

I am using the grammar file for PlSql from this Github repository. I want to underline the line in plsql file that I parse if it has a syntax error. I have the following snippet to do so:
public static class UnderlineListener extends BaseErrorListener {
public void syntaxError(Recognizer<?, ?> recognizer,
Object offendingSymbol,
int line, int charPositionInLine,
String msg,
RecognitionException e)
{
System.err.println("line "+line+":"+charPositionInLine+" "+msg);
underlineError(recognizer,(Token)offendingSymbol,
line, charPositionInLine);
}
protected void underlineError(Recognizer recognizer,
Token offendingToken, int line,
int charPositionInLine) {
CommonTokenStream tokens =
(CommonTokenStream)recognizer.getInputStream();
String input = tokens.getTokenSource().getInputStream().toString();
String[] lines = input.split("\n");
String errorLine = lines[line - 1];
System.err.println(errorLine);
for (int i=0; i<charPositionInLine; i++) System.err.print(" ");
int start = offendingToken.getStartIndex();
int stop = offendingToken.getStopIndex();
if ( start>=0 && stop>=0 ) {
for (int i=start; i<=stop; i++) System.err.print("^");
}
System.err.println();
}
}
While this works fine in most cases, some scripting languages, like PlSql, need special handling for case-sensitivity. This means I had to use CaseChangingCharStream as follows:
CharStream s = CharStreams.fromPath(Paths.get('test.sql'));
CaseChangingCharStream upper = new CaseChangingCharStream(s, true);
Lexer lexer = new SomeSQLLexer(upper);
Now when I try to get the input text inside my UnderlineListener using String input = tokens.getTokenSource().getInputStream().toString();, I do not get the actual text of my test.sql. This is because getInputStream() is returning CaseChangingCharStream object which does not give the desired actual text of my test.sql.
How do I get the actual file text in my case? One way could be to pass the file content to the the constructor of UnderlineListener, but I would prefer to stick to the above method of getting actual file text since it can be used for cases where CaseChangingCharStream is not used.
I have found a workaround. The current implementation of CaseChangingCharStream.java does not have a getter method, like getCharStream(), to access final CharStream stream; attribute. Simply adding a getter method for it allows us to access the underlying CharStream object as follows:
CaseChangingCharStream modifiedCharStream = (CaseChangingCharStream) tokens.getTokenSource().getInputStream();
String input = modifiedCharStream.getCharStream().toString();

Java: ClassNotFound Classpath issues

Im trying to read some information from a file into some objects. Main method just reads the Information into some string variables then uses those strings to initialize objects. Pretty simple. The objects are stored using a BST.
However, The error Im getting is ClassNotFoundException. Except when I run the java 'file' command, 'file' is spelled and capitalized correctly.
I've been reading that you can change the path that JVM uses when searching for class files.
so I tried:
set CLASSPATH=$CLASSPATH=~/../../BackEnd
but that didn't do anything..
Here is my main file..
import java.util.Scanner;
import java.io.File;
class BackEnd
{
public static void main(String args[]) throws java.io.FileNotFoundException
{
Tree.ServiceTree providers = new Tree.ServiceTree();
String path = "./providers.txt";
Scanner read = new Scanner (new File(path));
read.useDelimiter(",");
String information[] = new String[5];//array of strings used to store info from file, then used to initialize objects
try
{
while(read.hasNext())
{
for(int i = 0; i < 5; ++i)
{
information[i] = read.nextLine();//read in all the info into the array
}
Services.Service newService;//used as dynamic reference to be passed to tree
Services.Service serviceInfo = new Services.Service(information[0], information[1]);//initalizes base class to be passed to derived constructor
switch(information[0])//check type to initalize appropriate object
{
case "Dogwalk":
newService = new Services.Dogwalk(serviceInfo, information[2], information[3]);
case "Groceries":
newService = new Services.Groceries(serviceInfo, information[2], information[3]);
case "Housework":
newService = new Services.Housework(serviceInfo, information[2], information[3]);
}
providers.insert(information[4], newService);
}
read.close();
throw new java.io.FileNotFoundException("File not found...");
}
catch(java.io.FileNotFoundException exception)
{
System.out.println("File not found");
}
//providers.display();
}
}
Figured it out. Error had nothing to do with compilation or class path and was due
to uninitialized variable newService

`Cannot find symbol` when trying to access a property of a child class but the variable is of type superclass

Java noob here, I have a variable of type OutputStream and later on in the function I have a condition where I either assign OutputStream to a new instance of FileOutputStream or ByteArrayOutputStream, however whenever I try to access any property that belongs to any of the subclasses. I get a Error cannot find symbol.
Is there a way to keep the variable of the same parent class and try to tell the runtime that whenever I need to access the property it would be of the child's class type?
Here is some pseudo code
public void work(Map params)
{
OutputStream output = null;
if(params.isAFile)
{
output = new FileOutputStream();
}
else
{
output = new ByteArrayOutputStream();
}
...do some work that makes use of the OutputStreams class
if(isFile)
{
return output
}
else
{
mybuffer = output.buf; //it fails here with Cannot find symbol since output is of type OutputStream when it should be treated as type ByteArrayOutputStream
return myBuffer;
}
}
You have to cast it like this:
(ByteArrayOutputStream output).buf
Java doesn't know that it can safely call the method in ByteArrayOutputStream since OutputStream doesn't have that method.

How to fill an arraylist with an information from an array (java)

I am trying to create a program that reads from a txt file (this is the only thing in the file "5,5,5,0"). Then I want to take that information, put it in an array, then use that array to fill an array list. Then use that arraylist to write infromation into the file.
Here is what I have so far in my class file:
import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;
public void setMoney() throws IOException {
File moneyFile = new File ("Money.txt");
Scanner moneyScan = new Scanner(moneyFile);
String [] tokens = moneyFile.split(",");
ArrayList<Integer> money = new ArrayList<Integer>(Arrays.asList(tokens));
for(int i=0;i<tokens.length;i++){
money.append(tokens[i]);
}
String s = Integer.toString(tokens[i]);
FileOutputStream fos = new FileOutputStream("Money.txt");
fos.write(money);
fos.close();
}
Money.append is giving me this error:
error: cannot find symbol
money.append(tokens[i]);
^
symbol: method append(String)
location: variable money of type ArrayList
moneyFile.split is giving me this error:
error: cannot find symbol
String [] tokens = moneyFile.split(",");
^
symbol: method split(String)
location: variable moneyFile of type File
You have to use FileInputStream instead of File. Also, use the Scanner object you create in order to get the int values:
FileInputStream moneyFile = new FileInputStream("path/money.txt");
Scanner moneyScan = new Scanner(moneyFile);
moneyScan.useDelimiter(",");
ArrayList<Integer> money = new ArrayList<Integer>();
while(moneyScan.hasNextInt())
money.add(moneyScan.nextInt());
There are many ways to copy your data from Array to ArrayList:
The simplest one:
for (int i = 0; i < tokens.length; i++){
money.add(tokens[i]);
}
To parse your data to String
String s = Integer.toString(tokens[i]);
To write your data into a File:
FileOutputStream fos = new FileOutputStream(path_filename_extension);
fos.write(money);
fos.close();

Getting variables from another .java file using reflection

I've managed to get reflection working by getting and formatting the variables in the class that the toString() method is in.
public class ReadFile {
public int test1 =0;
public String test2 = "hello";
Boolean test3 = false;
int test4 = 1;
public static void main(String[] args) throws IOException{
ReadFile test = new ReadFile();
System.out.println(test);
}
public String toString(){
//Make a string builder so we can build up a string
StringBuilder result = new StringBuilder();
//Declare a new line constant
final String NEW_LINE = System.getProperty("line.separator");
//Gets the name of THIS Object
result.append(this.getClass().getName() );
result.append(" Class {" );
result.append(NEW_LINE);
//Determine fields declared in this class only (no fields of superclass)
Field[] fields = this.getClass().getDeclaredFields();
//Print field names paired with their values
for ( Field field : fields ) {
result.append(" ");
try {
result.append(field.getType() + " ");
result.append( field.getName() );
result.append(": ");
//requires access to private field:
result.append( field.get(this) );
} catch ( IllegalAccessException ex ) {
System.out.println(ex);
}
result.append(NEW_LINE);
}
result.append("}");
return result.toString();
}
}
However I was wondering whether it would be possible to specify a specific file in the directory for the toString() to work on?
I have tried getting a file and plugging it in the System.out.println() but the way I see it is you need to make an instance of a class and give it the instance for it to work. So I'm not sure how that can be done programatically.
I have been trying something like this:
Path path = FileSystems.getDefault().getPath("D:\\Directory\\Foo\\Bar\\Test.java", args);
File file = path.toFile();
System.out.println(file);
However I don't get very far with it, I've mainly been seeing if I can convert the file into anything usable but I'm not sure what I need to be doing!
Any advice would be great.
I think you need to look into the ClassLoader API - you need to get an new URLClassLoader and ask it to load your .java file into the JVM. You can then reflect on it.
You can try to read the package information from the file (D:\Directory\Foo\Bar\Test.java) and than try to load it the class by its name:
Class.forName(nameOfTheClass)
Java API Class

Categories