Java System.out.println() throwing error - java

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().

Related

Passing ArrayList as method argument provides error java.lang.NoSuchMethodErro at launch

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.

Trouble finding solution to "variable might not have been initialized" error

My java program takes input from the user on the command line. The user has a choice: he may either specify a plain-text file as input with the -inputfile option, or he may leave this option unspecified, in which case the program takes input from System.in. (I've observed this behavior in some programs that come pre-installed with my Ubuntu distro, so I infer that it is acceptable practice.)
So I make a BufferedReader (inBR)that reads from the file, if provided, and a Scanner (inScanner) that reads from System.in otherwise. Only one of these objects is actually instantiated, the other is left as null. Later on, when the program reads a line from input, I have the following code:
String line;
if (inBR != null) {
line = inBR.readLine(); (1)
} else {
line = inScanner.nextLine(); (2)
}
Which gives me the compile time errors variable inBR might not have been initialized and variable inScanner might not have been initialized at lines (1) and (2), respectively.
What is the acceptable solution here? I've considered, "initialize the variable that's supposed to be null as an Object to shut up the compiler." But this is just a hack; surely there's a better way.
Also, why isn't this a runtime exception, as a NullPointerException?
EDIT: inScanner.readLine() => inScanner.nextLine()
Declaring them this way would avoid the compilation error :
BufferedReader inBR = null;
Scanner inScanner = null;
Of course you still have to give them actual values before accessing them, or you'll get NullPointerException.
In java all variables that are used must be initialized at some point.
public void example(){
String name;
if(name == null) return null;
}
In the above example the variable name has not been initialized. There are several ways to solve this problem:
public void example1(){
String name = null;
if(name == null) return null;
}
This would solve the problem.
This would also solve the problem
public void exapmle2(){
String name = "";
if(name == null) return null;
}
Make the condition whether or not a file is provided. For example, if a file is provided, create the buffered reader and set line immediately. Otherwise, create a scanner and set the line.

Using instance variable Linkedlist() in method - why do I have to make new in method body

this is my first post here. I have recently started to get interested in learning Java, I have read through some beginner level tutorials, kept http://docs.oracle.com as my bookmark and read several sample codes.
Now messing with my own for practice I discovered something weird for which I couldn't find any satisfying answer in manuals/tutorials/documentation.
Theres a little class I produced to practice IO, and queue style objects. It is meant to create an object containing file name, and an empty linkedlist. Then it has a method for that given file to be read and lines from that added one by one to the linkedlist queue.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.LinkedList;
public class Handle
{
public File filehandle;
public LinkedList<String> queue;
Handle (File filename)
{
filehandle=filename;
LinkedList<String> queue = new LinkedList<String>();
}
public void addq()
{
try{
FileReader ava;
ava = new FileReader(filehandle);
//without initializing new linekedlist queue it'll give NPE in queue.add
//why can't it use class/instance variable queue it does fine with filehandle
queue = new LinkedList<String>();
BufferedReader br = null;
String sCurrentLine;
br = new BufferedReader(ava);
while ((sCurrentLine = br.readLine()) != null)
{
queue.add(sCurrentLine);
}
queue.offer("POISON");
}
catch (IOException e) {e.printStackTrace();}
}
The weird thing - When tried to use class variable/instance variable queue (public LinkedList queue) declared in class, the one also initiated in constructor, inside the method, it compiled fine but at the runtime it threw NPE at queue.add lines. NPE faded as I initialized method variable queue inside method. Why can't the method add to class variable queue? It seems to use the fielhandle variable just fine!
Also as shown by the poll method result in code running the class(posting it down) - it still seems to actually add the lines into the instance variable queue not just temporary method variable. (Which is of course good but I do not understand how and why)
Down here is the code that I used to run the Handle class in.
import java.io.File;
import java.util.LinkedList;
class Runner
{
public static void main(String[] args)
{
File file = new File("proovidest.csv");
Handle handle =new Handle(file);
//using the constructor, now we have object with filehandle and empty queue variables
handle.addq();
String mison;
//so apparently the instance variable queue is still filled with lines (good)
//but how? the method had to delcare its own variable (why), but still the class field is //now filled? how?
while ((mison = handle.queue.poll()) != "POISON")
{System.out.println(mison);}
}
}
So can anybody give me good explanation why I couldn't acess the class variable queue in method in runtime, although I was able to use filehandle variable.
What SHOULD I do to access it then?
Can anybody tell me how the class field queue then still got filled, although I declared a new variable inside the method. Or does the handle.queue.poll somehow detect variables form methods?
The problem is here:
Handle (File filename) {
filehandle=filename;
LinkedList<String> queue = new LinkedList<String>();
}
You don't initialize the instance field queue, rather you create a new local variable with the same name, which is valid only in the constructor. Change it to:
Handle (File filename) {
filehandle=filename;
queue = new LinkedList<String>();
}
and it should not throw a NPE.
Inside your constructor, you declared a local variable queue, hiding your class variable!
Handle (File filename)
{
filehandle=filename;
this.queue = new LinkedList<String>();
}
The problem is the visibility of your LinkedList. It is only visible in your private constructor. To use the queue LinkedList just write this in your constructor:
queue = new LinkedList<String>();
furthermore remove that in addq:
queue = new LinkedList<String>();
Looks there is no place to fire NPE on your code.
It will fire File not found exception if mention file not in location.
Can you post stack trace to more investigations.

reading filename through command line argument

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.

Java FileReader error

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.

Categories

Resources