Hi I'm a beginner of Java lauguage.
It seems like my computer does not recognize FileReader at all.(Random class does not work either.) I typed the exact same code in a different computer and it worked. I uninstalled JDK and reinstalled it, but still doesn't work. I don't know what to do.
My environment
Samsung Netbook N150 plus. ///
windows 7 starter///
java(1.6_21 standard edition) ///
jGrasp(1.8).
Here is my code.
import java.io.*;
import java.util.*;
public class FileReaderGG
{
public static void main(String[] args)throws Exception
{
FileReader infile = new FileReader("todolist.txt");
Scanner indata = new Scanner(infile);
while (indata.hasNextLine())
{
System.out.println(indata.nextLine());
}
infile.close();
}
}
It gives me errors saying "cannot find symbol"
Looks like this
FileReaderGG.java:11: cannot find symbol
symbol : constructor FileReader(java.lang.String)
location: class FileReader
FileReader infile = new FileReader("todolist.txt");
5 more errors are there. I spent a whole day trying to figure out what the problem is.
Please help me out.
It means that you are trying to use a constructor that isn't there. Apparently you are trying to input a String into the constructor, but there is no constructor that accepts just a String value, but that is not true for java.io.FileReader. Is there another class in the same package (folder) called "FileReader"? If so, line 8 should be
java.io.FileReader infile = new java.io.FileReader("todolist.txt");
instead. Other solutions include
public class FileReaderGG
{
public static void main(String[] args) throws Exception
{
String pathName = System.getProperty("user.dir") + (FileReaderGG.class.getPackage() == null ? "" : "\\" + FileReaderGG.class.getPackage().getName().replace('.', '\\'));
java.io.FileReader infile = new java.io.FileReader(pathName + "\\todolist.txt");
java.util.Scanner indata = new java.util.Scanner(infile);
while (indata.hasNextLine())
{
System.out.println(indata.nextLine());
}
infile.close();
}
}
Note how no imports are made and all packages are explicitly declared. This should work no matter what. Just so you know, line 5 gets (A) the path from which the program is being run (hopefully the same as the resource file) and (B) checks if it is in a package and adds the needed sub-folders (though, it seems you aren't in any so it probably isn't needed)
I think your code is 100% right. Its working on my end at least. Are u compiling this program from IDE or from command line?
I think you have to import more, here's what I mean:
import java.util.Scanner;
import java.util.Scanner.*;
import java.io.FileReader;
import java.io.FileReader.*;
You know that when you
import java.util.Scanner;
It only imports the "Scanner" package, but not other packages in the Scanner package.
Related
How would I fix this issue?
I've completed the code but the only issue is that it keeps saying the variable cannot be found. For these listed below:
QueueArrayBased pQueue = new QueueArrayBased();
StackArrayBased pStack = new StackArrayBased();
I've already checked the naming which is identical to the class being called. I don't know what else to do. Please help I would greatly appreciate it. I have import java.util.*; because a source said that it would fix that issue and it didn't.
import java.util.Scanner;
import java.util.*;
public class isPalindrome
{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Word to check: ");
String userInput = sc.nextLine();
userInput = userInput.toUpperCase();
System.out.print(isPal(userInput)+" ");
}
public static boolean isPal(String str)
{
QueueArrayBased pQueue = new QueueArrayBased();
StackArrayBased pStack = new StackArrayBased();
for (int i = 0; i < str.length(); i++){
pQueue.enqueue(str.charAt(i));
pStack.push(str.charAt(i));
}
//start to compare
while(!pQueue.isEmpty())
{
if(pQueue.dequeue() != pStack.pop()){
return false;
}
}
//finished w/ empty queue (and empty stack)
return true;
}
}
You said you've implemented the classes already, so if you're getting this sort of error, your class must be in a different package. When you write a class in a different package from the one in which you want to use it, you have to import it into your current Java file. For example, if your QueueArrayBased and StackArrayBased classes are in a package called "structures," you would include import structures.QueueArrayBased and import structures.StackArrayBased (or just import structures.* to get both at once) among your import statements. Then, you can use the class freely.
I would recommend reviewing some Java project structure before moving on much farther. It'll make your life easier down the road. You can find a good explanation on packages and imports here.
So I'm coming back to Java after a long time of not working with it. First method of my first class and I'm seeing an error I've never seen before.
For every System.out.println() statement I have, the .out. part throws this error:
cannot find symbol
symbol: variable out
location: class System
my class is unfinished but looks like this
import java.io.*;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class System{
//Variables
char map[];
/*
Functions
FILE INPUT
*/
public static void ReadFile(){
FileInputStream fstream;
try{
fstream = new FileInputStream("C:\\Users\\James\\Documents\\NetBeansProjects\\Assignment1\\src\\testfiles");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
System.out.println("Your Input File");
System.out.println("****************");
//Read File Line By Line
while ((strLine = br.readLine()) != null)
{
// Print the content on the console
System.out.println(strLine);
inputArray.add(strLine);
}
System.out.println("****************");
//Close the input stream
br.close();
System.out.println();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
Every single .out. in this block of code throws this error :cannot find symbol
symbol: variable out
location: class System
I am using Netbeans8.0.2 and java 1.7.0_76(because I have to)
Can someone shed some light on this?
This is the problem:
public class System
You're creating your own class called System, so when you later use:
System.out.println
that's looking in your System class rather than java.lang.System.
Options:
Change the name of your class. It's generally a bad idea to create classes with the same name as classes within java.lang, precisely for this reason
Fully-qualify the call:
java.lang.System.out.println(...);
I'd pick the former option, personally.
Replace all the System.<something> with java.lang.System.<something>.
In its current state, your code is referencing your own System class. Since the name is the same, and yours has a higher priority in the scope, you end up with this error.
It's probably a better idea to change the name of your class. You generally don't want to conflict with internal names.
When you are using System.out.println() in the same class name System . So at the time of calling method println() your program searching the method in same class instead of checking same in java.lang. package.
So as for the solution of issue , either you can change the name of class to some thing else rather than System or you can change System.out.println() with java.lang.System.out.println().
I have already check on the net for 1 hour approximately and I cannot figure out why do I got this error message when I launch my program (the compilation seems to work perfectly).
(java.lang.NoSuchMethodError:
RequestHandler.verifyRequest(Ljava/util/ArrayList;)
I have a classe RequesHandler, with a method verifyRequest(ArrayList <String> req_lines)
Here is the code of my class:
import java.io.*;
import java.net.*;
import java.util.*;
class RequestHandler {
public boolean verifyRequest(ArrayList <String> req_lines) {
int nb = req_lines.size();
String first_line = req_lines.get(0);
if(!checkFirstLine(first_line))
return false;
.....
}
And here the lines invoking the method verifyRequest situated in a class Worker extends Thread which imports java.io.* java.net.* and java.util.*
ArrayList<String> req_lines = new ArrayList<String>();
RequestHandler rqhand = new RequestHandler();
while((line = in.readLine()) != null) {
line_nbr++;
req_lines.add(line);
msg += line + "\n\r";
}
boolean valid;
valid = rqhand.verifyRequest(req_lines);
I have read about copying but I don t think it is the problem in my case as I do not try to modify the elements of the array list in my code... Is that it ? I have also read about bad list initialisation but I think I did it well ...
Can somebody help me please ? Thanks a lot !
A common cause of this error is that there are two classes with the same name on the classpath. This can happen, for example, when you move classes from one project to another and forget to properly clean and build the original project or when you still use an old version of the original project's JAR.
I need to programmatically find out which JRE classes can be referenced in a compilation unit without being imported (for static code analysis). We can disregard package-local classes. According to the JLS, classes from the package java.lang are implicitly imported. The output should be a list of binary class names. The solution should work with plain Java 5 and up (no Guava, Reflections, etc.), and be vendor agnostic.
Any reliable Java-based solution is welcome.
Here are some notes on what I've tried so far:
At first glance, it seems that the question boils down to "How to load all classes from a package?", which is of course practically impossible, although several workarounds exist (e.g. this and this, plus the blog posts linked there). But my case is much simpler, because the multiple classloaders issue does not exist. java.lang stuff can always be loaded by the system/bootstrap classloader, and you cannot create your own classes in that package. Problem is, the system classloader does not divulge its class path, which the linked appoaches rely on.
So far, I haven't managed to get access to the system classloader's class path, because on the HotSpot VM I'm using, Object.class.getClassLoader() returns null, and Thread.currentThread().getContextClassLoader() can load java.lang.Object by delegation, but does not itself include the classpath. So solutions like this one don't work for me. Also, the list of guaranteed system properties does not include properties with this kind of classpath info (such as sun.boot.class.path).
It would be nice if I didn't have to assume that there is an rt.jar at all, and rather scan the list of resources used by the system classloader. Such an approach would be safer with respect to vendor specific JRE implementations.
Compiled classes appear to contain readable java/lang text. So I wrote a little bit of code to see if these imports can be extracted. It's a hack, so not reliable, but assuming you can extract/list all classes in a jar-file, this could be a starting point.
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
public class Q21102294 {
public static final String EXTERNAL_JAR = "resources/appboot-1.1.1.jar";
public static final String SAMPLE_CLASS_NAME = "com/descartes/appboot/AppBoot.class";
public static HashSet<String> usedLangClasses = new HashSet<String>();
public static void main(String[] args) {
try {
Path f = Paths.get(EXTERNAL_JAR);
if (!Files.exists(f)) {
throw new RuntimeException("Could not find file " + f);
}
URLClassLoader loader = new URLClassLoader(new URL[] { f.toUri().toURL() }, null);
findLangClasses(loader, SAMPLE_CLASS_NAME);
ArrayList<String> sortedClasses = new ArrayList<String>();
sortedClasses.addAll(usedLangClasses);
Collections.sort(sortedClasses);
System.out.println("Loaded classes: ");
for (String s : sortedClasses) {
System.out.println(s);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void findLangClasses(URLClassLoader loader, String classResource) throws Exception {
URL curl = loader.getResource(classResource);
if (curl != null) {
System.out.println("Got class as resource.");
} else {
throw new RuntimeException("Can't open resource.");
}
ByteArrayOutputStream bout = new ByteArrayOutputStream();
InputStream in = curl.openStream();
try {
byte[] buf = new byte[8192];
int l = 0;
while ((l = in.read(buf)) > -1) {
bout.write(buf, 0, l);
}
} finally {
in.close();
}
String ctext = new String(bout.toByteArray(), StandardCharsets.UTF_8);
int offSet = -1;
while ((offSet = ctext.indexOf("java/lang/", offSet)) > -1) {
int beginIndex = offSet;
offSet += "java/lang/".length();
char cnext = ctext.charAt(offSet);
while (cnext != ';' && (cnext == '/' || Character.isAlphabetic(cnext))) {
offSet += 1;
cnext = ctext.charAt(offSet);
}
String langClass = ctext.substring(beginIndex, offSet);
//System.out.println("adding class " + langClass);
usedLangClasses.add(langClass);
}
}
}
Gives the following output:
Got class as resource.
Loaded classes:
java/lang/Class
java/lang/ClassLoader
java/lang/Exception
java/lang/Object
java/lang/RuntimeException
java/lang/String
java/lang/StringBuilder
java/lang/System
java/lang/Thread
java/lang/Throwable
java/lang/reflect/Method
Source code of the used compiled class is available here.
OK, I misread the question. Checking the JLS, all I see is:
"Every compilation unit implicitly imports every public type name declared in the predefined package java.lang, as if the declaration import java.lang.*; appeared at the beginning of each compilation unit immediately after any package statement. As a result, the names of all those types are available as simple names in every compilation unit."
(http://docs.oracle.com/javase/specs/jls/se7/html/jls-7.html)
If you want to know which types that includes, it's going to vary from version to version of Java...
I came across the following code in a book recently. It says that we can reference a file for instance that we want to read by writing a command line like the first line below. However it is throwing an error with this line. Can someone please advise as I have never come across this before?
Thanks
java ShowFile c:/Users/Bosra/Desktop/Sample.txt
import java.io.*;
public class ShowFile
{
public static void main(String args[])
{
int i;
FileInputStream fin;
//first confirm that a filename has been specified
if(args.length!=1)
{
System.out.println("Usage:ShowFile Filename");
return;
}
}
}
The first line is the thing you should type in at the command line after compiling the file - it doesn't belong in the file itself.